File size: 10,731 Bytes
a25a0c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae9d177
a25a0c5
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Babylon.js 3D VR Game</title>
    <style>
        body, html { margin: 0; padding: 0; overflow: hidden; font-family: 'Trebuchet MS', serif; }
        canvas { width: 100%; height: 100%; display: block; }
        #chatUI { position: absolute; top: 10px; right: 10px; width: 300px; }
        #chatLog { width: 100%; height: 400px; background-color: rgba(0, 0, 0, 0.7); padding: 10px; color: #fff; overflow-y: auto; border: 2px solid #4e342e; box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.9); }
        #chatInput { width: 100%; height: 40px; margin-top: 10px; background-color: rgba(255, 255, 255, 0.4); border: 2px solid #4e342e; }
        #sendButton { width: 100%; height: 40px; margin-top: 10px; background: linear-gradient(to bottom, #957d5f, #6c543e); color: #e0d7c5; border: none; cursor: pointer; }
    </style>
</head>

<body>
    <canvas id="renderCanvas"></canvas>
    <div id="chatUI">
        <div id="chatLog"></div>
        <input type="text" id="chatInput" placeholder="Type your message here..." />
        <button id="sendButton">Send</button>
    </div>

    <script src="https://cdn.babylonjs.com/babylon.js"></script>
    <script src="https://cdn.babylonjs.com/loaders/babylon.glTF2FileLoader.min.js"></script>
    <script src="https://unpkg.com/@huggingface/transformers"></script>

    <script>
        // Setup Babylon.js
        const canvas = document.getElementById("renderCanvas");
        const engine = new BABYLON.Engine(canvas, true);

        const createScene = function() {
            const scene = new BABYLON.Scene(engine);

            // Skybox setup
            scene.environmentTexture = new BABYLON.CubeTexture("sky.jpg", scene);

            // Camera
            const camera = new BABYLON.ArcRotateCamera("Camera", Math.PI / 2, Math.PI / 2, 100, BABYLON.Vector3.Zero(), scene);
            camera.attachControl(canvas, true);

            // Light
            const light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(1, 1, 0), scene);

            // Load maps
            const mapMatrix = generateRandomMap();
            const mapWidth = mapMatrix[0].length;
            const mapHeight = mapMatrix.length;

            // Ground setup with the same size as the map
            const ground = BABYLON.MeshBuilder.CreateGround("ground", { width: mapWidth, height: mapHeight }, scene);
            ground.material = new BABYLON.StandardMaterial("groundMat", scene);
            ground.material.diffuseTexture = new BABYLON.Texture("sky.jpg", scene);

            // Position ground underneath the map
            ground.position.x = mapWidth / 2 - 0.5;
            ground.position.z = mapHeight / 2 - 0.5;

            // Create map
            createMapFromMatrix(mapMatrix, scene);

            // Player
            const startPosition = getStartPosition(mapMatrix);
            const player = BABYLON.MeshBuilder.CreateBox("player", { size: 1 }, scene);
            player.position = new BABYLON.Vector3(startPosition.x, 0.5, startPosition.z);
            player.material = new BABYLON.StandardMaterial("playerMat", scene);
            player.material.diffuseTexture = new BABYLON.Texture("sky.jpg", scene);

            // NPC - Red Sphere
            const npcPosition = getRandomFreePosition(mapMatrix);
            const npc = BABYLON.MeshBuilder.CreateSphere("npc", { diameter: 1 }, scene);
            npc.position = new BABYLON.Vector3(npcPosition.x, 0.5, npcPosition.z);
            npc.material = new BABYLON.StandardMaterial("npcMat", scene);
            npc.material.diffuseColor = new BABYLON.Color3(1, 0, 0); // Red color

            // Basic movement
            window.addEventListener("keydown", (event) => {
                switch (event.key) {
                    case "ArrowUp":
                        player.position.z -= 0.1;
                        break;
                    case "ArrowDown":
                        player.position.z += 0.1;
                        break;
                    case "ArrowLeft":
                        player.position.x -= 0.1;
                        break;
                    case "ArrowRight":
                        player.position.x += 0.1;
                        break;
                }
            });

            return scene;
        };

        function generateRandomMap() {
            const size = 100;
            const map = [];
            for (let y = 0; y < size; y++) {
                const row = [];
                for (let x = 0; x < size; x++) {
                    row.push(Math.random() > 0.8 ? 1 : 0); // 1 for wall, 0 for empty
                }
                map.push(row);
            }
            return map;
        }

        function createMapFromMatrix(matrix, scene) {
            const wallMaterial = new BABYLON.StandardMaterial("wallMat", scene);
            wallMaterial.diffuseTexture = new BABYLON.Texture("sky.jpg", scene);

            matrix.forEach((row, y) => {
                row.forEach((value, x) => {
                    if (value === 1) {
                        const wall = BABYLON.MeshBuilder.CreateBox("wall_" + x + "_" + y, {
                            width: 1,
                            height: 2,
                            depth: 1
                        }, scene);
                        wall.position = new BABYLON.Vector3(x, 1, y);
                        wall.material = wallMaterial;
                    }
                });
            });
        }

        function getStartPosition(matrix) {
            for (let y = 0; y < matrix.length; y++) {
                for (let x = 0; x < matrix[y].length; x++) {
                    if (matrix[y][x] === 0) {
                        return { x, z: y }; // Starting position
                    }
                }
            }
            return { x: 0, z: 0 }; // Default position if none found
        }

        function getRandomFreePosition(matrix) {
            let x, z;
            do {
                x = Math.floor(Math.random() * matrix[0].length);
                z = Math.floor(Math.random() * matrix.length);
            } while (matrix[z][x] !== 0); // Ensure the position is free (no wall)
            return { x, z };
        }

        const scene = createScene();
        engine.runRenderLoop(() => {
            scene.render();
        });

        window.addEventListener("resize", () => {
            engine.resize();
        });

        async function createXRExperience() {
            try {
                const xrHelper = await scene.createDefaultXRExperienceAsync({
                    floorMeshes: [scene.getMeshByName("ground")],
                    disableDefaultUI: false // Keep the default UI enabled to ensure the VR button works
                });

                // After initialization, specifically disable hand tracking if it was included
                const featuresManager = xrHelper.baseExperience.featuresManager;
                featuresManager.disableFeature(BABYLON.WebXRFeatureName.HAND_TRACKING);

                // Set up interactions
                setupControllerInteractions(xrHelper);
                scene.activeCamera = xrHelper.baseExperience.camera;

            } catch (err) {
                console.error('Failed to start VR session:', err);
            }
        }

        // Set up VR button and initialize VR experience on click
        const vrButton = document.createElement("button");
        vrButton.textContent = "Enter VR";
        vrButton.style.position = "absolute";
        vrButton.style.bottom = "10px";
        vrButton.style.left = "10px";
        vrButton.style.width = "200px";
        vrButton.style.height = "40px";
        vrButton.style.background = "linear-gradient(to bottom, #6c543e, #4e342e)";
        vrButton.style.color = "#e0d7c5";
        vrButton.style.border = "none";
        vrButton.style.cursor = "pointer";
        document.body.appendChild(vrButton);

        vrButton.addEventListener("click", createXRExperience);

        function setupControllerInteractions(xrHelper) {
            xrHelper.input.onControllerAddedObservable.add(controller => {
                controller.onMotionControllerInitObservable.add(motionController => {
                    const xrRay = motionController.getComponent("xr-standard-trigger");

                    if (xrRay) {
                        let isProcessing = false; // Debounce flag

                        xrRay.onButtonStateChangedObservable.add(() => {
                            if (xrRay.pressed && !isProcessing) {
                                isProcessing = true;

                                // Use a try-catch block to handle any unexpected errors
                                try {
                                    const pickResult = scene.pickWithRay(controller.pointerRay);

                                    if (pickResult.hit && pickResult.pickedMesh) {
                                        if (pickResult.pickedMesh.name === "npc") {
                                            alert("You win!"); // Alert the player that they have won
                                        }
                                    }
                                } catch (err) {
                                    console.error('Error during ray interaction:', err);
                                } finally {
                                    // Allow further interactions after a short delay
                                    setTimeout(() => {
                                        isProcessing = false;
                                    }, 200); // Adjust delay as necessary
                                }
                            }
                        });
                    }
                });
            });
        }

        // Ensure the camera controls are reset when exiting VR mode
        window.addEventListener("resize", () => {
            engine.resize();
        });

        async function setupChat() {
            try {
                const model = await transformers.AutoModelForCausalLM.from_pretrained('mistralai/Mistral');
                const tokenizer = await transformers.AutoTokenizer.from_pretrained('mistralai/Mistral');
                return { model, tokenizer };
            } catch (error) {
                console.error('Failed to load the chat model or tokenizer:', error);
                //alert('Chat system is currently unavailable. Please try again later.');
                return null;
            }
        }

        let chatSetup = setupChat();
    </script>
</body>

</html>