webgl_instancing_performance.html 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - instancing - performance</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. .lil-gui .gui-stats {
  13. line-height: var(--widget-height);
  14. padding: var(--padding);
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="info">
  20. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> webgl - instancing - performance
  21. </div>
  22. <div id="container"></div>
  23. <!-- Import maps polyfill -->
  24. <!-- Remove this when import maps will be widely supported -->
  25. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  26. <script type="importmap">
  27. {
  28. "imports": {
  29. "three": "../build/three.module.js"
  30. }
  31. }
  32. </script>
  33. <script type="module">
  34. import * as THREE from 'three';
  35. import Stats from './jsm/libs/stats.module.js';
  36. import { GUI } from './jsm/libs/lil-gui.module.min.js';
  37. import { OrbitControls } from './jsm/controls/OrbitControls.js';
  38. import * as BufferGeometryUtils from './jsm/utils/BufferGeometryUtils.js';
  39. let container, stats, gui, guiStatsEl;
  40. let camera, controls, scene, renderer, material;
  41. // gui
  42. const Method = {
  43. INSTANCED: 'INSTANCED',
  44. MERGED: 'MERGED',
  45. NAIVE: 'NAIVE'
  46. };
  47. const api = {
  48. method: Method.INSTANCED,
  49. count: 1000
  50. };
  51. //
  52. init();
  53. initMesh();
  54. animate();
  55. //
  56. function clean() {
  57. const meshes = [];
  58. scene.traverse( function ( object ) {
  59. if ( object.isMesh ) meshes.push( object );
  60. } );
  61. for ( let i = 0; i < meshes.length; i ++ ) {
  62. const mesh = meshes[ i ];
  63. mesh.material.dispose();
  64. mesh.geometry.dispose();
  65. scene.remove( mesh );
  66. }
  67. }
  68. const randomizeMatrix = function () {
  69. const position = new THREE.Vector3();
  70. const rotation = new THREE.Euler();
  71. const quaternion = new THREE.Quaternion();
  72. const scale = new THREE.Vector3();
  73. return function ( matrix ) {
  74. position.x = Math.random() * 40 - 20;
  75. position.y = Math.random() * 40 - 20;
  76. position.z = Math.random() * 40 - 20;
  77. rotation.x = Math.random() * 2 * Math.PI;
  78. rotation.y = Math.random() * 2 * Math.PI;
  79. rotation.z = Math.random() * 2 * Math.PI;
  80. quaternion.setFromEuler( rotation );
  81. scale.x = scale.y = scale.z = Math.random() * 1;
  82. matrix.compose( position, quaternion, scale );
  83. };
  84. }();
  85. function initMesh() {
  86. clean();
  87. // make instances
  88. new THREE.BufferGeometryLoader()
  89. .setPath( 'models/json/' )
  90. .load( 'suzanne_buffergeometry.json', function ( geometry ) {
  91. material = new THREE.MeshNormalMaterial();
  92. geometry.computeVertexNormals();
  93. console.time( api.method + ' (build)' );
  94. switch ( api.method ) {
  95. case Method.INSTANCED:
  96. makeInstanced( geometry );
  97. break;
  98. case Method.MERGED:
  99. makeMerged( geometry );
  100. break;
  101. case Method.NAIVE:
  102. makeNaive( geometry );
  103. break;
  104. }
  105. console.timeEnd( api.method + ' (build)' );
  106. } );
  107. }
  108. function makeInstanced( geometry ) {
  109. const matrix = new THREE.Matrix4();
  110. const mesh = new THREE.InstancedMesh( geometry, material, api.count );
  111. for ( let i = 0; i < api.count; i ++ ) {
  112. randomizeMatrix( matrix );
  113. mesh.setMatrixAt( i, matrix );
  114. }
  115. scene.add( mesh );
  116. //
  117. const geometryByteLength = getGeometryByteLength( geometry );
  118. guiStatsEl.innerHTML = [
  119. '<i>GPU draw calls</i>: 1',
  120. '<i>GPU memory</i>: ' + formatBytes( api.count * 16 + geometryByteLength, 2 )
  121. ].join( '<br/>' );
  122. }
  123. function makeMerged( geometry ) {
  124. const geometries = [];
  125. const matrix = new THREE.Matrix4();
  126. for ( let i = 0; i < api.count; i ++ ) {
  127. randomizeMatrix( matrix );
  128. const instanceGeometry = geometry.clone();
  129. instanceGeometry.applyMatrix4( matrix );
  130. geometries.push( instanceGeometry );
  131. }
  132. const mergedGeometry = BufferGeometryUtils.mergeBufferGeometries( geometries );
  133. scene.add( new THREE.Mesh( mergedGeometry, material ) );
  134. //
  135. guiStatsEl.innerHTML = [
  136. '<i>GPU draw calls</i>: 1',
  137. '<i>GPU memory</i>: ' + formatBytes( getGeometryByteLength( mergedGeometry ), 2 )
  138. ].join( '<br/>' );
  139. }
  140. function makeNaive( geometry ) {
  141. const matrix = new THREE.Matrix4();
  142. for ( let i = 0; i < api.count; i ++ ) {
  143. randomizeMatrix( matrix );
  144. const mesh = new THREE.Mesh( geometry, material );
  145. mesh.applyMatrix4( matrix );
  146. scene.add( mesh );
  147. }
  148. //
  149. const geometryByteLength = getGeometryByteLength( geometry );
  150. guiStatsEl.innerHTML = [
  151. '<i>GPU draw calls</i>: ' + api.count,
  152. '<i>GPU memory</i>: ' + formatBytes( api.count * 16 + geometryByteLength, 2 )
  153. ].join( '<br/>' );
  154. }
  155. function init() {
  156. const width = window.innerWidth;
  157. const height = window.innerHeight;
  158. // camera
  159. camera = new THREE.PerspectiveCamera( 70, width / height, 1, 100 );
  160. camera.position.z = 30;
  161. // renderer
  162. renderer = new THREE.WebGLRenderer( { antialias: true } );
  163. renderer.setPixelRatio( window.devicePixelRatio );
  164. renderer.setSize( width, height );
  165. renderer.outputEncoding = THREE.sRGBEncoding;
  166. container = document.getElementById( 'container' );
  167. container.appendChild( renderer.domElement );
  168. // scene
  169. scene = new THREE.Scene();
  170. scene.background = new THREE.Color( 0xffffff );
  171. // controls
  172. controls = new OrbitControls( camera, renderer.domElement );
  173. controls.autoRotate = true;
  174. // stats
  175. stats = new Stats();
  176. container.appendChild( stats.dom );
  177. // gui
  178. gui = new GUI();
  179. gui.add( api, 'method', Method ).onChange( initMesh );
  180. gui.add( api, 'count', 1, 10000 ).step( 1 ).onChange( initMesh );
  181. const perfFolder = gui.addFolder( 'Performance' );
  182. guiStatsEl = document.createElement( 'div' );
  183. guiStatsEl.classList.add( 'gui-stats' );
  184. perfFolder.$children.appendChild( guiStatsEl );
  185. perfFolder.open();
  186. // listeners
  187. window.addEventListener( 'resize', onWindowResize );
  188. Object.assign( window, { scene } );
  189. }
  190. //
  191. function onWindowResize() {
  192. const width = window.innerWidth;
  193. const height = window.innerHeight;
  194. camera.aspect = width / height;
  195. camera.updateProjectionMatrix();
  196. renderer.setSize( width, height );
  197. }
  198. function animate() {
  199. requestAnimationFrame( animate );
  200. controls.update();
  201. stats.update();
  202. render();
  203. }
  204. function render() {
  205. renderer.render( scene, camera );
  206. }
  207. //
  208. function getGeometryByteLength( geometry ) {
  209. let total = 0;
  210. if ( geometry.index ) total += geometry.index.array.byteLength;
  211. for ( const name in geometry.attributes ) {
  212. total += geometry.attributes[ name ].array.byteLength;
  213. }
  214. return total;
  215. }
  216. // Source: https://stackoverflow.com/a/18650828/1314762
  217. function formatBytes( bytes, decimals ) {
  218. if ( bytes === 0 ) return '0 bytes';
  219. const k = 1024;
  220. const dm = decimals < 0 ? 0 : decimals;
  221. const sizes = [ 'bytes', 'KB', 'MB' ];
  222. const i = Math.floor( Math.log( bytes ) / Math.log( k ) );
  223. return parseFloat( ( bytes / Math.pow( k, i ) ).toFixed( dm ) ) + ' ' + sizes[ i ];
  224. }
  225. </script>
  226. </body>
  227. </html>