webgl_raycaster_bvh.html 8.0 KB

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