webgl_mesh_batch.html 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - mesh - batch</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. #info {
  10. background-color: rgba(0,0,0,0.75);
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <div id="info">
  16. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> webgl - mesh - batch
  17. </div>
  18. <script type="importmap">
  19. {
  20. "imports": {
  21. "three": "../build/three.module.js",
  22. "three/addons/": "./jsm/"
  23. }
  24. }
  25. </script>
  26. <script type="module">
  27. import * as THREE from 'three';
  28. import Stats from 'three/addons/libs/stats.module.js';
  29. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  30. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  31. import { radixSort } from 'three/addons/utils/SortUtils.js';
  32. let stats, gui, guiStatsEl;
  33. let camera, controls, scene, renderer;
  34. let geometries, mesh, material;
  35. const ids = [];
  36. const matrix = new THREE.Matrix4();
  37. //
  38. const position = new THREE.Vector3();
  39. const rotation = new THREE.Euler();
  40. const quaternion = new THREE.Quaternion();
  41. const scale = new THREE.Vector3();
  42. //
  43. const MAX_GEOMETRY_COUNT = 20000;
  44. const Method = {
  45. BATCHED: 'BATCHED',
  46. NAIVE: 'NAIVE'
  47. };
  48. const api = {
  49. method: Method.BATCHED,
  50. count: 256,
  51. dynamic: 16,
  52. sortObjects: true,
  53. perObjectFrustumCulled: true,
  54. opacity: 1,
  55. useCustomSort: true,
  56. };
  57. init();
  58. initGeometries();
  59. initMesh();
  60. animate();
  61. //
  62. function randomizeMatrix( matrix ) {
  63. position.x = Math.random() * 40 - 20;
  64. position.y = Math.random() * 40 - 20;
  65. position.z = Math.random() * 40 - 20;
  66. rotation.x = Math.random() * 2 * Math.PI;
  67. rotation.y = Math.random() * 2 * Math.PI;
  68. rotation.z = Math.random() * 2 * Math.PI;
  69. quaternion.setFromEuler( rotation );
  70. scale.x = scale.y = scale.z = 0.5 + ( Math.random() * 0.5 );
  71. return matrix.compose( position, quaternion, scale );
  72. }
  73. function randomizeRotationSpeed( rotation ) {
  74. rotation.x = Math.random() * 0.01;
  75. rotation.y = Math.random() * 0.01;
  76. rotation.z = Math.random() * 0.01;
  77. return rotation;
  78. }
  79. function initGeometries() {
  80. geometries = [
  81. new THREE.ConeGeometry( 1.0, 2.0 ),
  82. new THREE.BoxGeometry( 2.0, 2.0, 2.0 ),
  83. new THREE.SphereGeometry( 1.0, 16, 8 ),
  84. ];
  85. }
  86. function createMaterial() {
  87. if ( ! material ) {
  88. material = new THREE.MeshNormalMaterial();
  89. }
  90. return material;
  91. }
  92. function cleanup() {
  93. if ( mesh ) {
  94. mesh.parent.remove( mesh );
  95. if ( mesh.dispose ) {
  96. mesh.dispose();
  97. }
  98. }
  99. }
  100. function initMesh() {
  101. cleanup();
  102. if ( api.method === Method.BATCHED ) {
  103. initBatchedMesh();
  104. } else {
  105. initRegularMesh();
  106. }
  107. }
  108. function initRegularMesh() {
  109. mesh = new THREE.Group();
  110. const material = createMaterial();
  111. for ( let i = 0; i < api.count; i ++ ) {
  112. const child = new THREE.Mesh( geometries[ i % geometries.length ], material );
  113. randomizeMatrix( child.matrix );
  114. child.matrix.decompose( child.position, child.quaternion, child.scale );
  115. child.userData.rotationSpeed = randomizeRotationSpeed( new THREE.Euler() );
  116. mesh.add( child );
  117. }
  118. scene.add( mesh );
  119. }
  120. function initBatchedMesh() {
  121. const geometryCount = api.count;
  122. const vertexCount = api.count * 512;
  123. const indexCount = api.count * 1024;
  124. const euler = new THREE.Euler();
  125. const matrix = new THREE.Matrix4();
  126. mesh = new THREE.BatchedMesh( geometryCount, vertexCount, indexCount, createMaterial() );
  127. mesh.userData.rotationSpeeds = [];
  128. // disable full-object frustum culling since all of the objects can be dynamic.
  129. mesh.frustumCulled = false;
  130. ids.length = 0;
  131. for ( let i = 0; i < api.count; i ++ ) {
  132. const id = mesh.addGeometry( geometries[ i % geometries.length ] );
  133. mesh.setMatrixAt( id, randomizeMatrix( matrix ) );
  134. const rotationMatrix = new THREE.Matrix4();
  135. rotationMatrix.makeRotationFromEuler( randomizeRotationSpeed( euler ) );
  136. mesh.userData.rotationSpeeds.push( rotationMatrix );
  137. ids.push( id );
  138. }
  139. scene.add( mesh );
  140. }
  141. function init() {
  142. const width = window.innerWidth;
  143. const height = window.innerHeight;
  144. // camera
  145. camera = new THREE.PerspectiveCamera( 70, width / height, 1, 100 );
  146. camera.position.z = 30;
  147. // renderer
  148. renderer = new THREE.WebGLRenderer( { antialias: true } );
  149. renderer.setPixelRatio( window.devicePixelRatio );
  150. renderer.setSize( width, height );
  151. document.body.appendChild( renderer.domElement );
  152. // scene
  153. scene = new THREE.Scene();
  154. scene.background = new THREE.Color( 0xffffff );
  155. // controls
  156. controls = new OrbitControls( camera, renderer.domElement );
  157. controls.autoRotate = true;
  158. controls.autoRotateSpeed = 1.0;
  159. // stats
  160. stats = new Stats();
  161. document.body.appendChild( stats.dom );
  162. // gui
  163. gui = new GUI();
  164. gui.add( api, 'count', 1, MAX_GEOMETRY_COUNT ).step( 1 ).onChange( initMesh );
  165. gui.add( api, 'dynamic', 0, MAX_GEOMETRY_COUNT ).step( 1 );
  166. gui.add( api, 'method', Method ).onChange( initMesh );
  167. gui.add( api, 'opacity', 0, 1 ).onChange( v => {
  168. if ( v < 1 ) {
  169. material.transparent = true;
  170. material.depthWrite = false;
  171. } else {
  172. material.transparent = false;
  173. material.depthWrite = true;
  174. }
  175. material.opacity = v;
  176. material.needsUpdate = true;
  177. } );
  178. gui.add( api, 'sortObjects' );
  179. gui.add( api, 'perObjectFrustumCulled' );
  180. gui.add( api, 'useCustomSort' );
  181. guiStatsEl = document.createElement( 'li' );
  182. guiStatsEl.classList.add( 'gui-stats' );
  183. // listeners
  184. window.addEventListener( 'resize', onWindowResize );
  185. }
  186. //
  187. function sortFunction( list, camera ) {
  188. // initialize options
  189. this._options = this._options || {
  190. get: el => el.z,
  191. aux: new Array( this.maxGeometryCount )
  192. };
  193. const options = this._options;
  194. options.reversed = this.material.transparent;
  195. // convert depth to unsigned 32 bit range
  196. const factor = ( 2 ** 32 - 1 ) / camera.far; // UINT32_MAX / max_depth
  197. for ( let i = 0, l = list.length; i < l; i ++ ) {
  198. list[ i ].z *= factor;
  199. }
  200. // perform a fast-sort using the hybrid radix sort function
  201. radixSort( list, options );
  202. }
  203. function onWindowResize() {
  204. const width = window.innerWidth;
  205. const height = window.innerHeight;
  206. camera.aspect = width / height;
  207. camera.updateProjectionMatrix();
  208. renderer.setSize( width, height );
  209. }
  210. function animate() {
  211. requestAnimationFrame( animate );
  212. animateMeshes();
  213. controls.update();
  214. stats.update();
  215. render();
  216. }
  217. function animateMeshes() {
  218. const loopNum = Math.min( api.count, api.dynamic );
  219. if ( api.method === Method.BATCHED ) {
  220. for ( let i = 0; i < loopNum; i ++ ) {
  221. const rotationMatrix = mesh.userData.rotationSpeeds[ i ];
  222. const id = ids[ i ];
  223. mesh.getMatrixAt( id, matrix );
  224. matrix.multiply( rotationMatrix );
  225. mesh.setMatrixAt( id, matrix );
  226. }
  227. } else {
  228. for ( let i = 0; i < loopNum; i ++ ) {
  229. const child = mesh.children[ i ];
  230. const rotationSpeed = child.userData.rotationSpeed;
  231. child.rotation.set(
  232. child.rotation.x + rotationSpeed.x,
  233. child.rotation.y + rotationSpeed.y,
  234. child.rotation.z + rotationSpeed.z
  235. );
  236. }
  237. }
  238. }
  239. function render() {
  240. if ( mesh.isBatchedMesh ) {
  241. mesh.sortObjects = api.sortObjects;
  242. mesh.perObjectFrustumCulled = api.perObjectFrustumCulled;
  243. mesh.setCustomSort( api.useCustomSort ? sortFunction : null );
  244. }
  245. renderer.render( scene, camera );
  246. }
  247. </script>
  248. </body>
  249. </html>