webgpu_mesh_batch.html 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. <script type="importmap">
  19. {
  20. "imports": {
  21. "three": "../build/three.webgpu.js",
  22. "three/tsl": "../build/three.webgpu.js",
  23. "three/addons/": "./jsm/"
  24. }
  25. }
  26. </script>
  27. <script type="module">
  28. import * as THREE from 'three';
  29. import Stats from 'three/addons/libs/stats.module.js';
  30. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  31. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  32. import { radixSort } from 'three/addons/utils/SortUtils.js';
  33. import { transformedNormalView, directionToColor, diffuseColor } from 'three/tsl';
  34. let camera, scene, renderer;
  35. let controls, stats;
  36. let gui;
  37. let geometries, mesh, material;
  38. const ids = [];
  39. const matrix = new THREE.Matrix4();
  40. //
  41. const position = new THREE.Vector3();
  42. const rotation = new THREE.Euler();
  43. const quaternion = new THREE.Quaternion();
  44. const scale = new THREE.Vector3();
  45. //
  46. const MAX_GEOMETRY_COUNT = 20000;
  47. const api = {
  48. webgpu: true,
  49. count: 512,
  50. dynamic: 16,
  51. sortObjects: true,
  52. perObjectFrustumCulled: true,
  53. opacity: 1,
  54. useCustomSort: true,
  55. randomizeGeometry: ()=>{
  56. for ( let i = 0; i < api.count; i ++ ) {
  57. mesh.setGeometryIdAt( i, Math.floor( Math.random() * geometries.length ) );
  58. }
  59. }
  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 THREE.MeshBasicNodeMaterial();
  90. material.outputNode = diffuseColor.mul( directionToColor( transformedNormalView ).y.add( 0.5 ) );
  91. }
  92. return material;
  93. }
  94. function cleanup() {
  95. if ( mesh ) {
  96. mesh.parent.remove( mesh );
  97. if ( mesh.dispose ) {
  98. mesh.dispose();
  99. }
  100. }
  101. }
  102. function initMesh() {
  103. cleanup();
  104. initBatchedMesh();
  105. }
  106. function initBatchedMesh() {
  107. const geometryCount = api.count;
  108. const vertexCount = geometries.length * 512;
  109. const indexCount = geometries.length * 1024;
  110. const euler = new THREE.Euler();
  111. const matrix = new THREE.Matrix4();
  112. mesh = new THREE.BatchedMesh( geometryCount, vertexCount, indexCount, createMaterial() );
  113. mesh.userData.rotationSpeeds = [];
  114. // disable full-object frustum culling since all of the objects can be dynamic.
  115. mesh.frustumCulled = false;
  116. ids.length = 0;
  117. const geometryIds = [
  118. mesh.addGeometry( geometries[ 0 ] ),
  119. mesh.addGeometry( geometries[ 1 ] ),
  120. mesh.addGeometry( geometries[ 2 ] ),
  121. ];
  122. for ( let i = 0; i < api.count; i ++ ) {
  123. const id = mesh.addInstance( geometryIds[ i % geometryIds.length ] );
  124. mesh.setMatrixAt( id, randomizeMatrix( matrix ) );
  125. mesh.setColorAt( id, new THREE.Color( Math.random() * 0xffffff ) );
  126. const rotationMatrix = new THREE.Matrix4();
  127. rotationMatrix.makeRotationFromEuler( randomizeRotationSpeed( euler ) );
  128. mesh.userData.rotationSpeeds.push( rotationMatrix );
  129. ids.push( id );
  130. }
  131. scene.add( mesh );
  132. }
  133. function init( forceWebGL = false ) {
  134. if ( renderer ) {
  135. renderer.dispose();
  136. controls.dispose();
  137. document.body.removeChild( stats.dom );
  138. document.body.removeChild( renderer.domElement );
  139. }
  140. // camera
  141. const aspect = window.innerWidth / window.innerHeight;
  142. camera = new THREE.PerspectiveCamera( 70, aspect, 1, 100 );
  143. camera.position.z = 30;
  144. // renderer
  145. renderer = new THREE.WebGPURenderer( { antialias: true, forceWebGL } );
  146. renderer.setPixelRatio( window.devicePixelRatio );
  147. renderer.setSize( window.innerWidth, window.innerHeight );
  148. renderer.setAnimationLoop( animate );
  149. // scene
  150. scene = new THREE.Scene();
  151. scene.background = forceWebGL ? new THREE.Color( 0xffc1c1 ) : new THREE.Color( 0xc1c1ff );
  152. document.body.appendChild( renderer.domElement );
  153. initGeometries();
  154. initMesh();
  155. // controls
  156. controls = new OrbitControls( camera, renderer.domElement );
  157. controls.autoRotate = true;
  158. controls.autoRotateSpeed = 1.0;
  159. // stats
  160. stats = new Stats();
  161. document.body.appendChild( stats.dom );
  162. // gui
  163. gui = new GUI();
  164. gui.add( api, 'webgpu' ).onChange( () => {
  165. init( ! api.webgpu );
  166. } );
  167. gui.add( api, 'count', 1, MAX_GEOMETRY_COUNT ).step( 1 ).onChange( initMesh );
  168. gui.add( api, 'dynamic', 0, MAX_GEOMETRY_COUNT ).step( 1 );
  169. gui.add( api, 'opacity', 0, 1 ).onChange( v => {
  170. if ( v < 1 ) {
  171. material.transparent = true;
  172. material.depthWrite = false;
  173. } else {
  174. material.transparent = false;
  175. material.depthWrite = true;
  176. }
  177. material.opacity = v;
  178. material.needsUpdate = true;
  179. } );
  180. gui.add( api, 'sortObjects' );
  181. gui.add( api, 'perObjectFrustumCulled' );
  182. gui.add( api, 'useCustomSort' );
  183. gui.add( api, 'randomizeGeometry' );
  184. // listeners
  185. window.addEventListener( 'resize', onWindowResize );
  186. function onWindowResize() {
  187. const width = window.innerWidth;
  188. const height = window.innerHeight;
  189. camera.aspect = width / height;
  190. camera.updateProjectionMatrix();
  191. renderer.setSize( width, height );
  192. }
  193. async function animate() {
  194. animateMeshes();
  195. controls.update();
  196. if ( mesh.isBatchedMesh ) {
  197. mesh.sortObjects = api.sortObjects;
  198. mesh.perObjectFrustumCulled = api.perObjectFrustumCulled;
  199. mesh.setCustomSort( api.useCustomSort ? sortFunction : null );
  200. }
  201. await renderer.renderAsync( scene, camera );
  202. stats.update();
  203. }
  204. function animateMeshes() {
  205. const loopNum = Math.min( api.count, api.dynamic );
  206. for ( let i = 0; i < loopNum; i ++ ) {
  207. const rotationMatrix = mesh.userData.rotationSpeeds[ i ];
  208. const id = ids[ i ];
  209. mesh.getMatrixAt( id, matrix );
  210. matrix.multiply( rotationMatrix );
  211. mesh.setMatrixAt( id, matrix );
  212. }
  213. }
  214. }
  215. //
  216. function sortFunction( list, camera ) {
  217. // initialize options
  218. this._options = this._options || {
  219. get: el => el.z,
  220. aux: new Array( this.maxInstanceCount )
  221. };
  222. const options = this._options;
  223. options.reversed = this.material.transparent;
  224. // convert depth to unsigned 32 bit range
  225. const factor = ( 2 ** 32 - 1 ) / camera.far; // UINT32_MAX / max_depth
  226. for ( let i = 0, l = list.length; i < l; i ++ ) {
  227. list[ i ].z *= factor;
  228. }
  229. // perform a fast-sort using the hybrid radix sort function
  230. radixSort( list, options );
  231. }
  232. </script>
  233. </body>
  234. </html>