webgpu_mesh_batch.html 7.1 KB

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