threejs-webvr-point-to-select.html 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. <!-- Licensed under a BSD license. See license.html for license -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
  7. <title>Three.js - WebVR - Point to Select</title>
  8. <style>
  9. body {
  10. margin: 0;
  11. }
  12. #c {
  13. width: 100vw;
  14. height: 100vh;
  15. display: block;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <canvas id="c"></canvas>
  21. </body>
  22. <script type="module">
  23. import * as THREE from './resources/threejs/r110/build/three.module.js';
  24. import {WEBVR} from './resources/threejs/r110/examples/jsm/vr/WebVR.js';
  25. function main() {
  26. const canvas = document.querySelector('#c');
  27. const renderer = new THREE.WebGLRenderer({canvas});
  28. renderer.vr.enabled = true;
  29. document.body.appendChild(WEBVR.createButton(renderer));
  30. const fov = 75;
  31. const aspect = 2; // the canvas default
  32. const near = 0.1;
  33. const far = 50;
  34. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  35. const scene = new THREE.Scene();
  36. {
  37. const loader = new THREE.CubeTextureLoader();
  38. const texture = loader.load([
  39. 'resources/images/grid-1024.png',
  40. 'resources/images/grid-1024.png',
  41. 'resources/images/grid-1024.png',
  42. 'resources/images/grid-1024.png',
  43. 'resources/images/grid-1024.png',
  44. 'resources/images/grid-1024.png',
  45. ]);
  46. scene.background = texture;
  47. }
  48. {
  49. const color = 0xFFFFFF;
  50. const intensity = 1;
  51. const light = new THREE.DirectionalLight(color, intensity);
  52. light.position.set(-1, 2, 4);
  53. scene.add(light);
  54. }
  55. const boxWidth = 1;
  56. const boxHeight = 1;
  57. const boxDepth = 1;
  58. const boxGeometry = new THREE.BoxBufferGeometry(boxWidth, boxHeight, boxDepth);
  59. const sphereRadius = 0.5;
  60. const sphereGeometry = new THREE.SphereBufferGeometry(sphereRadius);
  61. function makeInstance(geometry, color, x) {
  62. const material = new THREE.MeshPhongMaterial({color});
  63. const cube = new THREE.Mesh(geometry, material);
  64. scene.add(cube);
  65. cube.position.x = x;
  66. cube.position.y = 1.6;
  67. cube.position.z = -2;
  68. return cube;
  69. }
  70. const meshToMeshMap = new Map();
  71. [
  72. { x: 0, boxColor: 0x44aa88, sphereColor: 0xFF4444, },
  73. { x: 2, boxColor: 0x8844aa, sphereColor: 0x44FF44, },
  74. { x: -2, boxColor: 0xaa8844, sphereColor: 0x4444FF, },
  75. ].forEach((info) => {
  76. const {x, boxColor, sphereColor} = info;
  77. const sphere = makeInstance(sphereGeometry, sphereColor, x);
  78. const box = makeInstance(boxGeometry, boxColor, x);
  79. // hide the sphere
  80. sphere.visible = false;
  81. // map the sphere to the box
  82. meshToMeshMap.set(box, sphere);
  83. // map the box to the sphere
  84. meshToMeshMap.set(sphere, box);
  85. });
  86. class ControllerPickHelper extends THREE.EventDispatcher {
  87. constructor(scene) {
  88. super();
  89. this.raycaster = new THREE.Raycaster();
  90. this.objectToColorMap = new Map();
  91. this.controllerToObjectMap = new Map();
  92. this.tempMatrix = new THREE.Matrix4();
  93. const pointerGeometry = new THREE.BufferGeometry().setFromPoints([
  94. new THREE.Vector3(0, 0, 0),
  95. new THREE.Vector3(0, 0, -1),
  96. ]);
  97. this.controllers = [];
  98. for (let i = 0; i < 2; ++i) {
  99. const controller = renderer.vr.getController(i);
  100. controller.addEventListener('select', (event) => {
  101. const controller = event.target;
  102. const selectedObject = this.controllerToObjectMap.get(controller);
  103. if (selectedObject) {
  104. this.dispatchEvent({type: 'select', controller, selectedObject});
  105. }
  106. });
  107. scene.add(controller);
  108. const line = new THREE.Line(pointerGeometry);
  109. line.scale.z = 5;
  110. controller.add(line);
  111. this.controllers.push({controller, line});
  112. }
  113. }
  114. reset() {
  115. // restore the colors
  116. this.objectToColorMap.forEach((color, object) => {
  117. object.material.emissive.setHex(color);
  118. });
  119. this.objectToColorMap.clear();
  120. this.controllerToObjectMap.clear();
  121. }
  122. update(scene, time) {
  123. this.reset();
  124. for (const {controller, line} of this.controllers) {
  125. // cast a ray through the from the controller
  126. this.tempMatrix.identity().extractRotation(controller.matrixWorld);
  127. this.raycaster.ray.origin.setFromMatrixPosition(controller.matrixWorld);
  128. this.raycaster.ray.direction.set(0, 0, -1).applyMatrix4(this.tempMatrix);
  129. // get the list of objects the ray intersected
  130. const intersections = this.raycaster.intersectObjects(scene.children);
  131. if (intersections.length) {
  132. const intersection = intersections[0];
  133. // make the line touch the object
  134. line.scale.z = intersection.distance;
  135. // pick the first object. It's the closest one
  136. const pickedObject = intersection.object;
  137. // save which object this controller picked
  138. this.controllerToObjectMap.set(controller, pickedObject);
  139. // highlight the object if we haven't already
  140. if (this.objectToColorMap.get(pickedObject) === undefined) {
  141. // save its color
  142. this.objectToColorMap.set(pickedObject, pickedObject.material.emissive.getHex());
  143. // set its emissive color to flashing red/yellow
  144. pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFF2000 : 0xFF0000);
  145. }
  146. } else {
  147. line.scale.z = 5;
  148. }
  149. }
  150. }
  151. }
  152. const pickHelper = new ControllerPickHelper(scene);
  153. pickHelper.addEventListener('select', (event) => {
  154. event.selectedObject.visible = false;
  155. const partnerObject = meshToMeshMap.get(event.selectedObject);
  156. partnerObject.visible = true;
  157. });
  158. function resizeRendererToDisplaySize(renderer) {
  159. const canvas = renderer.domElement;
  160. const width = canvas.clientWidth;
  161. const height = canvas.clientHeight;
  162. const needResize = canvas.width !== width || canvas.height !== height;
  163. if (needResize) {
  164. renderer.setSize(width, height, false);
  165. }
  166. return needResize;
  167. }
  168. function render(time) {
  169. time *= 0.001;
  170. if (!renderer.vr.isPresenting() && resizeRendererToDisplaySize(renderer)) {
  171. const canvas = renderer.domElement;
  172. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  173. camera.updateProjectionMatrix();
  174. }
  175. let ndx = 0;
  176. for (const mesh of meshToMeshMap.keys()) {
  177. const speed = 1 + ndx * .1;
  178. const rot = time * speed;
  179. mesh.rotation.x = rot;
  180. mesh.rotation.y = rot;
  181. ++ndx;
  182. }
  183. pickHelper.update(scene, time);
  184. renderer.render(scene, camera);
  185. }
  186. renderer.setAnimationLoop(render);
  187. }
  188. main();
  189. </script>
  190. </html>