BufferGeometryUtils.js 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  1. ( function () {
  2. function computeTangents() {
  3. throw new Error( 'BufferGeometryUtils: computeTangents renamed to computeMikkTSpaceTangents.' );
  4. }
  5. function computeMikkTSpaceTangents( geometry, MikkTSpace, negateSign = true ) {
  6. if ( ! MikkTSpace || ! MikkTSpace.isReady ) {
  7. throw new Error( 'BufferGeometryUtils: Initialized MikkTSpace library required.' );
  8. }
  9. if ( ! geometry.hasAttribute( 'position' ) || ! geometry.hasAttribute( 'normal' ) || ! geometry.hasAttribute( 'uv' ) ) {
  10. throw new Error( 'BufferGeometryUtils: Tangents require "position", "normal", and "uv" attributes.' );
  11. }
  12. function getAttributeArray( attribute ) {
  13. if ( attribute.normalized || attribute.isInterleavedBufferAttribute ) {
  14. const dstArray = new Float32Array( attribute.getCount() * attribute.itemSize );
  15. for ( let i = 0, j = 0; i < attribute.getCount(); i ++ ) {
  16. dstArray[ j ++ ] = attribute.getX( i );
  17. dstArray[ j ++ ] = attribute.getY( i );
  18. if ( attribute.itemSize > 2 ) {
  19. dstArray[ j ++ ] = attribute.getZ( i );
  20. }
  21. }
  22. return dstArray;
  23. }
  24. if ( attribute.array instanceof Float32Array ) {
  25. return attribute.array;
  26. }
  27. return new Float32Array( attribute.array );
  28. } // MikkTSpace algorithm requires non-indexed input.
  29. const _geometry = geometry.index ? geometry.toNonIndexed() : geometry; // Compute vertex tangents.
  30. const tangents = MikkTSpace.generateTangents( getAttributeArray( _geometry.attributes.position ), getAttributeArray( _geometry.attributes.normal ), getAttributeArray( _geometry.attributes.uv ) ); // Texture coordinate convention of glTF differs from the apparent
  31. // default of the MikkTSpace library; .w component must be flipped.
  32. if ( negateSign ) {
  33. for ( let i = 3; i < tangents.length; i += 4 ) {
  34. tangents[ i ] *= - 1;
  35. }
  36. } //
  37. _geometry.setAttribute( 'tangent', new THREE.BufferAttribute( tangents, 4 ) );
  38. if ( geometry !== _geometry ) {
  39. geometry.copy( _geometry );
  40. }
  41. return geometry;
  42. }
  43. /**
  44. * @param {Array<BufferGeometry>} geometries
  45. * @param {Boolean} useGroups
  46. * @return {BufferGeometry}
  47. */
  48. function mergeBufferGeometries( geometries, useGroups = false ) {
  49. const isIndexed = geometries[ 0 ].index !== null;
  50. const attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) );
  51. const morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) );
  52. const attributes = {};
  53. const morphAttributes = {};
  54. const morphTargetsRelative = geometries[ 0 ].morphTargetsRelative;
  55. const mergedGeometry = new THREE.BufferGeometry();
  56. let offset = 0;
  57. for ( let i = 0; i < geometries.length; ++ i ) {
  58. const geometry = geometries[ i ];
  59. let attributesCount = 0; // ensure that all geometries are indexed, or none
  60. if ( isIndexed !== ( geometry.index !== null ) ) {
  61. 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.' );
  62. return null;
  63. } // gather attributes, exit early if they're different
  64. for ( const name in geometry.attributes ) {
  65. if ( ! attributesUsed.has( name ) ) {
  66. 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.' );
  67. return null;
  68. }
  69. if ( attributes[ name ] === undefined ) attributes[ name ] = [];
  70. attributes[ name ].push( geometry.attributes[ name ] );
  71. attributesCount ++;
  72. } // ensure geometries have the same number of attributes
  73. if ( attributesCount !== attributesUsed.size ) {
  74. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.' );
  75. return null;
  76. } // gather morph attributes, exit early if they're different
  77. if ( morphTargetsRelative !== geometry.morphTargetsRelative ) {
  78. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.' );
  79. return null;
  80. }
  81. for ( const name in geometry.morphAttributes ) {
  82. if ( ! morphAttributesUsed.has( name ) ) {
  83. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.' );
  84. return null;
  85. }
  86. if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = [];
  87. morphAttributes[ name ].push( geometry.morphAttributes[ name ] );
  88. }
  89. if ( useGroups ) {
  90. let count;
  91. if ( isIndexed ) {
  92. count = geometry.index.count;
  93. } else if ( geometry.attributes.position !== undefined ) {
  94. count = geometry.attributes.position.count;
  95. } else {
  96. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute' );
  97. return null;
  98. }
  99. mergedGeometry.addGroup( offset, count, i );
  100. offset += count;
  101. }
  102. } // merge indices
  103. if ( isIndexed ) {
  104. let indexOffset = 0;
  105. const mergedIndex = [];
  106. for ( let i = 0; i < geometries.length; ++ i ) {
  107. const index = geometries[ i ].index;
  108. for ( let j = 0; j < index.count; ++ j ) {
  109. mergedIndex.push( index.getX( j ) + indexOffset );
  110. }
  111. indexOffset += geometries[ i ].attributes.position.count;
  112. }
  113. mergedGeometry.setIndex( mergedIndex );
  114. } // merge attributes
  115. for ( const name in attributes ) {
  116. const mergedAttribute = mergeBufferAttributes( attributes[ name ] );
  117. if ( ! mergedAttribute ) {
  118. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' attribute.' );
  119. return null;
  120. }
  121. mergedGeometry.setAttribute( name, mergedAttribute );
  122. } // merge morph attributes
  123. for ( const name in morphAttributes ) {
  124. const numMorphTargets = morphAttributes[ name ][ 0 ].length;
  125. if ( numMorphTargets === 0 ) break;
  126. mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
  127. mergedGeometry.morphAttributes[ name ] = [];
  128. for ( let i = 0; i < numMorphTargets; ++ i ) {
  129. const morphAttributesToMerge = [];
  130. for ( let j = 0; j < morphAttributes[ name ].length; ++ j ) {
  131. morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] );
  132. }
  133. const mergedMorphAttribute = mergeBufferAttributes( morphAttributesToMerge );
  134. if ( ! mergedMorphAttribute ) {
  135. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' morphAttribute.' );
  136. return null;
  137. }
  138. mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute );
  139. }
  140. }
  141. return mergedGeometry;
  142. }
  143. /**
  144. * @param {Array<BufferAttribute>} attributes
  145. * @return {BufferAttribute}
  146. */
  147. function mergeBufferAttributes( attributes ) {
  148. let TypedArray;
  149. let itemSize;
  150. let normalized;
  151. let arrayLength = 0;
  152. for ( let i = 0; i < attributes.length; ++ i ) {
  153. const attribute = attributes[ i ];
  154. if ( attribute.isInterleavedBufferAttribute ) {
  155. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported.' );
  156. return null;
  157. }
  158. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  159. if ( TypedArray !== attribute.array.constructor ) {
  160. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. THREE.BufferAttribute.array must be of consistent array types across matching attributes.' );
  161. return null;
  162. }
  163. if ( itemSize === undefined ) itemSize = attribute.itemSize;
  164. if ( itemSize !== attribute.itemSize ) {
  165. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. THREE.BufferAttribute.itemSize must be consistent across matching attributes.' );
  166. return null;
  167. }
  168. if ( normalized === undefined ) normalized = attribute.normalized;
  169. if ( normalized !== attribute.normalized ) {
  170. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. THREE.BufferAttribute.normalized must be consistent across matching attributes.' );
  171. return null;
  172. }
  173. arrayLength += attribute.array.length;
  174. }
  175. const array = new TypedArray( arrayLength );
  176. let offset = 0;
  177. for ( let i = 0; i < attributes.length; ++ i ) {
  178. array.set( attributes[ i ].array, offset );
  179. offset += attributes[ i ].array.length;
  180. }
  181. return new THREE.BufferAttribute( array, itemSize, normalized );
  182. }
  183. /**
  184. * @param {Array<BufferAttribute>} attributes
  185. * @return {Array<InterleavedBufferAttribute>}
  186. */
  187. function interleaveAttributes( attributes ) {
  188. // Interleaves the provided attributes into an THREE.InterleavedBuffer and returns
  189. // a set of InterleavedBufferAttributes for each attribute
  190. let TypedArray;
  191. let arrayLength = 0;
  192. let stride = 0; // calculate the length and type of the interleavedBuffer
  193. for ( let i = 0, l = attributes.length; i < l; ++ i ) {
  194. const attribute = attributes[ i ];
  195. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  196. if ( TypedArray !== attribute.array.constructor ) {
  197. console.error( 'AttributeBuffers of different types cannot be interleaved' );
  198. return null;
  199. }
  200. arrayLength += attribute.array.length;
  201. stride += attribute.itemSize;
  202. } // Create the set of buffer attributes
  203. const interleavedBuffer = new THREE.InterleavedBuffer( new TypedArray( arrayLength ), stride );
  204. let offset = 0;
  205. const res = [];
  206. const getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  207. const setters = [ 'setX', 'setY', 'setZ', 'setW' ];
  208. for ( let j = 0, l = attributes.length; j < l; j ++ ) {
  209. const attribute = attributes[ j ];
  210. const itemSize = attribute.itemSize;
  211. const count = attribute.count;
  212. const iba = new THREE.InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
  213. res.push( iba );
  214. offset += itemSize; // Move the data for each attribute into the new interleavedBuffer
  215. // at the appropriate offset
  216. for ( let c = 0; c < count; c ++ ) {
  217. for ( let k = 0; k < itemSize; k ++ ) {
  218. iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
  219. }
  220. }
  221. }
  222. return res;
  223. } // returns a new, non-interleaved version of the provided attribute
  224. function deinterleaveAttribute( attribute ) {
  225. const cons = attribute.data.array.constructor;
  226. const count = attribute.count;
  227. const itemSize = attribute.itemSize;
  228. const normalized = attribute.normalized;
  229. const array = new cons( count * itemSize );
  230. let newAttribute;
  231. if ( attribute.isInstancedInterleavedBufferAttribute ) {
  232. newAttribute = new THREE.InstancedBufferAttribute( array, itemSize, normalized, attribute.meshPerAttribute );
  233. } else {
  234. newAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  235. }
  236. for ( let i = 0; i < count; i ++ ) {
  237. newAttribute.setX( i, attribute.getX( i ) );
  238. if ( itemSize >= 2 ) {
  239. newAttribute.setY( i, attribute.getY( i ) );
  240. }
  241. if ( itemSize >= 3 ) {
  242. newAttribute.setZ( i, attribute.getZ( i ) );
  243. }
  244. if ( itemSize >= 4 ) {
  245. newAttribute.setW( i, attribute.getW( i ) );
  246. }
  247. }
  248. return newAttribute;
  249. } // deinterleaves all attributes on the geometry
  250. function deinterleaveGeometry( geometry ) {
  251. const attributes = geometry.attributes;
  252. const morphTargets = geometry.morphTargets;
  253. const attrMap = new Map();
  254. for ( const key in attributes ) {
  255. const attr = attributes[ key ];
  256. if ( attr.isInterleavedBufferAttribute ) {
  257. if ( ! attrMap.has( attr ) ) {
  258. attrMap.set( attr, deinterleaveAttribute( attr ) );
  259. }
  260. attributes[ key ] = attrMap.get( attr );
  261. }
  262. }
  263. for ( const key in morphTargets ) {
  264. const attr = morphTargets[ key ];
  265. if ( attr.isInterleavedBufferAttribute ) {
  266. if ( ! attrMap.has( attr ) ) {
  267. attrMap.set( attr, deinterleaveAttribute( attr ) );
  268. }
  269. morphTargets[ key ] = attrMap.get( attr );
  270. }
  271. }
  272. }
  273. /**
  274. * @param {Array<BufferGeometry>} geometry
  275. * @return {number}
  276. */
  277. function estimateBytesUsed( geometry ) {
  278. // Return the estimated memory used by this geometry in bytes
  279. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  280. // for InterleavedBufferAttributes.
  281. let mem = 0;
  282. for ( const name in geometry.attributes ) {
  283. const attr = geometry.getAttribute( name );
  284. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  285. }
  286. const indices = geometry.getIndex();
  287. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  288. return mem;
  289. }
  290. /**
  291. * @param {BufferGeometry} geometry
  292. * @param {number} tolerance
  293. * @return {BufferGeometry}
  294. */
  295. function mergeVertices( geometry, tolerance = 1e-4 ) {
  296. tolerance = Math.max( tolerance, Number.EPSILON ); // Generate an index buffer if the geometry doesn't have one, or optimize it
  297. // if it's already available.
  298. const hashToIndex = {};
  299. const indices = geometry.getIndex();
  300. const positions = geometry.getAttribute( 'position' );
  301. const vertexCount = indices ? indices.count : positions.count; // next value for triangle indices
  302. let nextIndex = 0; // attributes and new attribute arrays
  303. const attributeNames = Object.keys( geometry.attributes );
  304. const tmpAttributes = {};
  305. const tmpMorphAttributes = {};
  306. const newIndices = [];
  307. const getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  308. const setters = [ 'setX', 'setY', 'setZ', 'setW' ]; // Initialize the arrays, allocating space conservatively. Extra
  309. // space will be trimmed in the last step.
  310. for ( let i = 0, l = attributeNames.length; i < l; i ++ ) {
  311. const name = attributeNames[ i ];
  312. const attr = geometry.attributes[ name ];
  313. tmpAttributes[ name ] = new THREE.BufferAttribute( new attr.array.constructor( attr.count * attr.itemSize ), attr.itemSize, attr.normalized );
  314. const morphAttr = geometry.morphAttributes[ name ];
  315. if ( morphAttr ) {
  316. tmpMorphAttributes[ name ] = new THREE.BufferAttribute( new morphAttr.array.constructor( morphAttr.count * morphAttr.itemSize ), morphAttr.itemSize, morphAttr.normalized );
  317. }
  318. } // convert the error tolerance to an amount of decimal places to truncate to
  319. const decimalShift = Math.log10( 1 / tolerance );
  320. const shiftMultiplier = Math.pow( 10, decimalShift );
  321. for ( let i = 0; i < vertexCount; i ++ ) {
  322. const index = indices ? indices.getX( i ) : i; // Generate a hash for the vertex attributes at the current index 'i'
  323. let hash = '';
  324. for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
  325. const name = attributeNames[ j ];
  326. const attribute = geometry.getAttribute( name );
  327. const itemSize = attribute.itemSize;
  328. for ( let k = 0; k < itemSize; k ++ ) {
  329. // double tilde truncates the decimal value
  330. hash += `${~ ~ ( attribute[ getters[ k ] ]( index ) * shiftMultiplier )},`;
  331. }
  332. } // Add another reference to the vertex if it's already
  333. // used by another index
  334. if ( hash in hashToIndex ) {
  335. newIndices.push( hashToIndex[ hash ] );
  336. } else {
  337. // copy data to the new index in the temporary attributes
  338. for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
  339. const name = attributeNames[ j ];
  340. const attribute = geometry.getAttribute( name );
  341. const morphAttr = geometry.morphAttributes[ name ];
  342. const itemSize = attribute.itemSize;
  343. const newarray = tmpAttributes[ name ];
  344. const newMorphArrays = tmpMorphAttributes[ name ];
  345. for ( let k = 0; k < itemSize; k ++ ) {
  346. const getterFunc = getters[ k ];
  347. const setterFunc = setters[ k ];
  348. newarray[ setterFunc ]( nextIndex, attribute[ getterFunc ]( index ) );
  349. if ( morphAttr ) {
  350. for ( let m = 0, ml = morphAttr.length; m < ml; m ++ ) {
  351. newMorphArrays[ m ][ setterFunc ]( nextIndex, morphAttr[ m ][ getterFunc ]( index ) );
  352. }
  353. }
  354. }
  355. }
  356. hashToIndex[ hash ] = nextIndex;
  357. newIndices.push( nextIndex );
  358. nextIndex ++;
  359. }
  360. } // generate result THREE.BufferGeometry
  361. const result = geometry.clone();
  362. for ( const name in geometry.attributes ) {
  363. const tmpAttribute = tmpAttributes[ name ];
  364. result.setAttribute( name, new THREE.BufferAttribute( tmpAttribute.array.slice( 0, nextIndex * tmpAttribute.itemSize ), tmpAttribute.itemSize, tmpAttribute.normalized ) );
  365. if ( ! ( name in tmpMorphAttributes ) ) continue;
  366. for ( let j = 0; j < tmpMorphAttributes[ name ].length; j ++ ) {
  367. const tmpMorphAttribute = tmpMorphAttributes[ name ][ j ];
  368. result.morphAttributes[ name ][ j ] = new THREE.BufferAttribute( tmpMorphAttribute.array.slice( 0, nextIndex * tmpMorphAttribute.itemSize ), tmpMorphAttribute.itemSize, tmpMorphAttribute.normalized );
  369. }
  370. } // indices
  371. result.setIndex( newIndices );
  372. return result;
  373. }
  374. /**
  375. * @param {BufferGeometry} geometry
  376. * @param {number} drawMode
  377. * @return {BufferGeometry}
  378. */
  379. function toTrianglesDrawMode( geometry, drawMode ) {
  380. if ( drawMode === THREE.TrianglesDrawMode ) {
  381. console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' );
  382. return geometry;
  383. }
  384. if ( drawMode === THREE.TriangleFanDrawMode || drawMode === THREE.TriangleStripDrawMode ) {
  385. let index = geometry.getIndex(); // generate index if not present
  386. if ( index === null ) {
  387. const indices = [];
  388. const position = geometry.getAttribute( 'position' );
  389. if ( position !== undefined ) {
  390. for ( let i = 0; i < position.count; i ++ ) {
  391. indices.push( i );
  392. }
  393. geometry.setIndex( indices );
  394. index = geometry.getIndex();
  395. } else {
  396. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  397. return geometry;
  398. }
  399. } //
  400. const numberOfTriangles = index.count - 2;
  401. const newIndices = [];
  402. if ( drawMode === THREE.TriangleFanDrawMode ) {
  403. // gl.TRIANGLE_FAN
  404. for ( let i = 1; i <= numberOfTriangles; i ++ ) {
  405. newIndices.push( index.getX( 0 ) );
  406. newIndices.push( index.getX( i ) );
  407. newIndices.push( index.getX( i + 1 ) );
  408. }
  409. } else {
  410. // gl.TRIANGLE_STRIP
  411. for ( let i = 0; i < numberOfTriangles; i ++ ) {
  412. if ( i % 2 === 0 ) {
  413. newIndices.push( index.getX( i ) );
  414. newIndices.push( index.getX( i + 1 ) );
  415. newIndices.push( index.getX( i + 2 ) );
  416. } else {
  417. newIndices.push( index.getX( i + 2 ) );
  418. newIndices.push( index.getX( i + 1 ) );
  419. newIndices.push( index.getX( i ) );
  420. }
  421. }
  422. }
  423. if ( newIndices.length / 3 !== numberOfTriangles ) {
  424. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  425. } // build final geometry
  426. const newGeometry = geometry.clone();
  427. newGeometry.setIndex( newIndices );
  428. newGeometry.clearGroups();
  429. return newGeometry;
  430. } else {
  431. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode );
  432. return geometry;
  433. }
  434. }
  435. /**
  436. * Calculates the morphed attributes of a morphed/skinned THREE.BufferGeometry.
  437. * Helpful for Raytracing or Decals.
  438. * @param {Mesh | Line | Points} object An instance of Mesh, Line or Points.
  439. * @return {Object} An Object with original position/normal attributes and morphed ones.
  440. */
  441. function computeMorphedAttributes( object ) {
  442. if ( object.geometry.isBufferGeometry !== true ) {
  443. console.error( 'THREE.BufferGeometryUtils: Geometry is not of type THREE.BufferGeometry.' );
  444. return null;
  445. }
  446. const _vA = new THREE.Vector3();
  447. const _vB = new THREE.Vector3();
  448. const _vC = new THREE.Vector3();
  449. const _tempA = new THREE.Vector3();
  450. const _tempB = new THREE.Vector3();
  451. const _tempC = new THREE.Vector3();
  452. const _morphA = new THREE.Vector3();
  453. const _morphB = new THREE.Vector3();
  454. const _morphC = new THREE.Vector3();
  455. function _calculateMorphedAttributeData( object, attribute, morphAttribute, morphTargetsRelative, a, b, c, modifiedAttributeArray ) {
  456. _vA.fromBufferAttribute( attribute, a );
  457. _vB.fromBufferAttribute( attribute, b );
  458. _vC.fromBufferAttribute( attribute, c );
  459. const morphInfluences = object.morphTargetInfluences;
  460. if ( morphAttribute && morphInfluences ) {
  461. _morphA.set( 0, 0, 0 );
  462. _morphB.set( 0, 0, 0 );
  463. _morphC.set( 0, 0, 0 );
  464. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  465. const influence = morphInfluences[ i ];
  466. const morph = morphAttribute[ i ];
  467. if ( influence === 0 ) continue;
  468. _tempA.fromBufferAttribute( morph, a );
  469. _tempB.fromBufferAttribute( morph, b );
  470. _tempC.fromBufferAttribute( morph, c );
  471. if ( morphTargetsRelative ) {
  472. _morphA.addScaledVector( _tempA, influence );
  473. _morphB.addScaledVector( _tempB, influence );
  474. _morphC.addScaledVector( _tempC, influence );
  475. } else {
  476. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  477. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  478. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  479. }
  480. }
  481. _vA.add( _morphA );
  482. _vB.add( _morphB );
  483. _vC.add( _morphC );
  484. }
  485. if ( object.isSkinnedMesh ) {
  486. object.boneTransform( a, _vA );
  487. object.boneTransform( b, _vB );
  488. object.boneTransform( c, _vC );
  489. }
  490. modifiedAttributeArray[ a * 3 + 0 ] = _vA.x;
  491. modifiedAttributeArray[ a * 3 + 1 ] = _vA.y;
  492. modifiedAttributeArray[ a * 3 + 2 ] = _vA.z;
  493. modifiedAttributeArray[ b * 3 + 0 ] = _vB.x;
  494. modifiedAttributeArray[ b * 3 + 1 ] = _vB.y;
  495. modifiedAttributeArray[ b * 3 + 2 ] = _vB.z;
  496. modifiedAttributeArray[ c * 3 + 0 ] = _vC.x;
  497. modifiedAttributeArray[ c * 3 + 1 ] = _vC.y;
  498. modifiedAttributeArray[ c * 3 + 2 ] = _vC.z;
  499. }
  500. const geometry = object.geometry;
  501. const material = object.material;
  502. let a, b, c;
  503. const index = geometry.index;
  504. const positionAttribute = geometry.attributes.position;
  505. const morphPosition = geometry.morphAttributes.position;
  506. const morphTargetsRelative = geometry.morphTargetsRelative;
  507. const normalAttribute = geometry.attributes.normal;
  508. const morphNormal = geometry.morphAttributes.position;
  509. const groups = geometry.groups;
  510. const drawRange = geometry.drawRange;
  511. let i, j, il, jl;
  512. let group;
  513. let start, end;
  514. const modifiedPosition = new Float32Array( positionAttribute.count * positionAttribute.itemSize );
  515. const modifiedNormal = new Float32Array( normalAttribute.count * normalAttribute.itemSize );
  516. if ( index !== null ) {
  517. // indexed buffer geometry
  518. if ( Array.isArray( material ) ) {
  519. for ( i = 0, il = groups.length; i < il; i ++ ) {
  520. group = groups[ i ];
  521. start = Math.max( group.start, drawRange.start );
  522. end = Math.min( group.start + group.count, drawRange.start + drawRange.count );
  523. for ( j = start, jl = end; j < jl; j += 3 ) {
  524. a = index.getX( j );
  525. b = index.getX( j + 1 );
  526. c = index.getX( j + 2 );
  527. _calculateMorphedAttributeData( object, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition );
  528. _calculateMorphedAttributeData( object, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal );
  529. }
  530. }
  531. } else {
  532. start = Math.max( 0, drawRange.start );
  533. end = Math.min( index.count, drawRange.start + drawRange.count );
  534. for ( i = start, il = end; i < il; i += 3 ) {
  535. a = index.getX( i );
  536. b = index.getX( i + 1 );
  537. c = index.getX( i + 2 );
  538. _calculateMorphedAttributeData( object, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition );
  539. _calculateMorphedAttributeData( object, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal );
  540. }
  541. }
  542. } else {
  543. // non-indexed buffer geometry
  544. if ( Array.isArray( material ) ) {
  545. for ( i = 0, il = groups.length; i < il; i ++ ) {
  546. group = groups[ i ];
  547. start = Math.max( group.start, drawRange.start );
  548. end = Math.min( group.start + group.count, drawRange.start + drawRange.count );
  549. for ( j = start, jl = end; j < jl; j += 3 ) {
  550. a = j;
  551. b = j + 1;
  552. c = j + 2;
  553. _calculateMorphedAttributeData( object, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition );
  554. _calculateMorphedAttributeData( object, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal );
  555. }
  556. }
  557. } else {
  558. start = Math.max( 0, drawRange.start );
  559. end = Math.min( positionAttribute.count, drawRange.start + drawRange.count );
  560. for ( i = start, il = end; i < il; i += 3 ) {
  561. a = i;
  562. b = i + 1;
  563. c = i + 2;
  564. _calculateMorphedAttributeData( object, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition );
  565. _calculateMorphedAttributeData( object, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal );
  566. }
  567. }
  568. }
  569. const morphedPositionAttribute = new THREE.Float32BufferAttribute( modifiedPosition, 3 );
  570. const morphedNormalAttribute = new THREE.Float32BufferAttribute( modifiedNormal, 3 );
  571. return {
  572. positionAttribute: positionAttribute,
  573. normalAttribute: normalAttribute,
  574. morphedPositionAttribute: morphedPositionAttribute,
  575. morphedNormalAttribute: morphedNormalAttribute
  576. };
  577. }
  578. function mergeGroups( geometry ) {
  579. if ( geometry.groups.length === 0 ) {
  580. console.warn( 'THREE.BufferGeometryUtils.mergeGroups(): No groups are defined. Nothing to merge.' );
  581. return geometry;
  582. }
  583. let groups = geometry.groups; // sort groups by material index
  584. groups = groups.sort( ( a, b ) => {
  585. if ( a.materialIndex !== b.materialIndex ) return a.materialIndex - b.materialIndex;
  586. return a.start - b.start;
  587. } ); // create index for non-indexed geometries
  588. if ( geometry.getIndex() === null ) {
  589. const positionAttribute = geometry.getAttribute( 'position' );
  590. const indices = [];
  591. for ( let i = 0; i < positionAttribute.count; i += 3 ) {
  592. indices.push( i, i + 1, i + 2 );
  593. }
  594. geometry.setIndex( indices );
  595. } // sort index
  596. const index = geometry.getIndex();
  597. const newIndices = [];
  598. for ( let i = 0; i < groups.length; i ++ ) {
  599. const group = groups[ i ];
  600. const groupStart = group.start;
  601. const groupLength = groupStart + group.count;
  602. for ( let j = groupStart; j < groupLength; j ++ ) {
  603. newIndices.push( index.getX( j ) );
  604. }
  605. }
  606. geometry.dispose(); // Required to force buffer recreation
  607. geometry.setIndex( newIndices ); // update groups indices
  608. let start = 0;
  609. for ( let i = 0; i < groups.length; i ++ ) {
  610. const group = groups[ i ];
  611. group.start = start;
  612. start += group.count;
  613. } // merge groups
  614. let currentGroup = groups[ 0 ];
  615. geometry.groups = [ currentGroup ];
  616. for ( let i = 1; i < groups.length; i ++ ) {
  617. const group = groups[ i ];
  618. if ( currentGroup.materialIndex === group.materialIndex ) {
  619. currentGroup.count += group.count;
  620. } else {
  621. currentGroup = group;
  622. geometry.groups.push( currentGroup );
  623. }
  624. }
  625. return geometry;
  626. }
  627. THREE.BufferGeometryUtils = {};
  628. THREE.BufferGeometryUtils.computeMikkTSpaceTangents = computeMikkTSpaceTangents;
  629. THREE.BufferGeometryUtils.computeMorphedAttributes = computeMorphedAttributes;
  630. THREE.BufferGeometryUtils.computeTangents = computeTangents;
  631. THREE.BufferGeometryUtils.deinterleaveAttribute = deinterleaveAttribute;
  632. THREE.BufferGeometryUtils.deinterleaveGeometry = deinterleaveGeometry;
  633. THREE.BufferGeometryUtils.estimateBytesUsed = estimateBytesUsed;
  634. THREE.BufferGeometryUtils.interleaveAttributes = interleaveAttributes;
  635. THREE.BufferGeometryUtils.mergeBufferAttributes = mergeBufferAttributes;
  636. THREE.BufferGeometryUtils.mergeBufferGeometries = mergeBufferGeometries;
  637. THREE.BufferGeometryUtils.mergeGroups = mergeGroups;
  638. THREE.BufferGeometryUtils.mergeVertices = mergeVertices;
  639. THREE.BufferGeometryUtils.toTrianglesDrawMode = toTrianglesDrawMode;
  640. } )();