BufferGeometryUtils.js 15 KB

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