webxr-point-to-select.html 6.9 KB

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