webgl_batch_lod_bvh.html 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js raycaster - batch - lod - 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. a {
  10. text-decoration: underline;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <div id="info">
  16. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> batch lod bvh - <a href="https://github.com/agargaro/batched-mesh-extensions" target="_blank" rel="noopener">@three.ez/batched-mesh-extensions</a><br/>
  17. BatchedMesh with 10 geometries and 500k instances. Each geometry has 5 LODs (4 generated with meshoptimizer). <br>
  18. Frustum culling and raycasting are accelerated by using BVHs (TLAS & BLAS). <br>
  19. See <a href="https://github.com/agargaro/batched-mesh-extensions" target="_blank" rel="noopener">main project repository</a> for more information and examples on BatchedMesh extensions.
  20. </div>
  21. <script type="importmap">
  22. {
  23. "imports": {
  24. "three": "../build/three.module.js",
  25. "three/addons/": "./jsm/",
  26. "three-mesh-bvh": "https://cdn.jsdelivr.net/npm/three-mesh-bvh@0.9.0/build/index.module.js",
  27. "@three.ez/batched-mesh-extensions": "https://cdn.jsdelivr.net/npm/@three.ez/batched-mesh-extensions@0.0.8/build/webgl.js",
  28. "bvh.js": "https://cdn.jsdelivr.net/npm/bvh.js@0.0.13/build/index.js",
  29. "@three.ez/simplify-geometry": "https://cdn.jsdelivr.net/npm/@three.ez/simplify-geometry@0.0.1/build/index.js",
  30. "meshoptimizer": "https://cdn.jsdelivr.net/npm/meshoptimizer@0.23.0/+esm"
  31. }
  32. }
  33. </script>
  34. <script type="module">
  35. import * as THREE from 'three';
  36. import Stats from 'three/addons/libs/stats.module.js';
  37. import { MapControls } from 'three/addons/controls/MapControls.js';
  38. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  39. import { acceleratedRaycast, computeBatchedBoundsTree } from 'three-mesh-bvh';
  40. import { createRadixSort, extendBatchedMeshPrototype, getBatchedMeshLODCount } from '@three.ez/batched-mesh-extensions';
  41. import { performanceRangeLOD, simplifyGeometriesByErrorLOD } from '@three.ez/simplify-geometry';
  42. // add and override BatchedMesh methods ( @three.ez/batched-mesh-extensions )
  43. extendBatchedMeshPrototype();
  44. // add the extension functions ( three-mesh-bvh )
  45. THREE.Mesh.prototype.raycast = acceleratedRaycast;
  46. THREE.BatchedMesh.prototype.computeBoundsTree = computeBatchedBoundsTree;
  47. let stats;
  48. let camera, scene, renderer;
  49. const instancesCount = 500000;
  50. let batchedMesh;
  51. let lastHoveredInstance = null;
  52. const lastHoveredColor = new THREE.Color();
  53. const yellow = new THREE.Color( 'yellow' );
  54. const raycaster = new THREE.Raycaster();
  55. const mouse = new THREE.Vector2( 1, 1 );
  56. const position = new THREE.Vector3();
  57. const quaternion = new THREE.Quaternion();
  58. const scale = new THREE.Vector3( 1, 1, 1 );
  59. const matrix = new THREE.Matrix4();
  60. const color = new THREE.Color();
  61. init();
  62. async function init() {
  63. // environment
  64. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.1, 600 );
  65. camera.position.set( 0, 10, 50 );
  66. scene = new THREE.Scene();
  67. scene.fog = new THREE.Fog( 0x000000, 500, 600 );
  68. const ambient = new THREE.AmbientLight();
  69. scene.add( camera, ambient );
  70. const dirLight = new THREE.DirectionalLight( 'white', 2 );
  71. camera.add( dirLight, dirLight.target );
  72. // renderer
  73. renderer = new THREE.WebGLRenderer( { antialias: true } );
  74. renderer.setPixelRatio( window.devicePixelRatio );
  75. renderer.setSize( window.innerWidth, window.innerHeight );
  76. document.body.appendChild( renderer.domElement );
  77. raycaster.firstHitOnly = true;
  78. stats = new Stats();
  79. document.body.appendChild( stats.dom );
  80. const controls = new MapControls( camera, renderer.domElement );
  81. controls.maxPolarAngle = Math.PI / 2;
  82. const geometries = [
  83. new THREE.TorusKnotGeometry( 1, 0.4, 256, 32, 1, 1 ),
  84. new THREE.TorusKnotGeometry( 1, 0.4, 256, 32, 1, 2 ),
  85. new THREE.TorusKnotGeometry( 1, 0.4, 256, 32, 1, 3 ),
  86. new THREE.TorusKnotGeometry( 1, 0.4, 256, 32, 1, 4 ),
  87. new THREE.TorusKnotGeometry( 1, 0.4, 256, 32, 1, 5 ),
  88. new THREE.TorusKnotGeometry( 1, 0.4, 256, 32, 2, 1 ),
  89. new THREE.TorusKnotGeometry( 1, 0.4, 256, 32, 2, 3 ),
  90. new THREE.TorusKnotGeometry( 1, 0.4, 256, 32, 3, 1 ),
  91. new THREE.TorusKnotGeometry( 1, 0.4, 256, 32, 4, 1 ),
  92. new THREE.TorusKnotGeometry( 1, 0.4, 256, 32, 5, 3 )
  93. ];
  94. // generate 4 LODs (levels of detail) for each geometry
  95. const geometriesLODArray = await simplifyGeometriesByErrorLOD( geometries, 4, performanceRangeLOD );
  96. // create BatchedMesh
  97. const { vertexCount, indexCount, LODIndexCount } = getBatchedMeshLODCount( geometriesLODArray );
  98. batchedMesh = new THREE.BatchedMesh( instancesCount, vertexCount, indexCount, new THREE.MeshStandardMaterial( { metalness: 0.2, roughness: 0.2 } ) );
  99. // enable radix sort for better performance
  100. batchedMesh.customSort = createRadixSort( batchedMesh );
  101. // add geometries and their LODs to the batched mesh ( all LODs share the same position array )
  102. for ( let i = 0; i < geometriesLODArray.length; i ++ ) {
  103. const geometryLOD = geometriesLODArray[ i ];
  104. const geometryId = batchedMesh.addGeometry( geometryLOD[ 0 ], - 1, LODIndexCount[ i ] );
  105. batchedMesh.addGeometryLOD( geometryId, geometryLOD[ 1 ], 15 );
  106. batchedMesh.addGeometryLOD( geometryId, geometryLOD[ 2 ], 75 );
  107. batchedMesh.addGeometryLOD( geometryId, geometryLOD[ 3 ], 125 );
  108. batchedMesh.addGeometryLOD( geometryId, geometryLOD[ 4 ], 200 );
  109. }
  110. // place instances in a 2D grid with randomized rotation and color
  111. const sqrtCount = Math.ceil( Math.sqrt( instancesCount ) );
  112. const size = 5.5;
  113. const start = ( sqrtCount / - 2 * size ) + ( size / 2 );
  114. for ( let i = 0; i < instancesCount; i ++ ) {
  115. const r = Math.floor( i / sqrtCount );
  116. const c = i % sqrtCount;
  117. const id = batchedMesh.addInstance( Math.floor( Math.random() * geometriesLODArray.length ) );
  118. position.set( c * size + start, 0, r * size + start );
  119. quaternion.random();
  120. batchedMesh.setMatrixAt( id, matrix.compose( position, quaternion, scale ) );
  121. batchedMesh.setColorAt( id, color.setHSL( Math.random(), 0.6, 0.5 ) );
  122. }
  123. // compute blas (bottom-level acceleration structure) bvh ( three-mesh-bvh )
  124. batchedMesh.computeBoundsTree();
  125. // compute tlas (top-level acceleration structure) bvh ( @three.ez/batched-mesh-extensions )
  126. batchedMesh.computeBVH( THREE.WebGLCoordinateSystem );
  127. scene.add( batchedMesh );
  128. // set up gui
  129. const config = {
  130. freeze: false,
  131. useBVH: true,
  132. useLOD: true
  133. };
  134. const bvh = batchedMesh.bvh;
  135. const lods = batchedMesh._geometryInfo.map( x => x.LOD );
  136. const onBeforeRender = batchedMesh.onBeforeRender;
  137. const gui = new GUI();
  138. gui.add( batchedMesh, 'instanceCount' ).disable();
  139. gui.add( config, 'freeze' ).onChange( v => {
  140. batchedMesh.onBeforeRender = v ? () => {} : onBeforeRender;
  141. } );
  142. const frustumCullingFolder = gui.addFolder( 'Frustum culling & raycasting' );
  143. frustumCullingFolder.add( config, 'useBVH' ).onChange( v => {
  144. batchedMesh.bvh = v ? bvh : null;
  145. } );
  146. const geometriesFolder = gui.addFolder( 'Geometries' );
  147. geometriesFolder.add( config, 'useLOD' ).onChange( v => {
  148. const geometryInfo = batchedMesh._geometryInfo;
  149. for ( let i = 0; i < geometryInfo.length; i ++ ) {
  150. geometryInfo[ i ].LOD = v ? lods[ i ] : null;
  151. }
  152. } );
  153. document.addEventListener( 'pointermove', onPointerMove );
  154. window.addEventListener( 'resize', onWindowResize );
  155. onWindowResize();
  156. renderer.setAnimationLoop( animate );
  157. }
  158. function onPointerMove( event ) {
  159. event.preventDefault();
  160. mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
  161. mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
  162. raycast();
  163. }
  164. function onWindowResize() {
  165. camera.aspect = window.innerWidth / window.innerHeight;
  166. camera.updateProjectionMatrix();
  167. renderer.setSize( window.innerWidth, window.innerHeight );
  168. }
  169. function raycast() {
  170. raycaster.setFromCamera( mouse, camera );
  171. const intersection = raycaster.intersectObject( batchedMesh );
  172. const batchId = intersection.length > 0 ? intersection[ 0 ].batchId : null;
  173. if ( lastHoveredInstance === batchId ) return;
  174. if ( lastHoveredInstance ) {
  175. batchedMesh.setColorAt( lastHoveredInstance, lastHoveredColor );
  176. }
  177. if ( batchId ) {
  178. batchedMesh.getColorAt( batchId, lastHoveredColor );
  179. batchedMesh.setColorAt( batchId, yellow );
  180. }
  181. lastHoveredInstance = batchId;
  182. }
  183. function animate() {
  184. stats.begin();
  185. renderer.render( scene, camera );
  186. stats.end();
  187. }
  188. </script>
  189. </body>
  190. </html>
粤ICP备19079148号