1
0

webgl_mesh_batch.html 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - 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. <meta property="og:title" content="three.js webgl - mesh - batch">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/webgl_mesh_batch.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/webgl_mesh_batch.jpg">
  11. <link type="text/css" rel="stylesheet" href="main.css">
  12. <style>
  13. #info {
  14. background-color: rgba(0,0,0,0.75);
  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 - mesh - batch
  21. </div>
  22. <script type="importmap">
  23. {
  24. "imports": {
  25. "three": "../build/three.module.js",
  26. "three/addons/": "./jsm/"
  27. }
  28. }
  29. </script>
  30. <script type="module">
  31. import * as THREE from 'three';
  32. import Stats from 'three/addons/libs/stats.module.js';
  33. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  34. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  35. import { radixSort } from 'three/addons/utils/SortUtils.js';
  36. let stats, gui, guiStatsEl;
  37. let camera, controls, scene, renderer;
  38. let geometries, mesh;
  39. const ids = [];
  40. const matrix = new THREE.Matrix4();
  41. //
  42. const position = new THREE.Vector3();
  43. const rotation = new THREE.Euler();
  44. const quaternion = new THREE.Quaternion();
  45. const scale = new THREE.Vector3();
  46. //
  47. const MAX_GEOMETRY_COUNT = 20000;
  48. const Method = {
  49. BATCHED: 'BATCHED',
  50. NAIVE: 'NAIVE'
  51. };
  52. const api = {
  53. method: Method.BATCHED,
  54. count: 256,
  55. dynamic: 16,
  56. transparent: true,
  57. sortObjects: true,
  58. perObjectFrustumCulled: true,
  59. useCustomSort: true,
  60. };
  61. init();
  62. initGeometries();
  63. initMesh();
  64. //
  65. function randomizeMatrix( matrix ) {
  66. position.x = Math.random() * 40 - 20;
  67. position.y = Math.random() * 40 - 20;
  68. position.z = Math.random() * 40 - 20;
  69. rotation.x = Math.random() * 2 * Math.PI;
  70. rotation.y = Math.random() * 2 * Math.PI;
  71. rotation.z = Math.random() * 2 * Math.PI;
  72. quaternion.setFromEuler( rotation );
  73. scale.x = scale.y = scale.z = 0.5 + ( Math.random() * 0.5 );
  74. return matrix.compose( position, quaternion, scale );
  75. }
  76. function randomizeRotationSpeed( rotation ) {
  77. rotation.x = Math.random() * 0.01;
  78. rotation.y = Math.random() * 0.01;
  79. rotation.z = Math.random() * 0.01;
  80. return rotation;
  81. }
  82. function randomizeColor( color ) {
  83. return color.setHSL( Math.random() * 0.5, 0.6, 0.5 );
  84. }
  85. function randomizeAlpha() {
  86. // make ~20% of all objects transparent
  87. return Math.random() > 0.8 ? 0.5 : 1.0;
  88. }
  89. function initGeometries() {
  90. const cone = new THREE.ConeGeometry( 1.0, 2.0 );
  91. const box = new THREE.BoxGeometry( 2.0, 2.0, 2.0 );
  92. const sphere = new THREE.SphereGeometry( 1.0, 16, 8 );
  93. geometries = [ cone, box, sphere ];
  94. for ( const geometry of geometries ) {
  95. // add vertex colors for testing
  96. const count = geometry.getAttribute( 'position' ).count;
  97. const attribute = new THREE.BufferAttribute( new Float32Array( count * 3 ), 3 );
  98. geometry.setAttribute( 'color', attribute );
  99. for ( let i = 0, l = attribute.array.length; i < l; ++ i ) {
  100. attribute.array[ i ] = 1.0;
  101. }
  102. }
  103. }
  104. function createMaterial() {
  105. return new THREE.MeshPhongMaterial( {
  106. vertexColors: true,
  107. transparent: api.transparent,
  108. depthWrite: ! api.transparent
  109. } );
  110. }
  111. function cleanup() {
  112. if ( mesh ) {
  113. mesh.traverse( node => {
  114. if ( node instanceof THREE.Mesh ) {
  115. node.material.dispose();
  116. }
  117. } );
  118. mesh.parent.remove( mesh );
  119. if ( mesh.dispose ) {
  120. mesh.dispose();
  121. }
  122. }
  123. }
  124. function initMesh() {
  125. cleanup();
  126. if ( api.method === Method.BATCHED ) {
  127. initBatchedMesh();
  128. } else {
  129. initRegularMesh();
  130. }
  131. }
  132. function initRegularMesh() {
  133. mesh = new THREE.Group();
  134. for ( let i = 0; i < api.count; i ++ ) {
  135. const material = createMaterial();
  136. randomizeColor( material.color );
  137. material.opacity = randomizeAlpha();
  138. const child = new THREE.Mesh( geometries[ i % geometries.length ], material );
  139. randomizeMatrix( child.matrix );
  140. child.matrix.decompose( child.position, child.quaternion, child.scale );
  141. child.userData.rotationSpeed = randomizeRotationSpeed( new THREE.Euler() );
  142. mesh.add( child );
  143. }
  144. scene.add( mesh );
  145. }
  146. function initBatchedMesh() {
  147. const geometryCount = api.count;
  148. const vertexCount = geometries.length * 512;
  149. const indexCount = geometries.length * 1024;
  150. const euler = new THREE.Euler();
  151. const matrix = new THREE.Matrix4();
  152. const color = new THREE.Color();
  153. const colorWithAlpha = new THREE.Vector4();
  154. mesh = new THREE.BatchedMesh( geometryCount, vertexCount, indexCount, createMaterial() );
  155. mesh.userData.rotationSpeeds = [];
  156. // disable full-object frustum culling since all of the objects can be dynamic.
  157. mesh.frustumCulled = false;
  158. ids.length = 0;
  159. const geometryIds = [
  160. mesh.addGeometry( geometries[ 0 ] ),
  161. mesh.addGeometry( geometries[ 1 ] ),
  162. mesh.addGeometry( geometries[ 2 ] ),
  163. ];
  164. for ( let i = 0; i < api.count; i ++ ) {
  165. randomizeColor( color );
  166. colorWithAlpha.set( color.r, color.g, color.b, randomizeAlpha() );
  167. const id = mesh.addInstance( geometryIds[ i % geometryIds.length ] );
  168. mesh.setMatrixAt( id, randomizeMatrix( matrix ) );
  169. mesh.setColorAt( id, colorWithAlpha );
  170. const rotationMatrix = new THREE.Matrix4();
  171. rotationMatrix.makeRotationFromEuler( randomizeRotationSpeed( euler ) );
  172. mesh.userData.rotationSpeeds.push( rotationMatrix );
  173. ids.push( id );
  174. }
  175. scene.add( mesh );
  176. }
  177. function init() {
  178. const width = window.innerWidth;
  179. const height = window.innerHeight;
  180. // camera
  181. camera = new THREE.PerspectiveCamera( 70, width / height, 1, 100 );
  182. camera.position.z = 30;
  183. // renderer
  184. renderer = new THREE.WebGLRenderer( { antialias: true } );
  185. renderer.setPixelRatio( window.devicePixelRatio );
  186. renderer.setSize( width, height );
  187. renderer.setAnimationLoop( animate );
  188. document.body.appendChild( renderer.domElement );
  189. // scene
  190. scene = new THREE.Scene();
  191. scene.background = new THREE.Color( 0xffffff );
  192. // controls
  193. controls = new OrbitControls( camera, renderer.domElement );
  194. controls.autoRotate = true;
  195. controls.autoRotateSpeed = 1.0;
  196. // light
  197. const ambientLight = new THREE.AmbientLight( 0xffffff, 2 );
  198. const directionalLight = new THREE.DirectionalLight( 0xffffff, 2 );
  199. directionalLight.position.set( 1, 1, 1 );
  200. scene.add( directionalLight, ambientLight );
  201. // stats
  202. stats = new Stats();
  203. document.body.appendChild( stats.dom );
  204. // gui
  205. gui = new GUI();
  206. gui.add( api, 'count', 1, MAX_GEOMETRY_COUNT ).step( 1 ).onChange( initMesh );
  207. gui.add( api, 'dynamic', 0, MAX_GEOMETRY_COUNT ).step( 1 );
  208. gui.add( api, 'method', Method ).onChange( initMesh );
  209. gui.add( api, 'transparent' ).onChange( v => mesh.traverse( node => {
  210. if ( node instanceof THREE.Mesh ) {
  211. const material = node.material;
  212. material.transparent = v;
  213. material.depthWrite = ! v;
  214. material.needsUpdate = true;
  215. }
  216. } ) );
  217. gui.add( api, 'sortObjects' );
  218. gui.add( api, 'perObjectFrustumCulled' );
  219. gui.add( api, 'useCustomSort' );
  220. guiStatsEl = document.createElement( 'li' );
  221. guiStatsEl.classList.add( 'gui-stats' );
  222. // listeners
  223. window.addEventListener( 'resize', onWindowResize );
  224. }
  225. //
  226. function sortFunction( list ) {
  227. // initialize options
  228. this._options = this._options || {
  229. get: el => el.z,
  230. aux: new Array( this.maxInstanceCount )
  231. };
  232. const options = this._options;
  233. options.reversed = this.material.transparent;
  234. let minZ = Infinity;
  235. let maxZ = - Infinity;
  236. for ( let i = 0, l = list.length; i < l; i ++ ) {
  237. const z = list[ i ].z;
  238. if ( z > maxZ ) maxZ = z;
  239. if ( z < minZ ) minZ = z;
  240. }
  241. // convert depth to unsigned 32 bit range
  242. const depthDelta = maxZ - minZ;
  243. const factor = ( 2 ** 32 - 1 ) / depthDelta; // UINT32_MAX / z range
  244. for ( let i = 0, l = list.length; i < l; i ++ ) {
  245. list[ i ].z -= minZ;
  246. list[ i ].z *= factor;
  247. }
  248. // perform a fast-sort using the hybrid radix sort function
  249. radixSort( list, options );
  250. }
  251. function onWindowResize() {
  252. const width = window.innerWidth;
  253. const height = window.innerHeight;
  254. camera.aspect = width / height;
  255. camera.updateProjectionMatrix();
  256. renderer.setSize( width, height );
  257. }
  258. function animate() {
  259. animateMeshes();
  260. controls.update();
  261. stats.update();
  262. render();
  263. }
  264. function animateMeshes() {
  265. const loopNum = Math.min( api.count, api.dynamic );
  266. if ( api.method === Method.BATCHED ) {
  267. for ( let i = 0; i < loopNum; i ++ ) {
  268. const rotationMatrix = mesh.userData.rotationSpeeds[ i ];
  269. const id = ids[ i ];
  270. mesh.getMatrixAt( id, matrix );
  271. matrix.multiply( rotationMatrix );
  272. mesh.setMatrixAt( id, matrix );
  273. }
  274. } else {
  275. for ( let i = 0; i < loopNum; i ++ ) {
  276. const child = mesh.children[ i ];
  277. const rotationSpeed = child.userData.rotationSpeed;
  278. child.rotation.set(
  279. child.rotation.x + rotationSpeed.x,
  280. child.rotation.y + rotationSpeed.y,
  281. child.rotation.z + rotationSpeed.z
  282. );
  283. }
  284. }
  285. }
  286. function render() {
  287. if ( mesh.isBatchedMesh ) {
  288. mesh.sortObjects = api.sortObjects;
  289. mesh.perObjectFrustumCulled = api.perObjectFrustumCulled;
  290. mesh.setCustomSort( api.useCustomSort ? sortFunction : null );
  291. }
  292. renderer.render( scene, camera );
  293. }
  294. </script>
  295. </body>
  296. </html>
粤ICP备19079148号