webgpu_mesh_batch.html 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - 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> webgpu - mesh - batch
  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.module.js",
  25. "three/addons/": "./jsm/",
  26. "three/nodes": "./jsm/nodes/Nodes.js",
  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. import WebGPURenderer from 'three/addons/renderers/webgpu/WebGPURenderer.js';
  38. import { MeshNormalNodeMaterial } from 'three/nodes';
  39. let camera, scene, renderer;
  40. let controls, stats;
  41. let gui;
  42. let geometries, mesh, material;
  43. const ids = [];
  44. const matrix = new THREE.Matrix4();
  45. //
  46. const position = new THREE.Vector3();
  47. const rotation = new THREE.Euler();
  48. const quaternion = new THREE.Quaternion();
  49. const scale = new THREE.Vector3();
  50. //
  51. const MAX_GEOMETRY_COUNT = 20000;
  52. const api = {
  53. webgpu: true,
  54. count: 512,
  55. dynamic: 16,
  56. sortObjects: true,
  57. perObjectFrustumCulled: true,
  58. opacity: 1,
  59. useCustomSort: true,
  60. };
  61. init();
  62. //
  63. function randomizeMatrix( matrix ) {
  64. position.x = Math.random() * 40 - 20;
  65. position.y = Math.random() * 40 - 20;
  66. position.z = Math.random() * 40 - 20;
  67. rotation.x = Math.random() * 2 * Math.PI;
  68. rotation.y = Math.random() * 2 * Math.PI;
  69. rotation.z = Math.random() * 2 * Math.PI;
  70. quaternion.setFromEuler( rotation );
  71. scale.x = scale.y = scale.z = 0.5 + ( Math.random() * 0.5 );
  72. return matrix.compose( position, quaternion, scale );
  73. }
  74. function randomizeRotationSpeed( rotation ) {
  75. rotation.x = Math.random() * 0.01;
  76. rotation.y = Math.random() * 0.01;
  77. rotation.z = Math.random() * 0.01;
  78. return rotation;
  79. }
  80. function initGeometries() {
  81. geometries = [
  82. new THREE.ConeGeometry( 1.0, 2.0 ),
  83. new THREE.BoxGeometry( 2.0, 2.0, 2.0 ),
  84. new THREE.SphereGeometry( 1.0, 16, 8 ),
  85. ];
  86. }
  87. function createMaterial() {
  88. if ( ! material ) {
  89. material = new MeshNormalNodeMaterial();
  90. }
  91. return material;
  92. }
  93. function cleanup() {
  94. if ( mesh ) {
  95. mesh.parent.remove( mesh );
  96. if ( mesh.dispose ) {
  97. mesh.dispose();
  98. }
  99. }
  100. }
  101. function initMesh() {
  102. cleanup();
  103. initBatchedMesh();
  104. }
  105. function initBatchedMesh() {
  106. const geometryCount = api.count;
  107. const vertexCount = geometries.length * 512;
  108. const indexCount = geometries.length * 1024;
  109. const euler = new THREE.Euler();
  110. const matrix = new THREE.Matrix4();
  111. mesh = new THREE.BatchedMesh( geometryCount, vertexCount, indexCount, createMaterial() );
  112. mesh.userData.rotationSpeeds = [];
  113. // disable full-object frustum culling since all of the objects can be dynamic.
  114. mesh.frustumCulled = false;
  115. ids.length = 0;
  116. const geometryIds = [
  117. mesh.addGeometry( geometries[ 0 ] ),
  118. mesh.addGeometry( geometries[ 1 ] ),
  119. mesh.addGeometry( geometries[ 2 ] ),
  120. ];
  121. for ( let i = 0; i < api.count; i ++ ) {
  122. const id = mesh.addInstance( geometryIds[ i % geometryIds.length ] );
  123. mesh.setMatrixAt( id, randomizeMatrix( matrix ) );
  124. const rotationMatrix = new THREE.Matrix4();
  125. rotationMatrix.makeRotationFromEuler( randomizeRotationSpeed( euler ) );
  126. mesh.userData.rotationSpeeds.push( rotationMatrix );
  127. ids.push( id );
  128. }
  129. scene.add( mesh );
  130. }
  131. function init( forceWebGL = false ) {
  132. if ( renderer ) {
  133. renderer.dispose();
  134. controls.dispose();
  135. document.body.removeChild( stats.dom );
  136. document.body.removeChild( renderer.domElement );
  137. }
  138. document.getElementById( 'backend' ).innerText = 'Active Backend: ' + ( forceWebGL ? 'WebGL' : 'WebGPU' );
  139. // camera
  140. const aspect = window.innerWidth / window.innerHeight;
  141. camera = new THREE.PerspectiveCamera( 70, aspect, 1, 100 );
  142. camera.position.z = 50;
  143. // renderer
  144. renderer = new WebGPURenderer( { antialias: true, forceWebGL } );
  145. renderer.setPixelRatio( window.devicePixelRatio );
  146. renderer.setSize( window.innerWidth, window.innerHeight );
  147. renderer.setAnimationLoop( animate );
  148. // scene
  149. scene = new THREE.Scene();
  150. scene.background = new THREE.Color( 0xffffff );
  151. if ( forceWebGL ) {
  152. scene.background = new THREE.Color( 0xf10000 );
  153. } else {
  154. scene.background = new THREE.Color( 0x0000f1 );
  155. }
  156. document.body.appendChild( renderer.domElement );
  157. initGeometries();
  158. initMesh();
  159. // controls
  160. controls = new OrbitControls( camera, renderer.domElement );
  161. controls.autoRotate = true;
  162. controls.autoRotateSpeed = 1.0;
  163. // stats
  164. stats = new Stats( {
  165. precision: 3,
  166. horizontal: false
  167. } );
  168. stats.init( renderer );
  169. document.body.appendChild( stats.dom );
  170. stats.dom.style.position = 'absolute';
  171. // gui
  172. gui = new GUI();
  173. gui.add( api, 'webgpu' ).onChange( () => {
  174. init( ! api.webgpu );
  175. } );
  176. gui.add( api, 'count', 1, MAX_GEOMETRY_COUNT ).step( 1 ).onChange( initMesh );
  177. gui.add( api, 'dynamic', 0, MAX_GEOMETRY_COUNT ).step( 1 );
  178. gui.add( api, 'opacity', 0, 1 ).onChange( v => {
  179. if ( v < 1 ) {
  180. material.transparent = true;
  181. material.depthWrite = false;
  182. } else {
  183. material.transparent = false;
  184. material.depthWrite = true;
  185. }
  186. material.opacity = v;
  187. material.needsUpdate = true;
  188. } );
  189. gui.add( api, 'sortObjects' );
  190. gui.add( api, 'perObjectFrustumCulled' );
  191. gui.add( api, 'useCustomSort' );
  192. // listeners
  193. window.addEventListener( 'resize', onWindowResize );
  194. function onWindowResize() {
  195. const width = window.innerWidth;
  196. const height = window.innerHeight;
  197. camera.aspect = width / height;
  198. camera.updateProjectionMatrix();
  199. renderer.setSize( width, height );
  200. }
  201. async function animate() {
  202. animateMeshes();
  203. controls.update();
  204. if ( mesh.isBatchedMesh ) {
  205. mesh.sortObjects = api.sortObjects;
  206. mesh.perObjectFrustumCulled = api.perObjectFrustumCulled;
  207. mesh.setCustomSort( api.useCustomSort ? sortFunction : null );
  208. }
  209. await renderer.renderAsync( scene, camera );
  210. stats.update();
  211. }
  212. function animateMeshes() {
  213. const loopNum = Math.min( api.count, api.dynamic );
  214. for ( let i = 0; i < loopNum; i ++ ) {
  215. const rotationMatrix = mesh.userData.rotationSpeeds[ i ];
  216. const id = ids[ i ];
  217. mesh.getMatrixAt( id, matrix );
  218. matrix.multiply( rotationMatrix );
  219. mesh.setMatrixAt( id, matrix );
  220. }
  221. }
  222. }
  223. //
  224. function sortFunction( list, camera ) {
  225. // initialize options
  226. this._options = this._options || {
  227. get: el => el.z,
  228. aux: new Array( this.maxInstanceCount )
  229. };
  230. const options = this._options;
  231. options.reversed = this.material.transparent;
  232. // convert depth to unsigned 32 bit range
  233. const factor = ( 2 ** 32 - 1 ) / camera.far; // UINT32_MAX / max_depth
  234. for ( let i = 0, l = list.length; i < l; i ++ ) {
  235. list[ i ].z *= factor;
  236. }
  237. // perform a fast-sort using the hybrid radix sort function
  238. radixSort( list, options );
  239. }
  240. </script>
  241. </body>
  242. </html>