webgl_instancing_performance.html 7.0 KB

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