webgl_mesh_batch.html 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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;
  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. transparent: true,
  53. sortObjects: true,
  54. perObjectFrustumCulled: true,
  55. useCustomSort: true,
  56. };
  57. init();
  58. initGeometries();
  59. initMesh();
  60. //
  61. function randomizeMatrix( matrix ) {
  62. position.x = Math.random() * 40 - 20;
  63. position.y = Math.random() * 40 - 20;
  64. position.z = Math.random() * 40 - 20;
  65. rotation.x = Math.random() * 2 * Math.PI;
  66. rotation.y = Math.random() * 2 * Math.PI;
  67. rotation.z = Math.random() * 2 * Math.PI;
  68. quaternion.setFromEuler( rotation );
  69. scale.x = scale.y = scale.z = 0.5 + ( Math.random() * 0.5 );
  70. return matrix.compose( position, quaternion, scale );
  71. }
  72. function randomizeRotationSpeed( rotation ) {
  73. rotation.x = Math.random() * 0.01;
  74. rotation.y = Math.random() * 0.01;
  75. rotation.z = Math.random() * 0.01;
  76. return rotation;
  77. }
  78. function randomizeColor( color ) {
  79. return color.setHSL( Math.random() * 0.5, 0.6, 0.5 );
  80. }
  81. function randomizeAlpha() {
  82. // make ~20% of all objects transparent
  83. return Math.random() > 0.8 ? 0.5 : 1.0;
  84. }
  85. function initGeometries() {
  86. const cone = new THREE.ConeGeometry( 1.0, 2.0 );
  87. const box = new THREE.BoxGeometry( 2.0, 2.0, 2.0 );
  88. const sphere = new THREE.SphereGeometry( 1.0, 16, 8 );
  89. geometries = [ cone, box, sphere ];
  90. for ( const geometry of geometries ) {
  91. // add vertex colors for testing
  92. const count = geometry.getAttribute( 'position' ).count;
  93. const attribute = new THREE.BufferAttribute( new Float32Array( count * 3 ), 3 );
  94. geometry.setAttribute( 'color', attribute );
  95. for ( let i = 0, l = attribute.array.length; i < l; ++ i ) {
  96. attribute.array[ i ] = 1.0;
  97. }
  98. }
  99. }
  100. function createMaterial() {
  101. return new THREE.MeshPhongMaterial( {
  102. vertexColors: true,
  103. transparent: api.transparent,
  104. depthWrite: ! api.transparent
  105. } );
  106. }
  107. function cleanup() {
  108. if ( mesh ) {
  109. mesh.traverse( node => {
  110. if ( node instanceof THREE.Mesh ) {
  111. node.material.dispose();
  112. }
  113. } );
  114. mesh.parent.remove( mesh );
  115. if ( mesh.dispose ) {
  116. mesh.dispose();
  117. }
  118. }
  119. }
  120. function initMesh() {
  121. cleanup();
  122. if ( api.method === Method.BATCHED ) {
  123. initBatchedMesh();
  124. } else {
  125. initRegularMesh();
  126. }
  127. }
  128. function initRegularMesh() {
  129. mesh = new THREE.Group();
  130. for ( let i = 0; i < api.count; i ++ ) {
  131. const material = createMaterial();
  132. randomizeColor( material.color );
  133. material.opacity = randomizeAlpha();
  134. const child = new THREE.Mesh( geometries[ i % geometries.length ], material );
  135. randomizeMatrix( child.matrix );
  136. child.matrix.decompose( child.position, child.quaternion, child.scale );
  137. child.userData.rotationSpeed = randomizeRotationSpeed( new THREE.Euler() );
  138. mesh.add( child );
  139. }
  140. scene.add( mesh );
  141. }
  142. function initBatchedMesh() {
  143. const geometryCount = api.count;
  144. const vertexCount = geometries.length * 512;
  145. const indexCount = geometries.length * 1024;
  146. const euler = new THREE.Euler();
  147. const matrix = new THREE.Matrix4();
  148. const color = new THREE.Color();
  149. const colorWithAlpha = new THREE.Vector4();
  150. mesh = new THREE.BatchedMesh( geometryCount, vertexCount, indexCount, createMaterial() );
  151. mesh.userData.rotationSpeeds = [];
  152. // disable full-object frustum culling since all of the objects can be dynamic.
  153. mesh.frustumCulled = false;
  154. ids.length = 0;
  155. const geometryIds = [
  156. mesh.addGeometry( geometries[ 0 ] ),
  157. mesh.addGeometry( geometries[ 1 ] ),
  158. mesh.addGeometry( geometries[ 2 ] ),
  159. ];
  160. for ( let i = 0; i < api.count; i ++ ) {
  161. randomizeColor( color );
  162. colorWithAlpha.set( color.r, color.g, color.b, randomizeAlpha() );
  163. const id = mesh.addInstance( geometryIds[ i % geometryIds.length ] );
  164. mesh.setMatrixAt( id, randomizeMatrix( matrix ) );
  165. mesh.setColorAt( id, colorWithAlpha );
  166. const rotationMatrix = new THREE.Matrix4();
  167. rotationMatrix.makeRotationFromEuler( randomizeRotationSpeed( euler ) );
  168. mesh.userData.rotationSpeeds.push( rotationMatrix );
  169. ids.push( id );
  170. }
  171. scene.add( mesh );
  172. }
  173. function init() {
  174. const width = window.innerWidth;
  175. const height = window.innerHeight;
  176. // camera
  177. camera = new THREE.PerspectiveCamera( 70, width / height, 1, 100 );
  178. camera.position.z = 30;
  179. // renderer
  180. renderer = new THREE.WebGLRenderer( { antialias: true } );
  181. renderer.setPixelRatio( window.devicePixelRatio );
  182. renderer.setSize( width, height );
  183. renderer.setAnimationLoop( animate );
  184. document.body.appendChild( renderer.domElement );
  185. // scene
  186. scene = new THREE.Scene();
  187. scene.background = new THREE.Color( 0xffffff );
  188. // controls
  189. controls = new OrbitControls( camera, renderer.domElement );
  190. controls.autoRotate = true;
  191. controls.autoRotateSpeed = 1.0;
  192. // light
  193. const ambientLight = new THREE.AmbientLight( 0xffffff, 2 );
  194. const directionalLight = new THREE.DirectionalLight( 0xffffff, 2 );
  195. directionalLight.position.set( 1, 1, 1 );
  196. scene.add( directionalLight, ambientLight );
  197. // stats
  198. stats = new Stats();
  199. document.body.appendChild( stats.dom );
  200. // gui
  201. gui = new GUI();
  202. gui.add( api, 'count', 1, MAX_GEOMETRY_COUNT ).step( 1 ).onChange( initMesh );
  203. gui.add( api, 'dynamic', 0, MAX_GEOMETRY_COUNT ).step( 1 );
  204. gui.add( api, 'method', Method ).onChange( initMesh );
  205. gui.add( api, 'transparent' ).onChange( v => mesh.traverse( node => {
  206. if ( node instanceof THREE.Mesh ) {
  207. const material = node.material;
  208. material.transparent = v;
  209. material.depthWrite = ! v;
  210. material.needsUpdate = true;
  211. }
  212. } ) );
  213. gui.add( api, 'sortObjects' );
  214. gui.add( api, 'perObjectFrustumCulled' );
  215. gui.add( api, 'useCustomSort' );
  216. guiStatsEl = document.createElement( 'li' );
  217. guiStatsEl.classList.add( 'gui-stats' );
  218. // listeners
  219. window.addEventListener( 'resize', onWindowResize );
  220. }
  221. //
  222. function sortFunction( list ) {
  223. // initialize options
  224. this._options = this._options || {
  225. get: el => el.z,
  226. aux: new Array( this.maxInstanceCount )
  227. };
  228. const options = this._options;
  229. options.reversed = this.material.transparent;
  230. let minZ = Infinity;
  231. let maxZ = - Infinity;
  232. for ( let i = 0, l = list.length; i < l; i ++ ) {
  233. const z = list[ i ].z;
  234. if ( z > maxZ ) maxZ = z;
  235. if ( z < minZ ) minZ = z;
  236. }
  237. // convert depth to unsigned 32 bit range
  238. const depthDelta = maxZ - minZ;
  239. const factor = ( 2 ** 32 - 1 ) / depthDelta; // UINT32_MAX / z range
  240. for ( let i = 0, l = list.length; i < l; i ++ ) {
  241. list[ i ].z -= minZ;
  242. list[ i ].z *= factor;
  243. }
  244. // perform a fast-sort using the hybrid radix sort function
  245. radixSort( list, options );
  246. }
  247. function onWindowResize() {
  248. const width = window.innerWidth;
  249. const height = window.innerHeight;
  250. camera.aspect = width / height;
  251. camera.updateProjectionMatrix();
  252. renderer.setSize( width, height );
  253. }
  254. function animate() {
  255. animateMeshes();
  256. controls.update();
  257. stats.update();
  258. render();
  259. }
  260. function animateMeshes() {
  261. const loopNum = Math.min( api.count, api.dynamic );
  262. if ( api.method === Method.BATCHED ) {
  263. for ( let i = 0; i < loopNum; i ++ ) {
  264. const rotationMatrix = mesh.userData.rotationSpeeds[ i ];
  265. const id = ids[ i ];
  266. mesh.getMatrixAt( id, matrix );
  267. matrix.multiply( rotationMatrix );
  268. mesh.setMatrixAt( id, matrix );
  269. }
  270. } else {
  271. for ( let i = 0; i < loopNum; i ++ ) {
  272. const child = mesh.children[ i ];
  273. const rotationSpeed = child.userData.rotationSpeed;
  274. child.rotation.set(
  275. child.rotation.x + rotationSpeed.x,
  276. child.rotation.y + rotationSpeed.y,
  277. child.rotation.z + rotationSpeed.z
  278. );
  279. }
  280. }
  281. }
  282. function render() {
  283. if ( mesh.isBatchedMesh ) {
  284. mesh.sortObjects = api.sortObjects;
  285. mesh.perObjectFrustumCulled = api.perObjectFrustumCulled;
  286. mesh.setCustomSort( api.useCustomSort ? sortFunction : null );
  287. }
  288. renderer.render( scene, camera );
  289. }
  290. </script>
  291. </body>
  292. </html>
粤ICP备19079148号