BufferGeometryUtils.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. import {
  2. BufferAttribute,
  3. BufferGeometry,
  4. InterleavedBuffer,
  5. InterleavedBufferAttribute,
  6. TriangleFanDrawMode,
  7. TriangleStripDrawMode,
  8. TrianglesDrawMode
  9. } from '../../../build/three.module.js';
  10. var BufferGeometryUtils = {
  11. computeTangents: function ( geometry ) {
  12. geometry.computeTangents();
  13. console.warn( 'THREE.BufferGeometryUtils: .computeTangents() has been removed. Use BufferGeometry.computeTangents() instead.' );
  14. },
  15. /**
  16. * @param {Array<BufferGeometry>} geometries
  17. * @param {Boolean} useGroups
  18. * @return {BufferGeometry}
  19. */
  20. mergeBufferGeometries: function ( geometries, useGroups ) {
  21. var isIndexed = geometries[ 0 ].index !== null;
  22. var attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) );
  23. var morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) );
  24. var attributes = {};
  25. var morphAttributes = {};
  26. var morphTargetsRelative = geometries[ 0 ].morphTargetsRelative;
  27. var mergedGeometry = new BufferGeometry();
  28. var offset = 0;
  29. for ( var i = 0; i < geometries.length; ++ i ) {
  30. var geometry = geometries[ i ];
  31. var attributesCount = 0;
  32. // ensure that all geometries are indexed, or none
  33. if ( isIndexed !== ( geometry.index !== null ) ) {
  34. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.' );
  35. return null;
  36. }
  37. // gather attributes, exit early if they're different
  38. for ( var name in geometry.attributes ) {
  39. if ( ! attributesUsed.has( name ) ) {
  40. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure "' + name + '" attribute exists among all geometries, or in none of them.' );
  41. return null;
  42. }
  43. if ( attributes[ name ] === undefined ) attributes[ name ] = [];
  44. attributes[ name ].push( geometry.attributes[ name ] );
  45. attributesCount ++;
  46. }
  47. // ensure geometries have the same number of attributes
  48. if ( attributesCount !== attributesUsed.size ) {
  49. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.' );
  50. return null;
  51. }
  52. // gather morph attributes, exit early if they're different
  53. if ( morphTargetsRelative !== geometry.morphTargetsRelative ) {
  54. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.' );
  55. return null;
  56. }
  57. for ( var name in geometry.morphAttributes ) {
  58. if ( ! morphAttributesUsed.has( name ) ) {
  59. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.' );
  60. return null;
  61. }
  62. if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = [];
  63. morphAttributes[ name ].push( geometry.morphAttributes[ name ] );
  64. }
  65. // gather .userData
  66. mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || [];
  67. mergedGeometry.userData.mergedUserData.push( geometry.userData );
  68. if ( useGroups ) {
  69. var count;
  70. if ( isIndexed ) {
  71. count = geometry.index.count;
  72. } else if ( geometry.attributes.position !== undefined ) {
  73. count = geometry.attributes.position.count;
  74. } else {
  75. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute' );
  76. return null;
  77. }
  78. mergedGeometry.addGroup( offset, count, i );
  79. offset += count;
  80. }
  81. }
  82. // merge indices
  83. if ( isIndexed ) {
  84. var indexOffset = 0;
  85. var mergedIndex = [];
  86. for ( var i = 0; i < geometries.length; ++ i ) {
  87. var index = geometries[ i ].index;
  88. for ( var j = 0; j < index.count; ++ j ) {
  89. mergedIndex.push( index.getX( j ) + indexOffset );
  90. }
  91. indexOffset += geometries[ i ].attributes.position.count;
  92. }
  93. mergedGeometry.setIndex( mergedIndex );
  94. }
  95. // merge attributes
  96. for ( var name in attributes ) {
  97. var mergedAttribute = this.mergeBufferAttributes( attributes[ name ] );
  98. if ( ! mergedAttribute ) {
  99. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' attribute.' );
  100. return null;
  101. }
  102. mergedGeometry.setAttribute( name, mergedAttribute );
  103. }
  104. // merge morph attributes
  105. for ( var name in morphAttributes ) {
  106. var numMorphTargets = morphAttributes[ name ][ 0 ].length;
  107. if ( numMorphTargets === 0 ) break;
  108. mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
  109. mergedGeometry.morphAttributes[ name ] = [];
  110. for ( var i = 0; i < numMorphTargets; ++ i ) {
  111. var morphAttributesToMerge = [];
  112. for ( var j = 0; j < morphAttributes[ name ].length; ++ j ) {
  113. morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] );
  114. }
  115. var mergedMorphAttribute = this.mergeBufferAttributes( morphAttributesToMerge );
  116. if ( ! mergedMorphAttribute ) {
  117. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' morphAttribute.' );
  118. return null;
  119. }
  120. mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute );
  121. }
  122. }
  123. return mergedGeometry;
  124. },
  125. /**
  126. * @param {Array<BufferAttribute>} attributes
  127. * @return {BufferAttribute}
  128. */
  129. mergeBufferAttributes: function ( attributes ) {
  130. var TypedArray;
  131. var itemSize;
  132. var normalized;
  133. var arrayLength = 0;
  134. for ( var i = 0; i < attributes.length; ++ i ) {
  135. var attribute = attributes[ i ];
  136. if ( attribute.isInterleavedBufferAttribute ) {
  137. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported.' );
  138. return null;
  139. }
  140. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  141. if ( TypedArray !== attribute.array.constructor ) {
  142. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.' );
  143. return null;
  144. }
  145. if ( itemSize === undefined ) itemSize = attribute.itemSize;
  146. if ( itemSize !== attribute.itemSize ) {
  147. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.' );
  148. return null;
  149. }
  150. if ( normalized === undefined ) normalized = attribute.normalized;
  151. if ( normalized !== attribute.normalized ) {
  152. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.' );
  153. return null;
  154. }
  155. arrayLength += attribute.array.length;
  156. }
  157. var array = new TypedArray( arrayLength );
  158. var offset = 0;
  159. for ( var i = 0; i < attributes.length; ++ i ) {
  160. array.set( attributes[ i ].array, offset );
  161. offset += attributes[ i ].array.length;
  162. }
  163. return new BufferAttribute( array, itemSize, normalized );
  164. },
  165. /**
  166. * @param {Array<BufferAttribute>} attributes
  167. * @return {Array<InterleavedBufferAttribute>}
  168. */
  169. interleaveAttributes: function ( attributes ) {
  170. // Interleaves the provided attributes into an InterleavedBuffer and returns
  171. // a set of InterleavedBufferAttributes for each attribute
  172. var TypedArray;
  173. var arrayLength = 0;
  174. var stride = 0;
  175. // calculate the the length and type of the interleavedBuffer
  176. for ( var i = 0, l = attributes.length; i < l; ++ i ) {
  177. var attribute = attributes[ i ];
  178. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  179. if ( TypedArray !== attribute.array.constructor ) {
  180. console.error( 'AttributeBuffers of different types cannot be interleaved' );
  181. return null;
  182. }
  183. arrayLength += attribute.array.length;
  184. stride += attribute.itemSize;
  185. }
  186. // Create the set of buffer attributes
  187. var interleavedBuffer = new InterleavedBuffer( new TypedArray( arrayLength ), stride );
  188. var offset = 0;
  189. var res = [];
  190. var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  191. var setters = [ 'setX', 'setY', 'setZ', 'setW' ];
  192. for ( var j = 0, l = attributes.length; j < l; j ++ ) {
  193. var attribute = attributes[ j ];
  194. var itemSize = attribute.itemSize;
  195. var count = attribute.count;
  196. var iba = new InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
  197. res.push( iba );
  198. offset += itemSize;
  199. // Move the data for each attribute into the new interleavedBuffer
  200. // at the appropriate offset
  201. for ( var c = 0; c < count; c ++ ) {
  202. for ( var k = 0; k < itemSize; k ++ ) {
  203. iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
  204. }
  205. }
  206. }
  207. return res;
  208. },
  209. /**
  210. * @param {Array<BufferGeometry>} geometry
  211. * @return {number}
  212. */
  213. estimateBytesUsed: function ( geometry ) {
  214. // Return the estimated memory used by this geometry in bytes
  215. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  216. // for InterleavedBufferAttributes.
  217. var mem = 0;
  218. for ( var name in geometry.attributes ) {
  219. var attr = geometry.getAttribute( name );
  220. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  221. }
  222. var indices = geometry.getIndex();
  223. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  224. return mem;
  225. },
  226. /**
  227. * @param {BufferGeometry} geometry
  228. * @param {number} tolerance
  229. * @return {BufferGeometry>}
  230. */
  231. mergeVertices: function ( geometry, tolerance = 1e-4 ) {
  232. tolerance = Math.max( tolerance, Number.EPSILON );
  233. // Generate an index buffer if the geometry doesn't have one, or optimize it
  234. // if it's already available.
  235. var hashToIndex = {};
  236. var indices = geometry.getIndex();
  237. var positions = geometry.getAttribute( 'position' );
  238. var vertexCount = indices ? indices.count : positions.count;
  239. // next value for triangle indices
  240. var nextIndex = 0;
  241. // attributes and new attribute arrays
  242. var attributeNames = Object.keys( geometry.attributes );
  243. var attrArrays = {};
  244. var morphAttrsArrays = {};
  245. var newIndices = [];
  246. var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  247. // initialize the arrays
  248. for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
  249. var name = attributeNames[ i ];
  250. attrArrays[ name ] = [];
  251. var morphAttr = geometry.morphAttributes[ name ];
  252. if ( morphAttr ) {
  253. morphAttrsArrays[ name ] = new Array( morphAttr.length ).fill().map( () => [] );
  254. }
  255. }
  256. // convert the error tolerance to an amount of decimal places to truncate to
  257. var decimalShift = Math.log10( 1 / tolerance );
  258. var shiftMultiplier = Math.pow( 10, decimalShift );
  259. for ( var i = 0; i < vertexCount; i ++ ) {
  260. var index = indices ? indices.getX( i ) : i;
  261. // Generate a hash for the vertex attributes at the current index 'i'
  262. var hash = '';
  263. for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
  264. var name = attributeNames[ j ];
  265. var attribute = geometry.getAttribute( name );
  266. var itemSize = attribute.itemSize;
  267. for ( var k = 0; k < itemSize; k ++ ) {
  268. // double tilde truncates the decimal value
  269. hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * shiftMultiplier ) },`;
  270. }
  271. }
  272. // Add another reference to the vertex if it's already
  273. // used by another index
  274. if ( hash in hashToIndex ) {
  275. newIndices.push( hashToIndex[ hash ] );
  276. } else {
  277. // copy data to the new index in the attribute arrays
  278. for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
  279. var name = attributeNames[ j ];
  280. var attribute = geometry.getAttribute( name );
  281. var morphAttr = geometry.morphAttributes[ name ];
  282. var itemSize = attribute.itemSize;
  283. var newarray = attrArrays[ name ];
  284. var newMorphArrays = morphAttrsArrays[ name ];
  285. for ( var k = 0; k < itemSize; k ++ ) {
  286. var getterFunc = getters[ k ];
  287. newarray.push( attribute[ getterFunc ]( index ) );
  288. if ( morphAttr ) {
  289. for ( var m = 0, ml = morphAttr.length; m < ml; m ++ ) {
  290. newMorphArrays[ m ].push( morphAttr[ m ][ getterFunc ]( index ) );
  291. }
  292. }
  293. }
  294. }
  295. hashToIndex[ hash ] = nextIndex;
  296. newIndices.push( nextIndex );
  297. nextIndex ++;
  298. }
  299. }
  300. // Generate typed arrays from new attribute arrays and update
  301. // the attributeBuffers
  302. const result = geometry.clone();
  303. for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
  304. var name = attributeNames[ i ];
  305. var oldAttribute = geometry.getAttribute( name );
  306. var buffer = new oldAttribute.array.constructor( attrArrays[ name ] );
  307. var attribute = new BufferAttribute( buffer, oldAttribute.itemSize, oldAttribute.normalized );
  308. result.setAttribute( name, attribute );
  309. // Update the attribute arrays
  310. if ( name in morphAttrsArrays ) {
  311. for ( var j = 0; j < morphAttrsArrays[ name ].length; j ++ ) {
  312. var oldMorphAttribute = geometry.morphAttributes[ name ][ j ];
  313. var buffer = new oldMorphAttribute.array.constructor( morphAttrsArrays[ name ][ j ] );
  314. var morphAttribute = new BufferAttribute( buffer, oldMorphAttribute.itemSize, oldMorphAttribute.normalized );
  315. result.morphAttributes[ name ][ j ] = morphAttribute;
  316. }
  317. }
  318. }
  319. // indices
  320. result.setIndex( newIndices );
  321. return result;
  322. },
  323. /**
  324. * @param {BufferGeometry} geometry
  325. * @param {number} drawMode
  326. * @return {BufferGeometry>}
  327. */
  328. toTrianglesDrawMode: function ( geometry, drawMode ) {
  329. if ( drawMode === TrianglesDrawMode ) {
  330. console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' );
  331. return geometry;
  332. }
  333. if ( drawMode === TriangleFanDrawMode || drawMode === TriangleStripDrawMode ) {
  334. var index = geometry.getIndex();
  335. // generate index if not present
  336. if ( index === null ) {
  337. var indices = [];
  338. var position = geometry.getAttribute( 'position' );
  339. if ( position !== undefined ) {
  340. for ( var i = 0; i < position.count; i ++ ) {
  341. indices.push( i );
  342. }
  343. geometry.setIndex( indices );
  344. index = geometry.getIndex();
  345. } else {
  346. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  347. return geometry;
  348. }
  349. }
  350. //
  351. var numberOfTriangles = index.count - 2;
  352. var newIndices = [];
  353. if ( drawMode === TriangleFanDrawMode ) {
  354. // gl.TRIANGLE_FAN
  355. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  356. newIndices.push( index.getX( 0 ) );
  357. newIndices.push( index.getX( i ) );
  358. newIndices.push( index.getX( i + 1 ) );
  359. }
  360. } else {
  361. // gl.TRIANGLE_STRIP
  362. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  363. if ( i % 2 === 0 ) {
  364. newIndices.push( index.getX( i ) );
  365. newIndices.push( index.getX( i + 1 ) );
  366. newIndices.push( index.getX( i + 2 ) );
  367. } else {
  368. newIndices.push( index.getX( i + 2 ) );
  369. newIndices.push( index.getX( i + 1 ) );
  370. newIndices.push( index.getX( i ) );
  371. }
  372. }
  373. }
  374. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  375. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  376. }
  377. // build final geometry
  378. var newGeometry = geometry.clone();
  379. newGeometry.setIndex( newIndices );
  380. newGeometry.clearGroups();
  381. return newGeometry;
  382. } else {
  383. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode );
  384. return geometry;
  385. }
  386. }
  387. };
  388. export { BufferGeometryUtils };