BatchedMesh.js 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  1. import { BufferAttribute } from '../core/BufferAttribute.js';
  2. import { BufferGeometry } from '../core/BufferGeometry.js';
  3. import { DataTexture } from '../textures/DataTexture.js';
  4. import { FloatType } from '../constants.js';
  5. import { Matrix4 } from '../math/Matrix4.js';
  6. import { Mesh } from './Mesh.js';
  7. import { RGBAFormat } from '../constants.js';
  8. import { Box3 } from '../math/Box3.js';
  9. import { Sphere } from '../math/Sphere.js';
  10. import { Frustum } from '../math/Frustum.js';
  11. import { WebGLCoordinateSystem } from '../constants.js';
  12. import { WebGPUCoordinateSystem } from '../constants.js';
  13. import { Vector3 } from '../math/Vector3.js';
  14. function sortOpaque( a, b ) {
  15. return a.z - b.z;
  16. }
  17. function sortTransparent( a, b ) {
  18. return b.z - a.z;
  19. }
  20. class MultiDrawRenderList {
  21. constructor() {
  22. this.index = 0;
  23. this.pool = [];
  24. this.list = [];
  25. }
  26. push( drawRange, z ) {
  27. const pool = this.pool;
  28. const list = this.list;
  29. if ( this.index >= pool.length ) {
  30. pool.push( {
  31. start: - 1,
  32. count: - 1,
  33. z: - 1,
  34. } );
  35. }
  36. const item = pool[ this.index ];
  37. list.push( item );
  38. this.index ++;
  39. item.start = drawRange.start;
  40. item.count = drawRange.count;
  41. item.z = z;
  42. }
  43. reset() {
  44. this.list.length = 0;
  45. this.index = 0;
  46. }
  47. }
  48. const ID_ATTR_NAME = 'batchId';
  49. const _matrix = new Matrix4();
  50. const _identityMatrix = new Matrix4();
  51. const _projScreenMatrix = new Matrix4();
  52. const _frustum = new Frustum();
  53. const _box = new Box3();
  54. const _sphere = new Sphere();
  55. const _vector = new Vector3();
  56. const _renderList = new MultiDrawRenderList();
  57. const _mesh = new Mesh();
  58. const _batchIntersects = [];
  59. // @TODO: SkinnedMesh support?
  60. // @TODO: geometry.groups support?
  61. // @TODO: geometry.drawRange support?
  62. // @TODO: geometry.morphAttributes support?
  63. // @TODO: Support uniform parameter per geometry
  64. // @TODO: Add an "optimize" function to pack geometry and remove data gaps
  65. // copies data from attribute "src" into "target" starting at "targetOffset"
  66. function copyAttributeData( src, target, targetOffset = 0 ) {
  67. const itemSize = target.itemSize;
  68. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  69. // use the component getters and setters if the array data cannot
  70. // be copied directly
  71. const vertexCount = src.count;
  72. for ( let i = 0; i < vertexCount; i ++ ) {
  73. for ( let c = 0; c < itemSize; c ++ ) {
  74. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  75. }
  76. }
  77. } else {
  78. // faster copy approach using typed array set function
  79. target.array.set( src.array, targetOffset * itemSize );
  80. }
  81. target.needsUpdate = true;
  82. }
  83. class BatchedMesh extends Mesh {
  84. constructor( maxGeometryCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  85. super( new BufferGeometry(), material );
  86. this.isBatchedMesh = true;
  87. this.perObjectFrustumCulled = true;
  88. this.sortObjects = true;
  89. this.boundingBox = null;
  90. this.boundingSphere = null;
  91. this._drawRanges = [];
  92. this._reservedRanges = [];
  93. this._visibility = [];
  94. this._active = [];
  95. this._bounds = [];
  96. this._maxGeometryCount = maxGeometryCount;
  97. this._maxVertexCount = maxVertexCount;
  98. this._maxIndexCount = maxIndexCount;
  99. this._geometryInitialized = false;
  100. this._geometryCount = 0;
  101. this._multiDrawCounts = new Int32Array( maxGeometryCount );
  102. this._multiDrawStarts = new Int32Array( maxGeometryCount );
  103. this._multiDrawCount = 0;
  104. this._visibilityChanged = true;
  105. // Local matrix per geometry by using data texture
  106. this._matricesTexture = null;
  107. this._initMatricesTexture();
  108. }
  109. _initMatricesTexture() {
  110. // layout (1 matrix = 4 pixels)
  111. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  112. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  113. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  114. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  115. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  116. let size = Math.sqrt( this._maxGeometryCount * 4 ); // 4 pixels needed for 1 matrix
  117. size = Math.ceil( size / 4 ) * 4;
  118. size = Math.max( size, 4 );
  119. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  120. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  121. this._matricesTexture = matricesTexture;
  122. }
  123. _initializeGeometry( reference ) {
  124. const geometry = this.geometry;
  125. const maxVertexCount = this._maxVertexCount;
  126. const maxGeometryCount = this._maxGeometryCount;
  127. const maxIndexCount = this._maxIndexCount;
  128. if ( this._geometryInitialized === false ) {
  129. for ( const attributeName in reference.attributes ) {
  130. const srcAttribute = reference.getAttribute( attributeName );
  131. const { array, itemSize, normalized } = srcAttribute;
  132. const dstArray = new array.constructor( maxVertexCount * itemSize );
  133. const dstAttribute = new srcAttribute.constructor( dstArray, itemSize, normalized );
  134. dstAttribute.setUsage( srcAttribute.usage );
  135. geometry.setAttribute( attributeName, dstAttribute );
  136. }
  137. if ( reference.getIndex() !== null ) {
  138. const indexArray = maxVertexCount > 65536
  139. ? new Uint32Array( maxIndexCount )
  140. : new Uint16Array( maxIndexCount );
  141. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  142. }
  143. const idArray = maxGeometryCount > 65536
  144. ? new Uint32Array( maxVertexCount )
  145. : new Uint16Array( maxVertexCount );
  146. geometry.setAttribute( ID_ATTR_NAME, new BufferAttribute( idArray, 1 ) );
  147. this._geometryInitialized = true;
  148. }
  149. }
  150. // Make sure the geometry is compatible with the existing combined geometry atributes
  151. _validateGeometry( geometry ) {
  152. // check that the geometry doesn't have a version of our reserved id attribute
  153. if ( geometry.getAttribute( ID_ATTR_NAME ) ) {
  154. throw new Error( `BatchedMesh: Geometry cannot use attribute "${ ID_ATTR_NAME }"` );
  155. }
  156. // check to ensure the geometries are using consistent attributes and indices
  157. const batchGeometry = this.geometry;
  158. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  159. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  160. }
  161. for ( const attributeName in batchGeometry.attributes ) {
  162. if ( attributeName === ID_ATTR_NAME ) {
  163. continue;
  164. }
  165. if ( ! geometry.hasAttribute( attributeName ) ) {
  166. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  167. }
  168. const srcAttribute = geometry.getAttribute( attributeName );
  169. const dstAttribute = batchGeometry.getAttribute( attributeName );
  170. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  171. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  172. }
  173. }
  174. }
  175. getGeometryCount() {
  176. return this._geometryCount;
  177. }
  178. getVertexCount() {
  179. const reservedRanges = this._reservedRanges;
  180. if ( reservedRanges.length === 0 ) {
  181. return 0;
  182. } else {
  183. const finalRange = reservedRanges[ reservedRanges.length - 1 ];
  184. return finalRange.vertexStart + finalRange.vertexCount;
  185. }
  186. }
  187. getIndexCount() {
  188. const reservedRanges = this._reservedRanges;
  189. const geometry = this.geometry;
  190. if ( geometry.getIndex() === null || reservedRanges.length === 0 ) {
  191. return 0;
  192. } else {
  193. const finalRange = reservedRanges[ reservedRanges.length - 1 ];
  194. return finalRange.indexStart + finalRange.indexCount;
  195. }
  196. }
  197. computeBoundingBox() {
  198. if ( this.boundingBox === null ) {
  199. this.boundingBox = new Box3();
  200. }
  201. const geometryCount = this._geometryCount;
  202. const boundingBox = this.boundingBox;
  203. const active = this._active;
  204. boundingBox.makeEmpty();
  205. for ( let i = 0; i < geometryCount; i ++ ) {
  206. if ( active[ i ] === false ) continue;
  207. this.getMatrixAt( i, _matrix );
  208. this.getBoundingBoxAt( i, _box ).applyMatrix4( _matrix );
  209. boundingBox.union( _box );
  210. }
  211. }
  212. computeBoundingSphere() {
  213. if ( this.boundingSphere === null ) {
  214. this.boundingSphere = new Sphere();
  215. }
  216. const geometryCount = this._geometryCount;
  217. const boundingSphere = this.boundingSphere;
  218. const active = this._active;
  219. boundingSphere.makeEmpty();
  220. for ( let i = 0; i < geometryCount; i ++ ) {
  221. if ( active[ i ] === false ) continue;
  222. this.getMatrixAt( i, _matrix );
  223. this.getBoundingSphereAt( i, _sphere ).applyMatrix4( _matrix );
  224. boundingSphere.union( _sphere );
  225. }
  226. }
  227. addGeometry( geometry, vertexCount = - 1, indexCount = - 1 ) {
  228. this._initializeGeometry( geometry );
  229. this._validateGeometry( geometry );
  230. // ensure we're not over geometry
  231. if ( this._geometryCount >= this._maxGeometryCount ) {
  232. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  233. }
  234. // get the necessary range fo the geometry
  235. const reservedRange = {
  236. vertexStart: - 1,
  237. vertexCount: - 1,
  238. indexStart: - 1,
  239. indexCount: - 1,
  240. };
  241. let lastRange = null;
  242. const reservedRanges = this._reservedRanges;
  243. const drawRanges = this._drawRanges;
  244. const bounds = this._bounds;
  245. if ( this._geometryCount !== 0 ) {
  246. lastRange = reservedRanges[ reservedRanges.length - 1 ];
  247. }
  248. if ( vertexCount === - 1 ) {
  249. reservedRange.vertexCount = geometry.getAttribute( 'position' ).count;
  250. } else {
  251. reservedRange.vertexCount = vertexCount;
  252. }
  253. if ( lastRange === null ) {
  254. reservedRange.vertexStart = 0;
  255. } else {
  256. reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount;
  257. }
  258. const index = geometry.getIndex();
  259. const hasIndex = index !== null;
  260. if ( hasIndex ) {
  261. if ( indexCount === - 1 ) {
  262. reservedRange.indexCount = index.count;
  263. } else {
  264. reservedRange.indexCount = indexCount;
  265. }
  266. if ( lastRange === null ) {
  267. reservedRange.indexStart = 0;
  268. } else {
  269. reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount;
  270. }
  271. }
  272. if (
  273. reservedRange.indexStart !== - 1 &&
  274. reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount ||
  275. reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount
  276. ) {
  277. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  278. }
  279. const visibility = this._visibility;
  280. const active = this._active;
  281. const matricesTexture = this._matricesTexture;
  282. const matricesArray = this._matricesTexture.image.data;
  283. // push new visibility states
  284. visibility.push( true );
  285. active.push( true );
  286. // update id
  287. const geometryId = this._geometryCount;
  288. this._geometryCount ++;
  289. // initialize matrix information
  290. _identityMatrix.toArray( matricesArray, geometryId * 16 );
  291. matricesTexture.needsUpdate = true;
  292. // add the reserved range and draw range objects
  293. reservedRanges.push( reservedRange );
  294. drawRanges.push( {
  295. start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart,
  296. count: - 1
  297. } );
  298. bounds.push( {
  299. boxInitialized: false,
  300. box: new Box3(),
  301. sphereInitialized: false,
  302. sphere: new Sphere()
  303. } );
  304. // set the id for the geometry
  305. const idAttribute = this.geometry.getAttribute( ID_ATTR_NAME );
  306. for ( let i = 0; i < reservedRange.vertexCount; i ++ ) {
  307. idAttribute.setX( reservedRange.vertexStart + i, geometryId );
  308. }
  309. idAttribute.needsUpdate = true;
  310. // update the geometry
  311. this.setGeometryAt( geometryId, geometry );
  312. return geometryId;
  313. }
  314. setGeometryAt( id, geometry ) {
  315. if ( id >= this._geometryCount ) {
  316. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  317. }
  318. this._validateGeometry( geometry );
  319. const batchGeometry = this.geometry;
  320. const hasIndex = batchGeometry.getIndex() !== null;
  321. const dstIndex = batchGeometry.getIndex();
  322. const srcIndex = geometry.getIndex();
  323. const reservedRange = this._reservedRanges[ id ];
  324. if (
  325. hasIndex &&
  326. srcIndex.count > reservedRange.indexCount ||
  327. geometry.attributes.position.count > reservedRange.vertexCount
  328. ) {
  329. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  330. }
  331. // copy geometry over
  332. const vertexStart = reservedRange.vertexStart;
  333. const vertexCount = reservedRange.vertexCount;
  334. for ( const attributeName in batchGeometry.attributes ) {
  335. if ( attributeName === ID_ATTR_NAME ) {
  336. continue;
  337. }
  338. // copy attribute data
  339. const srcAttribute = geometry.getAttribute( attributeName );
  340. const dstAttribute = batchGeometry.getAttribute( attributeName );
  341. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  342. // fill the rest in with zeroes
  343. const itemSize = srcAttribute.itemSize;
  344. for ( let i = srcAttribute.count, l = vertexCount; i < l; i ++ ) {
  345. const index = vertexStart + i;
  346. for ( let c = 0; c < itemSize; c ++ ) {
  347. dstAttribute.setComponent( index, c, 0 );
  348. }
  349. }
  350. dstAttribute.needsUpdate = true;
  351. }
  352. // copy index
  353. if ( hasIndex ) {
  354. const indexStart = reservedRange.indexStart;
  355. // copy index data over
  356. for ( let i = 0; i < srcIndex.count; i ++ ) {
  357. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  358. }
  359. // fill the rest in with zeroes
  360. for ( let i = srcIndex.count, l = reservedRange.indexCount; i < l; i ++ ) {
  361. dstIndex.setX( indexStart + i, vertexStart );
  362. }
  363. dstIndex.needsUpdate = true;
  364. }
  365. // store the bounding boxes
  366. const bound = this._bounds[ id ];
  367. if ( geometry.boundingBox !== null ) {
  368. bound.box.copy( geometry.boundingBox );
  369. bound.boxInitialized = true;
  370. } else {
  371. bound.boxInitialized = false;
  372. }
  373. if ( geometry.boundingSphere !== null ) {
  374. bound.sphere.copy( geometry.boundingSphere );
  375. bound.sphereInitialized = true;
  376. } else {
  377. bound.sphereInitialized = false;
  378. }
  379. // set drawRange count
  380. const drawRange = this._drawRanges[ id ];
  381. const posAttr = geometry.getAttribute( 'position' );
  382. drawRange.count = hasIndex ? srcIndex.count : posAttr.count;
  383. this._visibilityChanged = true;
  384. return id;
  385. }
  386. deleteGeometry( geometryId ) {
  387. // Note: User needs to call optimize() afterward to pack the data.
  388. const active = this._active;
  389. if ( geometryId >= active.length || active[ geometryId ] === false ) {
  390. return this;
  391. }
  392. active[ geometryId ] = false;
  393. this._visibilityChanged = true;
  394. return this;
  395. }
  396. // get bounding box and compute it if it doesn't exist
  397. getBoundingBoxAt( id, target ) {
  398. const active = this._active;
  399. if ( active[ id ] === false ) {
  400. return this;
  401. }
  402. // compute bounding box
  403. const bound = this._bounds[ id ];
  404. const box = bound.box;
  405. const geometry = this.geometry;
  406. if ( bound.boxInitialized === false ) {
  407. box.makeEmpty();
  408. const index = geometry.index;
  409. const position = geometry.attributes.position;
  410. const drawRange = this._drawRanges[ id ];
  411. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  412. let iv = i;
  413. if ( index ) {
  414. iv = index.getX( iv );
  415. }
  416. box.expandByPoint( _vector.fromBufferAttribute( position, iv ) );
  417. }
  418. bound.boxInitialized = true;
  419. }
  420. target.copy( box );
  421. return target;
  422. }
  423. // get bounding sphere and compute it if it doesn't exist
  424. getBoundingSphereAt( id, target ) {
  425. const active = this._active;
  426. if ( active[ id ] === false ) {
  427. return this;
  428. }
  429. // compute bounding sphere
  430. const bound = this._bounds[ id ];
  431. const sphere = bound.sphere;
  432. const geometry = this.geometry;
  433. if ( bound.sphereInitialized === false ) {
  434. sphere.makeEmpty();
  435. this.getBoundingBoxAt( id, _box );
  436. _box.getCenter( sphere.center );
  437. const index = geometry.index;
  438. const position = geometry.attributes.position;
  439. const drawRange = this._drawRanges[ id ];
  440. let maxRadiusSq = 0;
  441. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  442. let iv = i;
  443. if ( index ) {
  444. iv = index.getX( iv );
  445. }
  446. _vector.fromBufferAttribute( position, iv );
  447. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector ) );
  448. }
  449. sphere.radius = Math.sqrt( maxRadiusSq );
  450. bound.sphereInitialized = true;
  451. }
  452. target.copy( sphere );
  453. return target;
  454. }
  455. setMatrixAt( geometryId, matrix ) {
  456. // @TODO: Map geometryId to index of the arrays because
  457. // optimize() can make geometryId mismatch the index
  458. const active = this._active;
  459. const matricesTexture = this._matricesTexture;
  460. const matricesArray = this._matricesTexture.image.data;
  461. const geometryCount = this._geometryCount;
  462. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  463. return this;
  464. }
  465. matrix.toArray( matricesArray, geometryId * 16 );
  466. matricesTexture.needsUpdate = true;
  467. return this;
  468. }
  469. getMatrixAt( geometryId, matrix ) {
  470. const active = this._active;
  471. const matricesArray = this._matricesTexture.image.data;
  472. const geometryCount = this._geometryCount;
  473. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  474. return null;
  475. }
  476. return matrix.fromArray( matricesArray, geometryId * 16 );
  477. }
  478. setVisibleAt( geometryId, value ) {
  479. const visibility = this._visibility;
  480. const active = this._active;
  481. const geometryCount = this._geometryCount;
  482. // if the geometry is out of range, not active, or visibility state
  483. // does not change then return early
  484. if (
  485. geometryId >= geometryCount ||
  486. active[ geometryId ] === false ||
  487. visibility[ geometryId ] === value
  488. ) {
  489. return this;
  490. }
  491. visibility[ geometryId ] = value;
  492. this._visibilityChanged = true;
  493. return this;
  494. }
  495. getVisibleAt( geometryId ) {
  496. const visibility = this._visibility;
  497. const active = this._active;
  498. const geometryCount = this._geometryCount;
  499. // return early if the geometry is out of range or not active
  500. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  501. return false;
  502. }
  503. return visibility[ geometryId ];
  504. }
  505. raycast( raycaster, intersects ) {
  506. const visibility = this._visibility;
  507. const active = this._active;
  508. const drawRanges = this._drawRanges;
  509. const geometryCount = this._geometryCount;
  510. const matrixWorld = this.matrixWorld;
  511. const batchGeometry = this.geometry;
  512. // iterate over each geometry
  513. _mesh.material = this.material;
  514. _mesh.geometry.index = batchGeometry.index;
  515. _mesh.geometry.attributes = batchGeometry.attributes;
  516. if ( _mesh.geometry.boundingBox === null ) {
  517. _mesh.geometry.boundingBox = new Box3();
  518. }
  519. if ( _mesh.geometry.boundingSphere === null ) {
  520. _mesh.geometry.boundingSphere = new Sphere();
  521. }
  522. for ( let i = 0; i < geometryCount; i ++ ) {
  523. if ( ! visibility[ i ] || ! active[ i ] ) {
  524. continue;
  525. }
  526. const drawRange = drawRanges[ i ];
  527. _mesh.geometry.setDrawRange( drawRange.start, drawRange.count );
  528. // ge the intersects
  529. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  530. this.getBoundingBoxAt( i, _mesh.geometry.boundingBox );
  531. this.getBoundingSphereAt( i, _mesh.geometry.boundingSphere );
  532. _mesh.raycast( raycaster, _batchIntersects );
  533. // add batch id to the intersects
  534. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  535. const intersect = _batchIntersects[ j ];
  536. intersect.object = this;
  537. intersect.batchId = i;
  538. intersects.push( intersect );
  539. }
  540. _batchIntersects.length = 0;
  541. }
  542. _mesh.material = null;
  543. _mesh.geometry.index = null;
  544. _mesh.geometry.attributes = {};
  545. _mesh.geometry.setDrawRange( 0, Infinity );
  546. }
  547. copy( source ) {
  548. super.copy( source );
  549. this.geometry = source.geometry.clone();
  550. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  551. this.sortObjects = source.sortObjects;
  552. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  553. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  554. this._drawRanges = source._drawRanges.map( range => ( { ...range } ) );
  555. this._reservedRanges = source._reservedRanges.map( range => ( { ...range } ) );
  556. this._visibility = source._visibility.slice();
  557. this._active = source._active.slice();
  558. this._bounds = source._bounds.map( bound => ( {
  559. boxInitialized: bound.boxInitialized,
  560. box: bound.box.clone(),
  561. sphereInitialized: bound.sphereInitialized,
  562. sphere: bound.sphere.clone()
  563. } ) );
  564. this._maxGeometryCount = source._maxGeometryCount;
  565. this._maxVertexCount = source._maxVertexCount;
  566. this._maxIndexCount = source._maxIndexCount;
  567. this._geometryInitialized = source._geometryInitialized;
  568. this._geometryCount = source._geometryCount;
  569. this._multiDrawCounts = source._multiDrawCounts.slice();
  570. this._multiDrawStarts = source._multiDrawStarts.slice();
  571. this._matricesTexture = source._matricesTexture.clone();
  572. this._matricesTexture.image.data = this._matricesTexture.image.slice();
  573. return this;
  574. }
  575. dispose() {
  576. // Assuming the geometry is not shared with other meshes
  577. this.geometry.dispose();
  578. this._matricesTexture.dispose();
  579. this._matricesTexture = null;
  580. return this;
  581. }
  582. onBeforeRender( _renderer, _scene, camera, geometry, material/*, _group*/ ) {
  583. // if visibility has not changed and frustum culling and object sorting is not required
  584. // then skip iterating over all items
  585. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  586. return;
  587. }
  588. // the indexed version of the multi draw function requires specifying the start
  589. // offset in bytes.
  590. const index = geometry.getIndex();
  591. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  592. const visibility = this._visibility;
  593. const multiDrawStarts = this._multiDrawStarts;
  594. const multiDrawCounts = this._multiDrawCounts;
  595. const drawRanges = this._drawRanges;
  596. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  597. // prepare the frustum
  598. if ( perObjectFrustumCulled ) {
  599. _projScreenMatrix
  600. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  601. .multiply( this.matrixWorld );
  602. _frustum.setFromProjectionMatrix(
  603. _projScreenMatrix,
  604. _renderer.isWebGPURenderer ? WebGPUCoordinateSystem : WebGLCoordinateSystem
  605. );
  606. }
  607. let count = 0;
  608. if ( this.sortObjects ) {
  609. // get the camera position
  610. _vector.setFromMatrixPosition( camera.matrixWorld );
  611. for ( let i = 0, l = visibility.length; i < l; i ++ ) {
  612. if ( visibility[ i ] ) {
  613. this.getMatrixAt( i, _matrix );
  614. this.getBoundingSphereAt( i, _sphere ).applyMatrix4( _matrix );
  615. // determine whether the batched geometry is within the frustum
  616. let culled = false;
  617. if ( perObjectFrustumCulled ) {
  618. // get the bounds in camera space
  619. this.getMatrixAt( i, _matrix );
  620. // get the bounds
  621. this.getBoundingBoxAt( i, _box ).applyMatrix4( _matrix );
  622. culled = ! _frustum.intersectsBox( _box ) || ! _frustum.intersectsSphere( _sphere );
  623. }
  624. if ( ! culled ) {
  625. // get the distance from camera used for sorting
  626. const z = _vector.distanceToSquared( _sphere.center );
  627. _renderList.push( drawRanges[ i ], z );
  628. }
  629. }
  630. }
  631. // Sort the draw ranges and prep for rendering
  632. const list = _renderList.list;
  633. list.sort( material.transparent ? sortTransparent : sortOpaque );
  634. for ( let i = 0, l = list.length; i < l; i ++ ) {
  635. const item = list[ i ];
  636. multiDrawStarts[ count ] = item.start * bytesPerElement;
  637. multiDrawCounts[ count ] = item.count;
  638. count ++;
  639. }
  640. _renderList.reset();
  641. } else {
  642. for ( let i = 0, l = visibility.length; i < l; i ++ ) {
  643. if ( visibility[ i ] ) {
  644. // determine whether the batched geometry is within the frustum
  645. let culled = false;
  646. if ( perObjectFrustumCulled ) {
  647. // get the bounds in camera space
  648. this.getMatrixAt( i, _matrix );
  649. // get the bounds
  650. this.getBoundingBoxAt( i, _box ).applyMatrix4( _matrix );
  651. this.getBoundingSphereAt( i, _sphere ).applyMatrix4( _matrix );
  652. culled = ! _frustum.intersectsBox( _box ) || ! _frustum.intersectsSphere( _sphere );
  653. }
  654. if ( ! culled ) {
  655. const range = drawRanges[ i ];
  656. multiDrawStarts[ count ] = range.start * bytesPerElement;
  657. multiDrawCounts[ count ] = range.count;
  658. count ++;
  659. }
  660. }
  661. }
  662. }
  663. this._multiDrawCount = count;
  664. this._visibilityChanged = false;
  665. }
  666. }
  667. export { BatchedMesh };