threejs-webvr-point-to-select-w-move.html 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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 w/Move</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 src="resources/threejs/r103/three.min.js"></script>
  23. <script src="resources/threejs/r103/js/vr/WebVR.js"></script>
  24. <script src="resources/threejs/r103/js/utils/SceneUtils.js"></script>
  25. <script>
  26. 'use strict';
  27. /* global THREE, WEBVR */
  28. function main() {
  29. const canvas = document.querySelector('#c');
  30. const renderer = new THREE.WebGLRenderer({canvas});
  31. renderer.vr.enabled = true;
  32. document.body.appendChild(WEBVR.createButton(renderer));
  33. const fov = 75;
  34. const aspect = 2; // the canvas default
  35. const near = 0.1;
  36. const far = 50;
  37. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  38. const scene = new THREE.Scene();
  39. {
  40. const loader = new THREE.CubeTextureLoader();
  41. const texture = loader.load([
  42. 'resources/images/grid-1024.png',
  43. 'resources/images/grid-1024.png',
  44. 'resources/images/grid-1024.png',
  45. 'resources/images/grid-1024.png',
  46. 'resources/images/grid-1024.png',
  47. 'resources/images/grid-1024.png',
  48. ]);
  49. scene.background = texture;
  50. }
  51. {
  52. const color = 0xFFFFFF;
  53. const intensity = 1;
  54. const light = new THREE.DirectionalLight(color, intensity);
  55. light.position.set(-1, 2, 4);
  56. scene.add(light);
  57. }
  58. const boxWidth = 1;
  59. const boxHeight = 1;
  60. const boxDepth = 1;
  61. const boxGeometry = new THREE.BoxBufferGeometry(boxWidth, boxHeight, boxDepth);
  62. const sphereRadius = 0.5;
  63. const sphereGeometry = new THREE.SphereBufferGeometry(sphereRadius);
  64. function makeInstance(geometry, color, x) {
  65. const material = new THREE.MeshPhongMaterial({color});
  66. const cube = new THREE.Mesh(geometry, material);
  67. scene.add(cube);
  68. cube.position.x = x;
  69. cube.position.y = 1.6;
  70. cube.position.z = -2;
  71. return cube;
  72. }
  73. const meshToMeshMap = new Map();
  74. [
  75. { x: 0, boxColor: 0x44aa88, sphereColor: 0xFF4444, },
  76. { x: 2, boxColor: 0x8844aa, sphereColor: 0x44FF44, },
  77. { x: -2, boxColor: 0xaa8844, sphereColor: 0x4444FF, },
  78. ].forEach((info) => {
  79. const {x, boxColor, sphereColor} = info;
  80. const sphere = makeInstance(sphereGeometry, sphereColor, x);
  81. const box = makeInstance(boxGeometry, boxColor, x);
  82. // hide the sphere
  83. sphere.visible = false;
  84. // map the sphere to the box
  85. meshToMeshMap.set(box, sphere);
  86. // map the box to the sphere
  87. meshToMeshMap.set(sphere, box);
  88. });
  89. class ControllerPickHelper extends THREE.EventDispatcher {
  90. constructor(scene) {
  91. super();
  92. this.raycaster = new THREE.Raycaster();
  93. this.objectToColorMap = new Map();
  94. this.controllerToObjectMap = new Map();
  95. this.tempMatrix = new THREE.Matrix4();
  96. const pointerGeometry = new THREE.BufferGeometry().setFromPoints([
  97. new THREE.Vector3(0, 0, 0),
  98. new THREE.Vector3(0, 0, -1),
  99. ]);
  100. this.controllers = [];
  101. const selectListener = (event) => {
  102. const controller = event.target;
  103. const selectedObject = this.controllerToObjectMap.get(event.target);
  104. if (selectedObject) {
  105. this.dispatchEvent({type: event.type, controller, selectedObject});
  106. }
  107. };
  108. const endListener = (event) => {
  109. const controller = event.target;
  110. this.dispatchEvent({type: event.type, controller});
  111. };
  112. for (let i = 0; i < 2; ++i) {
  113. const controller = renderer.vr.getController(i);
  114. controller.addEventListener('select', selectListener);
  115. controller.addEventListener('selectstart', selectListener);
  116. controller.addEventListener('selectend', endListener);
  117. scene.add(controller);
  118. const line = new THREE.Line(pointerGeometry);
  119. line.scale.z = 5;
  120. controller.add(line);
  121. this.controllers.push({controller, line});
  122. }
  123. }
  124. reset() {
  125. // restore the colors
  126. this.objectToColorMap.forEach((color, object) => {
  127. object.material.emissive.setHex(color);
  128. });
  129. this.objectToColorMap.clear();
  130. this.controllerToObjectMap.clear();
  131. }
  132. update(scene, time) {
  133. this.reset();
  134. for (const {controller, line} of this.controllers) {
  135. // cast a ray through the from the controller
  136. this.tempMatrix.identity().extractRotation(controller.matrixWorld);
  137. this.raycaster.ray.origin.setFromMatrixPosition(controller.matrixWorld);
  138. this.raycaster.ray.direction.set(0, 0, -1).applyMatrix4(this.tempMatrix);
  139. // get the list of objects the ray intersected
  140. const intersections = this.raycaster.intersectObjects(scene.children);
  141. if (intersections.length) {
  142. const intersection = intersections[0];
  143. // make the line touch the object
  144. line.scale.z = intersection.distance;
  145. // pick the first object. It's the closest one
  146. const pickedObject = intersection.object;
  147. // save which object this controller picked
  148. this.controllerToObjectMap.set(controller, pickedObject);
  149. // highlight the object if we haven't already
  150. if (this.objectToColorMap.get(pickedObject) === undefined) {
  151. // save its color
  152. this.objectToColorMap.set(pickedObject, pickedObject.material.emissive.getHex());
  153. // set its emissive color to flashing red/yellow
  154. pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFF2000 : 0xFF0000);
  155. }
  156. } else {
  157. line.scale.z = 5;
  158. }
  159. }
  160. }
  161. }
  162. const controllerToSelection = new Map();
  163. const pickHelper = new ControllerPickHelper(scene);
  164. pickHelper.addEventListener('selectstart', (event) => {
  165. const {controller, selectedObject} = event;
  166. const existingSelection = controllerToSelection.get(controller);
  167. if (!existingSelection) {
  168. controllerToSelection.set(controller, {
  169. object: selectedObject,
  170. parent: selectedObject.parent,
  171. });
  172. THREE.SceneUtils.detach(selectedObject, selectedObject.parent, scene);
  173. THREE.SceneUtils.attach(selectedObject, scene, controller);
  174. }
  175. });
  176. pickHelper.addEventListener('selectend', (event) => {
  177. const {controller} = event;
  178. const selection = controllerToSelection.get(controller);
  179. if (selection) {
  180. controllerToSelection.delete(controller);
  181. THREE.SceneUtils.detach(selection.object, controller, scene);
  182. THREE.SceneUtils.attach(selection.object, scene, selection.parent);
  183. }
  184. });
  185. function resizeRendererToDisplaySize(renderer) {
  186. const canvas = renderer.domElement;
  187. const width = canvas.clientWidth;
  188. const height = canvas.clientHeight;
  189. const needResize = canvas.width !== width || canvas.height !== height;
  190. if (needResize) {
  191. renderer.setSize(width, height, false);
  192. }
  193. return needResize;
  194. }
  195. function render(time) {
  196. time *= 0.001;
  197. if (!renderer.vr.isPresenting() && resizeRendererToDisplaySize(renderer)) {
  198. const canvas = renderer.domElement;
  199. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  200. camera.updateProjectionMatrix();
  201. }
  202. let ndx = 0;
  203. for (const mesh of meshToMeshMap.keys()) {
  204. const speed = 1 + ndx * .1;
  205. const rot = time * speed;
  206. mesh.rotation.x = rot;
  207. mesh.rotation.y = rot;
  208. ++ndx;
  209. }
  210. pickHelper.update(scene, time);
  211. renderer.render(scene, camera);
  212. }
  213. renderer.setAnimationLoop(render);
  214. }
  215. main();
  216. </script>
  217. </html>