webgl_mesh_batch.html 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. let stats, gui, guiStatsEl;
  32. let camera, controls, scene, renderer;
  33. let geometries, mesh, material;
  34. const ids = [];
  35. const matrix = new THREE.Matrix4();
  36. //
  37. const position = new THREE.Vector3();
  38. const rotation = new THREE.Euler();
  39. const quaternion = new THREE.Quaternion();
  40. const scale = new THREE.Vector3();
  41. //
  42. const MAX_GEOMETRY_COUNT = 20000;
  43. const Method = {
  44. BATCHED: 'BATCHED',
  45. NAIVE: 'NAIVE'
  46. };
  47. const api = {
  48. method: Method.BATCHED,
  49. count: 256,
  50. dynamic: 16,
  51. sortObjects: true,
  52. perObjectFrustumCulled: true,
  53. opacity: 1,
  54. };
  55. init();
  56. initGeometries();
  57. initMesh();
  58. animate();
  59. //
  60. function randomizeMatrix( matrix ) {
  61. position.x = Math.random() * 40 - 20;
  62. position.y = Math.random() * 40 - 20;
  63. position.z = Math.random() * 40 - 20;
  64. rotation.x = Math.random() * 2 * Math.PI;
  65. rotation.y = Math.random() * 2 * Math.PI;
  66. rotation.z = Math.random() * 2 * Math.PI;
  67. quaternion.setFromEuler( rotation );
  68. scale.x = scale.y = scale.z = 0.5 + ( Math.random() * 0.5 );
  69. return matrix.compose( position, quaternion, scale );
  70. }
  71. function randomizeRotationSpeed( rotation ) {
  72. rotation.x = Math.random() * 0.01;
  73. rotation.y = Math.random() * 0.01;
  74. rotation.z = Math.random() * 0.01;
  75. return rotation;
  76. }
  77. function initGeometries() {
  78. geometries = [
  79. new THREE.ConeGeometry( 1.0, 2.0 ),
  80. new THREE.BoxGeometry( 2.0, 2.0, 2.0 ),
  81. new THREE.SphereGeometry( 1.0, 16, 8 ),
  82. ];
  83. }
  84. function createMaterial() {
  85. if ( ! material ) {
  86. material = new THREE.MeshNormalMaterial();
  87. material.opacity = 0.1;
  88. }
  89. return material;
  90. }
  91. function cleanup() {
  92. if ( mesh ) {
  93. mesh.parent.remove( mesh );
  94. if ( mesh.dispose ) {
  95. mesh.dispose();
  96. }
  97. }
  98. }
  99. function initMesh() {
  100. cleanup();
  101. if ( api.method === Method.BATCHED ) {
  102. initBatchedMesh();
  103. } else {
  104. initRegularMesh();
  105. }
  106. }
  107. function initRegularMesh() {
  108. mesh = new THREE.Group();
  109. const material = createMaterial();
  110. for ( let i = 0; i < api.count; i ++ ) {
  111. const child = new THREE.Mesh( geometries[ i % geometries.length ], material );
  112. randomizeMatrix( child.matrix );
  113. child.matrix.decompose( child.position, child.quaternion, child.scale );
  114. child.userData.rotationSpeed = randomizeRotationSpeed( new THREE.Euler() );
  115. mesh.add( child );
  116. }
  117. scene.add( mesh );
  118. }
  119. function initBatchedMesh() {
  120. const geometryCount = api.count;
  121. const vertexCount = api.count * 512;
  122. const indexCount = api.count * 1024;
  123. const euler = new THREE.Euler();
  124. const matrix = new THREE.Matrix4();
  125. mesh = new THREE.BatchedMesh( geometryCount, vertexCount, indexCount, createMaterial() );
  126. mesh.userData.rotationSpeeds = [];
  127. // disable full-object frustum culling since all of the objects can be dynamic.
  128. mesh.frustumCulled = false;
  129. ids.length = 0;
  130. for ( let i = 0; i < api.count; i ++ ) {
  131. const id = mesh.addGeometry( geometries[ i % geometries.length ] );
  132. mesh.setMatrixAt( id, randomizeMatrix( matrix ) );
  133. const rotationMatrix = new THREE.Matrix4();
  134. rotationMatrix.makeRotationFromEuler( randomizeRotationSpeed( euler ) );
  135. mesh.userData.rotationSpeeds.push( rotationMatrix );
  136. ids.push( id );
  137. }
  138. scene.add( mesh );
  139. }
  140. function init() {
  141. const width = window.innerWidth;
  142. const height = window.innerHeight;
  143. // camera
  144. camera = new THREE.PerspectiveCamera( 70, width / height, 1, 100 );
  145. camera.position.z = 30;
  146. // renderer
  147. renderer = new THREE.WebGLRenderer( { antialias: true } );
  148. renderer.setPixelRatio( window.devicePixelRatio );
  149. renderer.setSize( width, height );
  150. document.body.appendChild( renderer.domElement );
  151. // scene
  152. scene = new THREE.Scene();
  153. scene.background = new THREE.Color( 0xffffff );
  154. // controls
  155. controls = new OrbitControls( camera, renderer.domElement );
  156. controls.autoRotate = true;
  157. controls.autoRotateSpeed = 1.0;
  158. // stats
  159. stats = new Stats();
  160. document.body.appendChild( stats.dom );
  161. // gui
  162. gui = new GUI();
  163. gui.add( api, 'count', 1, MAX_GEOMETRY_COUNT ).step( 1 ).onChange( initMesh );
  164. gui.add( api, 'dynamic', 0, MAX_GEOMETRY_COUNT ).step( 1 );
  165. gui.add( api, 'method', Method ).onChange( initMesh );
  166. gui.add( api, 'opacity', 0, 1 ).onChange( v => {
  167. if ( v < 1 ) {
  168. material.transparent = true;
  169. material.depthWrite = false;
  170. } else {
  171. material.transparent = false;
  172. material.depthWrite = true;
  173. }
  174. material.opacity = v;
  175. material.needsUpdate = true;
  176. } );
  177. gui.add( api, 'sortObjects' );
  178. gui.add( api, 'perObjectFrustumCulled' );
  179. guiStatsEl = document.createElement( 'li' );
  180. guiStatsEl.classList.add( 'gui-stats' );
  181. // listeners
  182. window.addEventListener( 'resize', onWindowResize );
  183. }
  184. //
  185. function onWindowResize() {
  186. const width = window.innerWidth;
  187. const height = window.innerHeight;
  188. camera.aspect = width / height;
  189. camera.updateProjectionMatrix();
  190. renderer.setSize( width, height );
  191. }
  192. function animate() {
  193. requestAnimationFrame( animate );
  194. animateMeshes();
  195. controls.update();
  196. stats.update();
  197. render();
  198. }
  199. function animateMeshes() {
  200. const loopNum = Math.min( api.count, api.dynamic );
  201. if ( api.method === Method.BATCHED ) {
  202. for ( let i = 0; i < loopNum; i ++ ) {
  203. const rotationMatrix = mesh.userData.rotationSpeeds[ i ];
  204. const id = ids[ i ];
  205. mesh.getMatrixAt( id, matrix );
  206. matrix.multiply( rotationMatrix );
  207. mesh.setMatrixAt( id, matrix );
  208. }
  209. } else {
  210. for ( let i = 0; i < loopNum; i ++ ) {
  211. const child = mesh.children[ i ];
  212. const rotationSpeed = child.userData.rotationSpeed;
  213. child.rotation.set(
  214. child.rotation.x + rotationSpeed.x,
  215. child.rotation.y + rotationSpeed.y,
  216. child.rotation.z + rotationSpeed.z
  217. );
  218. }
  219. }
  220. }
  221. function render() {
  222. if ( mesh.isBatchedMesh ) {
  223. mesh.sortObjects = api.sortObjects;
  224. mesh.perObjectFrustumCulled = api.perObjectFrustumCulled;
  225. }
  226. renderer.render( scene, camera );
  227. }
  228. </script>
  229. </body>
  230. </html>