BufferGeometryUtils.js 28 KB

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