webgpu_mesh_batch.html 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - batch mesh</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> webgpu - batch mesh
  17. </div>
  18. <div id="backend" style="position: absolute; top: 200px; left: 0; color: #fff; background-color: rgba(0,0,0,0.75); padding: 5px;">
  19. Active Backend: WebGPU
  20. </div>
  21. <script type="importmap">
  22. {
  23. "imports": {
  24. "three": "../build/three.webgpu.js",
  25. "three/tsl": "../build/three.webgpu.js",
  26. "three/addons/": "./jsm/",
  27. "stats-gl": "https://cdn.jsdelivr.net/npm/[email protected]/dist/main.js"
  28. }
  29. }
  30. </script>
  31. <script type="module">
  32. import * as THREE from 'three';
  33. import Stats from 'stats-gl';
  34. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  35. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  36. import { radixSort } from 'three/addons/utils/SortUtils.js';
  37. let camera, scene, renderer;
  38. let controls, stats;
  39. let gui;
  40. let geometries, mesh, material;
  41. const ids = [];
  42. const matrix = new THREE.Matrix4();
  43. //
  44. const position = new THREE.Vector3();
  45. const rotation = new THREE.Euler();
  46. const quaternion = new THREE.Quaternion();
  47. const scale = new THREE.Vector3();
  48. //
  49. const MAX_GEOMETRY_COUNT = 20000;
  50. const api = {
  51. webgpu: true,
  52. count: 512,
  53. dynamic: 16,
  54. sortObjects: true,
  55. perObjectFrustumCulled: true,
  56. opacity: 1,
  57. useCustomSort: true,
  58. };
  59. init();
  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 initGeometries() {
  79. geometries = [
  80. new THREE.ConeGeometry( 1.0, 2.0 ),
  81. new THREE.BoxGeometry( 2.0, 2.0, 2.0 ),
  82. new THREE.SphereGeometry( 1.0, 16, 8 ),
  83. ];
  84. }
  85. function createMaterial() {
  86. if ( ! material ) {
  87. material = new THREE.MeshNormalNodeMaterial();
  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. initBatchedMesh();
  102. }
  103. function initBatchedMesh() {
  104. const geometryCount = api.count;
  105. const vertexCount = geometries.length * 512;
  106. const indexCount = geometries.length * 1024;
  107. const euler = new THREE.Euler();
  108. const matrix = new THREE.Matrix4();
  109. mesh = new THREE.BatchedMesh( geometryCount, vertexCount, indexCount, createMaterial() );
  110. mesh.userData.rotationSpeeds = [];
  111. // disable full-object frustum culling since all of the objects can be dynamic.
  112. mesh.frustumCulled = false;
  113. ids.length = 0;
  114. const geometryIds = [
  115. mesh.addGeometry( geometries[ 0 ] ),
  116. mesh.addGeometry( geometries[ 1 ] ),
  117. mesh.addGeometry( geometries[ 2 ] ),
  118. ];
  119. for ( let i = 0; i < api.count; i ++ ) {
  120. const id = mesh.addInstance( geometryIds[ i % geometryIds.length ] );
  121. mesh.setMatrixAt( id, randomizeMatrix( matrix ) );
  122. const rotationMatrix = new THREE.Matrix4();
  123. rotationMatrix.makeRotationFromEuler( randomizeRotationSpeed( euler ) );
  124. mesh.userData.rotationSpeeds.push( rotationMatrix );
  125. ids.push( id );
  126. }
  127. scene.add( mesh );
  128. }
  129. function init( forceWebGL = false ) {
  130. if ( renderer ) {
  131. renderer.dispose();
  132. controls.dispose();
  133. document.body.removeChild( stats.dom );
  134. document.body.removeChild( renderer.domElement );
  135. }
  136. document.getElementById( 'backend' ).innerText = 'Active Backend: ' + ( forceWebGL ? 'WebGL' : 'WebGPU' );
  137. // camera
  138. const aspect = window.innerWidth / window.innerHeight;
  139. camera = new THREE.PerspectiveCamera( 70, aspect, 1, 100 );
  140. camera.position.z = 50;
  141. // renderer
  142. renderer = new THREE.WebGPURenderer( { antialias: true, forceWebGL } );
  143. renderer.setPixelRatio( window.devicePixelRatio );
  144. renderer.setSize( window.innerWidth, window.innerHeight );
  145. renderer.setAnimationLoop( animate );
  146. // scene
  147. scene = new THREE.Scene();
  148. scene.background = new THREE.Color( 0xffffff );
  149. if ( forceWebGL ) {
  150. scene.background = new THREE.Color( 0xf10000 );
  151. } else {
  152. scene.background = new THREE.Color( 0x0000f1 );
  153. }
  154. document.body.appendChild( renderer.domElement );
  155. initGeometries();
  156. initMesh();
  157. // controls
  158. controls = new OrbitControls( camera, renderer.domElement );
  159. controls.autoRotate = true;
  160. controls.autoRotateSpeed = 1.0;
  161. // stats
  162. stats = new Stats( {
  163. precision: 3,
  164. horizontal: false
  165. } );
  166. stats.init( renderer );
  167. document.body.appendChild( stats.dom );
  168. stats.dom.style.position = 'absolute';
  169. // gui
  170. gui = new GUI();
  171. gui.add( api, 'webgpu' ).onChange( () => {
  172. init( ! api.webgpu );
  173. } );
  174. gui.add( api, 'count', 1, MAX_GEOMETRY_COUNT ).step( 1 ).onChange( initMesh );
  175. gui.add( api, 'dynamic', 0, MAX_GEOMETRY_COUNT ).step( 1 );
  176. gui.add( api, 'opacity', 0, 1 ).onChange( v => {
  177. if ( v < 1 ) {
  178. material.transparent = true;
  179. material.depthWrite = false;
  180. } else {
  181. material.transparent = false;
  182. material.depthWrite = true;
  183. }
  184. material.opacity = v;
  185. material.needsUpdate = true;
  186. } );
  187. gui.add( api, 'sortObjects' );
  188. gui.add( api, 'perObjectFrustumCulled' );
  189. gui.add( api, 'useCustomSort' );
  190. // listeners
  191. window.addEventListener( 'resize', onWindowResize );
  192. function onWindowResize() {
  193. const width = window.innerWidth;
  194. const height = window.innerHeight;
  195. camera.aspect = width / height;
  196. camera.updateProjectionMatrix();
  197. renderer.setSize( width, height );
  198. }
  199. async function animate() {
  200. animateMeshes();
  201. controls.update();
  202. if ( mesh.isBatchedMesh ) {
  203. mesh.sortObjects = api.sortObjects;
  204. mesh.perObjectFrustumCulled = api.perObjectFrustumCulled;
  205. mesh.setCustomSort( api.useCustomSort ? sortFunction : null );
  206. }
  207. await renderer.renderAsync( scene, camera );
  208. stats.update();
  209. }
  210. function animateMeshes() {
  211. const loopNum = Math.min( api.count, api.dynamic );
  212. for ( let i = 0; i < loopNum; i ++ ) {
  213. const rotationMatrix = mesh.userData.rotationSpeeds[ i ];
  214. const id = ids[ i ];
  215. mesh.getMatrixAt( id, matrix );
  216. matrix.multiply( rotationMatrix );
  217. mesh.setMatrixAt( id, matrix );
  218. }
  219. }
  220. }
  221. //
  222. function sortFunction( list, camera ) {
  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. // convert depth to unsigned 32 bit range
  231. const factor = ( 2 ** 32 - 1 ) / camera.far; // UINT32_MAX / max_depth
  232. for ( let i = 0, l = list.length; i < l; i ++ ) {
  233. list[ i ].z *= factor;
  234. }
  235. // perform a fast-sort using the hybrid radix sort function
  236. radixSort( list, options );
  237. }
  238. </script>
  239. </body>
  240. </html>