BatchedMesh.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. import {
  2. BufferAttribute,
  3. BufferGeometry,
  4. DataTexture,
  5. FloatType,
  6. MathUtils,
  7. Matrix4,
  8. Mesh,
  9. RGBAFormat
  10. } from 'three';
  11. const ID_ATTR_NAME = 'batchId';
  12. const _identityMatrix = new Matrix4();
  13. const _zeroScaleMatrix = new Matrix4().set(
  14. 0, 0, 0, 0,
  15. 0, 0, 0, 0,
  16. 0, 0, 0, 0,
  17. 0, 0, 0, 1,
  18. );
  19. // @TODO: SkinnedMesh support?
  20. // @TODO: Future work if needed. Move into the core. Can be optimized more with WEBGL_multi_draw.
  21. // @TODO: geometry.groups support?
  22. // @TODO: geometry.drawRange support?
  23. // @TODO: geometry.morphAttributes support?
  24. // @TODO: Support uniform parameter per geometry
  25. // copies data from attribute "src" into "target" starting at "targetOffset"
  26. function copyAttributeData( src, target, targetOffset = 0 ) {
  27. const itemSize = target.itemSize;
  28. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  29. // use the component getters and setters if the array data cannot
  30. // be copied directly
  31. const vertexCount = src.count;
  32. for ( let i = 0; i < vertexCount; i ++ ) {
  33. for ( let c = 0; c < itemSize; c ++ ) {
  34. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  35. }
  36. }
  37. } else {
  38. // faster copy approach using typed array set function
  39. target.array.set( src.array, targetOffset * itemSize );
  40. }
  41. target.needsUpdate = true;
  42. }
  43. class BatchedMesh extends Mesh {
  44. constructor( maxGeometryCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  45. super( new BufferGeometry(), material );
  46. this.isBatchedMesh = true;
  47. this._drawRanges = [];
  48. this._reservedRanges = [];
  49. this._visible = [];
  50. this._active = [];
  51. this._maxGeometryCount = maxGeometryCount;
  52. this._maxVertexCount = maxVertexCount;
  53. this._maxIndexCount = maxIndexCount;
  54. this._geometryInitialized = false;
  55. this._geometryCount = 0;
  56. this._multiDrawCounts = null;
  57. this._multiDrawStarts = null;
  58. this._multiDrawCount = 0;
  59. // Local matrix per geometry by using data texture
  60. this._matricesTexture = null;
  61. // @TODO: Calculate the entire binding box and make frustumCulled true
  62. this.frustumCulled = false;
  63. this._initMatricesTexture();
  64. }
  65. _initMatricesTexture() {
  66. // layout (1 matrix = 4 pixels)
  67. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  68. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  69. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  70. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  71. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  72. let size = Math.sqrt( this._maxGeometryCount * 4 ); // 4 pixels needed for 1 matrix
  73. size = MathUtils.ceilPowerOfTwo( size );
  74. size = Math.max( size, 4 );
  75. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  76. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  77. this._matricesTexture = matricesTexture;
  78. }
  79. _initializeGeometry( reference ) {
  80. const geometry = this.geometry;
  81. const maxVertexCount = this._maxVertexCount;
  82. const maxGeometryCount = this._maxGeometryCount;
  83. const maxIndexCount = this._maxIndexCount;
  84. if ( this._geometryInitialized === false ) {
  85. for ( const attributeName in reference.attributes ) {
  86. const srcAttribute = reference.getAttribute( attributeName );
  87. const { array, itemSize, normalized } = srcAttribute;
  88. const dstArray = new array.constructor( maxVertexCount * itemSize );
  89. const dstAttribute = new srcAttribute.constructor( dstArray, itemSize, normalized );
  90. dstAttribute.setUsage( srcAttribute.usage );
  91. geometry.setAttribute( attributeName, dstAttribute );
  92. }
  93. if ( reference.getIndex() !== null ) {
  94. const indexArray = maxVertexCount > 65536
  95. ? new Uint32Array( maxIndexCount )
  96. : new Uint16Array( maxIndexCount );
  97. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  98. }
  99. const idArray = maxGeometryCount > 65536
  100. ? new Uint32Array( maxVertexCount )
  101. : new Uint16Array( maxVertexCount );
  102. geometry.setAttribute( ID_ATTR_NAME, new BufferAttribute( idArray, 1 ) );
  103. this._geometryInitialized = true;
  104. this._multiDrawCounts = new Int32Array( maxGeometryCount );
  105. this._multiDrawStarts = new Int32Array( maxGeometryCount );
  106. }
  107. }
  108. // Make sure the geometry is compatible with the existing combined geometry atributes
  109. _validateGeometry( geometry ) {
  110. // check that the geometry doesn't have a version of our reserved id attribute
  111. if ( geometry.getAttribute( ID_ATTR_NAME ) ) {
  112. throw new Error( `BatchedMesh: Geometry cannot use attribute "${ ID_ATTR_NAME }"` );
  113. }
  114. // check to ensure the geometries are using consistent attributes and indices
  115. const batchGeometry = this.geometry;
  116. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  117. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  118. }
  119. for ( const attributeName in batchGeometry.attributes ) {
  120. if ( attributeName === ID_ATTR_NAME ) {
  121. continue;
  122. }
  123. if ( ! geometry.hasAttribute( attributeName ) ) {
  124. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  125. }
  126. const srcAttribute = geometry.getAttribute( attributeName );
  127. const dstAttribute = batchGeometry.getAttribute( attributeName );
  128. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  129. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  130. }
  131. }
  132. }
  133. getGeometryCount() {
  134. return this._geometryCount;
  135. }
  136. getVertexCount() {
  137. const reservedRanges = this._reservedRanges;
  138. if ( reservedRanges.length === 0 ) {
  139. return 0;
  140. } else {
  141. const finalRange = reservedRanges[ reservedRanges.length - 1 ];
  142. return finalRange.vertexStart + finalRange.vertexCount;
  143. }
  144. }
  145. getIndexCount() {
  146. const reservedRanges = this._reservedRanges;
  147. const geometry = this.geometry;
  148. if ( geometry.getIndex() === null || reservedRanges.length === 0 ) {
  149. return 0;
  150. } else {
  151. const finalRange = reservedRanges[ reservedRanges.length - 1 ];
  152. return finalRange.indexStart + finalRange.indexCount;
  153. }
  154. }
  155. addGeometry( geometry, vertexCount = - 1, indexCount = - 1 ) {
  156. this._initializeGeometry( geometry );
  157. this._validateGeometry( geometry );
  158. // ensure we're not over geometry
  159. if ( this._geometryCount >= this._maxGeometryCount ) {
  160. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  161. }
  162. // get the necessary range fo the geometry
  163. const reservedRange = {
  164. vertexStart: - 1,
  165. vertexCount: - 1,
  166. indexStart: - 1,
  167. indexCount: - 1,
  168. };
  169. let lastRange = null;
  170. const reservedRanges = this._reservedRanges;
  171. const drawRanges = this._drawRanges;
  172. if ( this._geometryCount !== 0 ) {
  173. lastRange = reservedRanges[ reservedRanges.length - 1 ];
  174. }
  175. if ( vertexCount === - 1 ) {
  176. reservedRange.vertexCount = geometry.getAttribute( 'position' ).count;
  177. } else {
  178. reservedRange.vertexCount = vertexCount;
  179. }
  180. if ( lastRange === null ) {
  181. reservedRange.vertexStart = 0;
  182. } else {
  183. reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount;
  184. }
  185. const index = geometry.getIndex();
  186. const hasIndex = index !== null;
  187. if ( hasIndex ) {
  188. if ( indexCount === - 1 ) {
  189. reservedRange.indexCount = index.count;
  190. } else {
  191. reservedRange.indexCount = indexCount;
  192. }
  193. if ( lastRange === null ) {
  194. reservedRange.indexStart = 0;
  195. } else {
  196. reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount;
  197. }
  198. }
  199. if (
  200. reservedRange.indexStart !== - 1 &&
  201. reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount ||
  202. reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount
  203. ) {
  204. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  205. }
  206. const visible = this._visible;
  207. const active = this._active;
  208. const matricesTexture = this._matricesTexture;
  209. const matricesArray = this._matricesTexture.image.data;
  210. // push new visibility states
  211. visible.push( true );
  212. active.push( true );
  213. // update id
  214. const geometryId = this._geometryCount;
  215. this._geometryCount ++;
  216. // initialize matrix information
  217. _identityMatrix.toArray( matricesArray, geometryId * 16 );
  218. matricesTexture.needsUpdate = true;
  219. // add the reserved range and draw range objects
  220. reservedRanges.push( reservedRange );
  221. drawRanges.push( {
  222. start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart,
  223. count: - 1
  224. } );
  225. // set the id for the geometry
  226. const idAttribute = this.geometry.getAttribute( ID_ATTR_NAME );
  227. for ( let i = 0; i < reservedRange.vertexCount; i ++ ) {
  228. idAttribute.setX( reservedRange.vertexStart + i, geometryId );
  229. }
  230. idAttribute.needsUpdate = true;
  231. // update the geometry
  232. this.setGeometryAt( geometryId, geometry );
  233. return geometryId;
  234. }
  235. setGeometryAt( id, geometry ) {
  236. if ( id >= this._geometryCount ) {
  237. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  238. }
  239. this._validateGeometry( geometry );
  240. const batchGeometry = this.geometry;
  241. const hasIndex = batchGeometry.getIndex() !== null;
  242. const dstIndex = batchGeometry.getIndex();
  243. const srcIndex = geometry.getIndex();
  244. const reservedRange = this._reservedRanges[ id ];
  245. if (
  246. hasIndex &&
  247. srcIndex.count > reservedRange.indexCount ||
  248. geometry.attributes.position.count > reservedRange.vertexCount
  249. ) {
  250. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  251. }
  252. // copy geometry over
  253. const vertexStart = reservedRange.vertexStart;
  254. const vertexCount = reservedRange.vertexCount;
  255. for ( const attributeName in batchGeometry.attributes ) {
  256. if ( attributeName === ID_ATTR_NAME ) {
  257. continue;
  258. }
  259. // copy attribute data
  260. const srcAttribute = geometry.getAttribute( attributeName );
  261. const dstAttribute = batchGeometry.getAttribute( attributeName );
  262. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  263. // fill the rest in with zeroes
  264. const itemSize = srcAttribute.itemSize;
  265. for ( let i = srcAttribute.count, l = vertexCount; i < l; i ++ ) {
  266. const index = vertexStart + i;
  267. for ( let c = 0; c < itemSize; c ++ ) {
  268. dstAttribute.setComponent( index, c, 0 );
  269. }
  270. }
  271. dstAttribute.needsUpdate = true;
  272. }
  273. // copy index
  274. if ( hasIndex ) {
  275. const indexStart = reservedRange.indexStart;
  276. // copy index data over
  277. for ( let i = 0; i < srcIndex.count; i ++ ) {
  278. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  279. }
  280. // fill the rest in with zeroes
  281. for ( let i = srcIndex.count, l = reservedRange.indexCount; i < l; i ++ ) {
  282. dstIndex.setX( indexStart + i, vertexStart );
  283. }
  284. dstIndex.needsUpdate = true;
  285. }
  286. // set drawRange count
  287. const drawRange = this._drawRanges[ id ];
  288. const posAttr = geometry.getAttribute( 'position' );
  289. drawRange.count = hasIndex ? srcIndex.count : posAttr.count;
  290. return id;
  291. }
  292. deleteGeometry( geometryId ) {
  293. // Note: User needs to call optimize() afterward to pack the data.
  294. const active = this._active;
  295. const matricesArray = this._matricesTexture.image.data;
  296. const matricesTexture = this._matricesTexture;
  297. if ( geometryId >= active.length || active[ geometryId ] === false ) {
  298. return this;
  299. }
  300. active[ geometryId ] = false;
  301. _zeroScaleMatrix.toArray( matricesArray, geometryId * 16 );
  302. matricesTexture.needsUpdate = true;
  303. return this;
  304. }
  305. optimize() {
  306. throw new Error( 'BatchedMesh: Optimize function not implemented.' );
  307. }
  308. setMatrixAt( geometryId, matrix ) {
  309. // @TODO: Map geometryId to index of the arrays because
  310. // optimize() can make geometryId mismatch the index
  311. const active = this._active;
  312. const matricesTexture = this._matricesTexture;
  313. const matricesArray = this._matricesTexture.image.data;
  314. const geometryCount = this._geometryCount;
  315. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  316. return this;
  317. }
  318. matrix.toArray( matricesArray, geometryId * 16 );
  319. matricesTexture.needsUpdate = true;
  320. return this;
  321. }
  322. getMatrixAt( geometryId, matrix ) {
  323. const active = this._active;
  324. const matricesArray = this._matricesTexture.image.data;
  325. const geometryCount = this._geometryCount;
  326. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  327. return null;
  328. }
  329. return matrix.fromArray( matricesArray, geometryId * 16 );
  330. }
  331. setVisibleAt( geometryId, value ) {
  332. const visible = this._visible;
  333. const active = this._active;
  334. const geometryCount = this._geometryCount;
  335. // if the geometry is out of range, not active, or visibility state
  336. // does not change then return early
  337. if (
  338. geometryId >= geometryCount ||
  339. active[ geometryId ] === false ||
  340. visible[ geometryId ] === value
  341. ) {
  342. return this;
  343. }
  344. visible[ geometryId ] = value;
  345. return this;
  346. }
  347. getVisibleAt( geometryId ) {
  348. const visible = this._visible;
  349. const active = this._active;
  350. const geometryCount = this._geometryCount;
  351. // return early if the geometry is out of range or not active
  352. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  353. return false;
  354. }
  355. return visible[ geometryId ];
  356. }
  357. raycast() {
  358. console.warn( 'BatchedMesh: Raycast function not implemented.' );
  359. }
  360. copy() {
  361. // super.copy( source );
  362. throw new Error( 'BatchedMesh: Copy function not implemented.' );
  363. }
  364. toJSON() {
  365. throw new Error( 'BatchedMesh: toJSON function not implemented.' );
  366. }
  367. dispose() {
  368. // Assuming the geometry is not shared with other meshes
  369. this.geometry.dispose();
  370. this._matricesTexture.dispose();
  371. this._matricesTexture = null;
  372. return this;
  373. }
  374. onBeforeRender( _renderer, _scene, _camera, geometry ) {
  375. // the indexed version of the multi draw function requires specifying the start
  376. // offset in bytes.
  377. const index = geometry.getIndex();
  378. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  379. const visible = this._visible;
  380. const multiDrawStarts = this._multiDrawStarts;
  381. const multiDrawCounts = this._multiDrawCounts;
  382. const drawRanges = this._drawRanges;
  383. let count = 0;
  384. for ( let i = 0, l = visible.length; i < l; i ++ ) {
  385. if ( visible[ i ] ) {
  386. const range = drawRanges[ i ];
  387. multiDrawStarts[ count ] = range.start * bytesPerElement;
  388. multiDrawCounts[ count ] = range.count;
  389. count ++;
  390. }
  391. }
  392. this._multiDrawCount = count;
  393. // @TODO: Implement frustum culling for each geometry
  394. // @TODO: Implement geometry sorting for transparent and opaque materials
  395. }
  396. }
  397. export { BatchedMesh };