webgl_raycaster_bvh.html 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js raycaster - bvh</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. <style>
  9. body {
  10. background-color: #eeeeee;
  11. color: #333;
  12. }
  13. a {
  14. color: #E91E63;
  15. text-decoration: underline;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <div id="info">
  21. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> raycaster - <a href="https://github.com/gkjohnson/three-mesh-bvh" target="_blank" rel="noopener">three-mesh-bvh</a><br/>
  22. See <a href="https://github.com/gkjohnson/three-mesh-bvh" target="_blank" rel="noopener">main project repository</a> for more information and examples on high performance spatial queries.
  23. </div>
  24. <!-- Import maps polyfill -->
  25. <!-- Remove this when import maps will be widely supported -->
  26. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  27. <script type="importmap">
  28. {
  29. "imports": {
  30. "three": "../build/three.module.js",
  31. "three/addons/": "./jsm/",
  32. "three-mesh-bvh": "https://unpkg.com/three-mesh-bvh@^0.5.21/build/index.module.js"
  33. }
  34. }
  35. </script>
  36. <script type="module">
  37. import * as THREE from 'three';
  38. import { computeBoundsTree, disposeBoundsTree, acceleratedRaycast, MeshBVHVisualizer } from 'three-mesh-bvh';
  39. import Stats from 'three/addons/libs/stats.module.js';
  40. import { FBXLoader } from 'three/addons/loaders/FBXLoader.js';
  41. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  42. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  43. THREE.ColorManagement.enabled = true;
  44. // Add the extension functions
  45. THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree;
  46. THREE.BufferGeometry.prototype.disposeBoundsTree = disposeBoundsTree;
  47. THREE.Mesh.prototype.raycast = acceleratedRaycast;
  48. let stats;
  49. let camera, scene, renderer;
  50. let mesh, helper, bvh;
  51. let sphereInstance, lineSegments;
  52. // reusable variables
  53. const _raycaster = new THREE.Raycaster();
  54. const _position = new THREE.Vector3();
  55. const _quaternion = new THREE.Quaternion();
  56. const _scale = new THREE.Vector3( 1, 1, 1 );
  57. const _matrix = new THREE.Matrix4();
  58. const _axis = new THREE.Vector3();
  59. const MAX_RAYS = 3000;
  60. const RAY_COLOR = 0x444444;
  61. const params = {
  62. count: 150,
  63. firstHitOnly: true,
  64. useBVH: true,
  65. displayHelper: false,
  66. helperDepth: 10,
  67. };
  68. init();
  69. animate();
  70. function init() {
  71. // environment
  72. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 100 );
  73. camera.position.z = 10;
  74. scene = new THREE.Scene();
  75. scene.background = new THREE.Color( 0xeeeeee );
  76. const ambient = new THREE.HemisphereLight( 0xffffff, 0x999999 );
  77. scene.add( ambient );
  78. // renderer
  79. renderer = new THREE.WebGLRenderer( { antialias: true } );
  80. renderer.setPixelRatio( window.devicePixelRatio );
  81. renderer.setSize( window.innerWidth, window.innerHeight );
  82. renderer.outputEncoding = THREE.sRGBEncoding;
  83. document.body.appendChild( renderer.domElement );
  84. stats = new Stats();
  85. document.body.appendChild( stats.dom );
  86. // raycast visualizations
  87. const lineGeometry = new THREE.BufferGeometry();
  88. lineGeometry.setAttribute( 'position', new THREE.BufferAttribute( new Float32Array( MAX_RAYS * 2 * 3 ), 3 ) );
  89. lineSegments = new THREE.LineSegments( lineGeometry, new THREE.LineBasicMaterial( {
  90. color: RAY_COLOR,
  91. transparent: true,
  92. opacity: 0.25,
  93. depthWrite: false
  94. } ) );
  95. sphereInstance = new THREE.InstancedMesh(
  96. new THREE.SphereGeometry(),
  97. new THREE.MeshBasicMaterial( { color: RAY_COLOR } ),
  98. 2 * MAX_RAYS
  99. );
  100. sphereInstance.instanceMatrix.setUsage( THREE.DynamicDrawUsage );
  101. sphereInstance.count = 0;
  102. scene.add( sphereInstance, lineSegments );
  103. // load the bunny
  104. const loader = new FBXLoader();
  105. loader.load( 'models/fbx/stanford-bunny.fbx', object => {
  106. mesh = object.children[ 0 ];
  107. const geometry = mesh.geometry;
  108. geometry.translate( 0, 0.5 / 0.0075, 0 );
  109. geometry.computeBoundsTree();
  110. bvh = geometry.boundsTree;
  111. if ( ! params.useBVH ) {
  112. geometry.boundsTree = null;
  113. }
  114. scene.add( mesh );
  115. mesh.scale.setScalar( 0.0075 );
  116. helper = new MeshBVHVisualizer( mesh );
  117. helper.color.set( 0xE91E63 );
  118. scene.add( helper );
  119. } );
  120. const controls = new OrbitControls( camera, renderer.domElement );
  121. controls.minDistance = 5;
  122. controls.maxDistance = 75;
  123. // set up gui
  124. const gui = new GUI();
  125. const rayFolder = gui.addFolder( 'Raycasting' );
  126. rayFolder.add( params, 'count', 1, MAX_RAYS, 1 );
  127. rayFolder.add( params, 'firstHitOnly' );
  128. rayFolder.add( params, 'useBVH' ).onChange( v => {
  129. mesh.geometry.boundsTree = v ? bvh : null;
  130. } );
  131. const helperFolder = gui.addFolder( 'BVH Helper' );
  132. helperFolder.add( params, 'displayHelper' );
  133. helperFolder.add( params, 'helperDepth', 1, 20, 1 ).onChange( v => {
  134. helper.depth = v;
  135. helper.update();
  136. } );
  137. window.addEventListener( 'resize', onWindowResize );
  138. onWindowResize();
  139. initRays();
  140. }
  141. function initRays() {
  142. const position = new THREE.Vector3();
  143. const quaternion = new THREE.Quaternion();
  144. const scale = new THREE.Vector3( 1, 1, 1 );
  145. const matrix = new THREE.Matrix4();
  146. for ( let i = 0; i < MAX_RAYS * 2; i ++ ) {
  147. position.randomDirection().multiplyScalar( 3.75 );
  148. matrix.compose( position, quaternion, scale );
  149. sphereInstance.setMatrixAt( i, matrix );
  150. }
  151. }
  152. function updateRays() {
  153. if ( ! mesh ) return;
  154. _raycaster.firstHitOnly = params.firstHitOnly;
  155. const rayCount = params.count;
  156. let lineNum = 0;
  157. for ( let i = 0; i < rayCount; i ++ ) {
  158. // get the current ray origin
  159. sphereInstance.getMatrixAt( i * 2, _matrix );
  160. _matrix.decompose( _position, _quaternion, _scale );
  161. // rotate it about the origin
  162. const offset = 1e-4 * window.performance.now();
  163. _axis.set(
  164. Math.sin( i * 100 + offset ),
  165. Math.cos( - i * 10 + offset ),
  166. Math.sin( i * 1 + offset ),
  167. ).normalize();
  168. _position.applyAxisAngle( _axis, 0.001 );
  169. // update the position
  170. _scale.setScalar( 0.02 );
  171. _matrix.compose( _position, _quaternion, _scale );
  172. sphereInstance.setMatrixAt( i * 2, _matrix );
  173. // raycast
  174. _raycaster.ray.origin.copy( _position );
  175. _raycaster.ray.direction.copy( _position ).multiplyScalar( - 1 ).normalize();
  176. // update hits points and lines
  177. const hits = _raycaster.intersectObject( mesh );
  178. if ( hits.length !== 0 ) {
  179. const hit = hits[ 0 ];
  180. const point = hit.point;
  181. _scale.setScalar( 0.01 );
  182. _matrix.compose( point, _quaternion, _scale );
  183. sphereInstance.setMatrixAt( i * 2 + 1, _matrix );
  184. lineSegments.geometry.attributes.position.setXYZ( lineNum ++, _position.x, _position.y, _position.z );
  185. lineSegments.geometry.attributes.position.setXYZ( lineNum ++, point.x, point.y, point.z );
  186. } else {
  187. sphereInstance.setMatrixAt( i * 2 + 1, _matrix );
  188. lineSegments.geometry.attributes.position.setXYZ( lineNum ++, _position.x, _position.y, _position.z );
  189. lineSegments.geometry.attributes.position.setXYZ( lineNum ++, 0, 0, 0 );
  190. }
  191. }
  192. sphereInstance.count = rayCount * 2;
  193. sphereInstance.instanceMatrix.needsUpdate = true;
  194. lineSegments.geometry.setDrawRange( 0, lineNum );
  195. lineSegments.geometry.attributes.position.needsUpdate = true;
  196. }
  197. function onWindowResize() {
  198. camera.aspect = window.innerWidth / window.innerHeight;
  199. camera.updateProjectionMatrix();
  200. renderer.setSize( window.innerWidth, window.innerHeight );
  201. }
  202. function animate() {
  203. requestAnimationFrame( animate );
  204. render();
  205. stats.update();
  206. }
  207. function render() {
  208. if ( helper ) {
  209. helper.visible = params.displayHelper;
  210. }
  211. if ( mesh ) {
  212. mesh.rotation.y += 0.002;
  213. mesh.updateMatrixWorld();
  214. }
  215. updateRays();
  216. renderer.render( scene, camera );
  217. }
  218. </script>
  219. </body>
  220. </html>