BufferGeometryUtils.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  1. import {
  2. BufferAttribute,
  3. BufferGeometry,
  4. Float32BufferAttribute,
  5. InstancedBufferAttribute,
  6. InterleavedBuffer,
  7. InterleavedBufferAttribute,
  8. TriangleFanDrawMode,
  9. TriangleStripDrawMode,
  10. TrianglesDrawMode,
  11. Vector3,
  12. } from 'three';
  13. function computeMikkTSpaceTangents( geometry, MikkTSpace, negateSign = true ) {
  14. if ( ! MikkTSpace || ! MikkTSpace.isReady ) {
  15. throw new Error( 'BufferGeometryUtils: Initialized MikkTSpace library required.' );
  16. }
  17. if ( ! geometry.hasAttribute( 'position' ) || ! geometry.hasAttribute( 'normal' ) || ! geometry.hasAttribute( 'uv' ) ) {
  18. throw new Error( 'BufferGeometryUtils: Tangents require "position", "normal", and "uv" attributes.' );
  19. }
  20. function getAttributeArray( attribute ) {
  21. if ( attribute.normalized || attribute.isInterleavedBufferAttribute ) {
  22. const dstArray = new Float32Array( attribute.count * attribute.itemSize );
  23. for ( let i = 0, j = 0; i < attribute.count; i ++ ) {
  24. dstArray[ j ++ ] = attribute.getX( i );
  25. dstArray[ j ++ ] = attribute.getY( i );
  26. if ( attribute.itemSize > 2 ) {
  27. dstArray[ j ++ ] = attribute.getZ( i );
  28. }
  29. }
  30. return dstArray;
  31. }
  32. if ( attribute.array instanceof Float32Array ) {
  33. return attribute.array;
  34. }
  35. return new Float32Array( attribute.array );
  36. }
  37. // MikkTSpace algorithm requires non-indexed input.
  38. const _geometry = geometry.index ? geometry.toNonIndexed() : geometry;
  39. // Compute vertex tangents.
  40. const tangents = MikkTSpace.generateTangents(
  41. getAttributeArray( _geometry.attributes.position ),
  42. getAttributeArray( _geometry.attributes.normal ),
  43. getAttributeArray( _geometry.attributes.uv )
  44. );
  45. // Texture coordinate convention of glTF differs from the apparent
  46. // default of the MikkTSpace library; .w component must be flipped.
  47. if ( negateSign ) {
  48. for ( let i = 3; i < tangents.length; i += 4 ) {
  49. tangents[ i ] *= - 1;
  50. }
  51. }
  52. //
  53. _geometry.setAttribute( 'tangent', new BufferAttribute( tangents, 4 ) );
  54. if ( geometry !== _geometry ) {
  55. geometry.copy( _geometry );
  56. }
  57. return geometry;
  58. }
  59. /**
  60. * @param {Array<BufferGeometry>} geometries
  61. * @param {Boolean} useGroups
  62. * @return {BufferGeometry}
  63. */
  64. function mergeGeometries( geometries, useGroups = false ) {
  65. const isIndexed = geometries[ 0 ].index !== null;
  66. const attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) );
  67. const morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) );
  68. const attributes = {};
  69. const morphAttributes = {};
  70. const morphTargetsRelative = geometries[ 0 ].morphTargetsRelative;
  71. const mergedGeometry = new BufferGeometry();
  72. let offset = 0;
  73. for ( let i = 0; i < geometries.length; ++ i ) {
  74. const geometry = geometries[ i ];
  75. let attributesCount = 0;
  76. // ensure that all geometries are indexed, or none
  77. if ( isIndexed !== ( geometry.index !== null ) ) {
  78. console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() 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.' );
  79. return null;
  80. }
  81. // gather attributes, exit early if they're different
  82. for ( const name in geometry.attributes ) {
  83. if ( ! attributesUsed.has( name ) ) {
  84. console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() 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.' );
  85. return null;
  86. }
  87. if ( attributes[ name ] === undefined ) attributes[ name ] = [];
  88. attributes[ name ].push( geometry.attributes[ name ] );
  89. attributesCount ++;
  90. }
  91. // ensure geometries have the same number of attributes
  92. if ( attributesCount !== attributesUsed.size ) {
  93. console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.' );
  94. return null;
  95. }
  96. // gather morph attributes, exit early if they're different
  97. if ( morphTargetsRelative !== geometry.morphTargetsRelative ) {
  98. console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.' );
  99. return null;
  100. }
  101. for ( const name in geometry.morphAttributes ) {
  102. if ( ! morphAttributesUsed.has( name ) ) {
  103. console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.' );
  104. return null;
  105. }
  106. if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = [];
  107. morphAttributes[ name ].push( geometry.morphAttributes[ name ] );
  108. }
  109. if ( useGroups ) {
  110. let count;
  111. if ( isIndexed ) {
  112. count = geometry.index.count;
  113. } else if ( geometry.attributes.position !== undefined ) {
  114. count = geometry.attributes.position.count;
  115. } else {
  116. console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute' );
  117. return null;
  118. }
  119. mergedGeometry.addGroup( offset, count, i );
  120. offset += count;
  121. }
  122. }
  123. // merge indices
  124. if ( isIndexed ) {
  125. let indexOffset = 0;
  126. const mergedIndex = [];
  127. for ( let i = 0; i < geometries.length; ++ i ) {
  128. const index = geometries[ i ].index;
  129. for ( let j = 0; j < index.count; ++ j ) {
  130. mergedIndex.push( index.getX( j ) + indexOffset );
  131. }
  132. indexOffset += geometries[ i ].attributes.position.count;
  133. }
  134. mergedGeometry.setIndex( mergedIndex );
  135. }
  136. // merge attributes
  137. for ( const name in attributes ) {
  138. const mergedAttribute = mergeAttributes( attributes[ name ] );
  139. if ( ! mergedAttribute ) {
  140. console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the ' + name + ' attribute.' );
  141. return null;
  142. }
  143. mergedGeometry.setAttribute( name, mergedAttribute );
  144. }
  145. // merge morph attributes
  146. for ( const name in morphAttributes ) {
  147. const numMorphTargets = morphAttributes[ name ][ 0 ].length;
  148. if ( numMorphTargets === 0 ) break;
  149. mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
  150. mergedGeometry.morphAttributes[ name ] = [];
  151. for ( let i = 0; i < numMorphTargets; ++ i ) {
  152. const morphAttributesToMerge = [];
  153. for ( let j = 0; j < morphAttributes[ name ].length; ++ j ) {
  154. morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] );
  155. }
  156. const mergedMorphAttribute = mergeAttributes( morphAttributesToMerge );
  157. if ( ! mergedMorphAttribute ) {
  158. console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the ' + name + ' morphAttribute.' );
  159. return null;
  160. }
  161. mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute );
  162. }
  163. }
  164. return mergedGeometry;
  165. }
  166. /**
  167. * @param {Array<BufferAttribute>} attributes
  168. * @return {BufferAttribute}
  169. */
  170. function mergeAttributes( attributes ) {
  171. let TypedArray;
  172. let itemSize;
  173. let normalized;
  174. let gpuType = - 1;
  175. let arrayLength = 0;
  176. for ( let i = 0; i < attributes.length; ++ i ) {
  177. const attribute = attributes[ i ];
  178. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  179. if ( TypedArray !== attribute.array.constructor ) {
  180. console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.' );
  181. return null;
  182. }
  183. if ( itemSize === undefined ) itemSize = attribute.itemSize;
  184. if ( itemSize !== attribute.itemSize ) {
  185. console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.' );
  186. return null;
  187. }
  188. if ( normalized === undefined ) normalized = attribute.normalized;
  189. if ( normalized !== attribute.normalized ) {
  190. console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.' );
  191. return null;
  192. }
  193. if ( gpuType === - 1 ) gpuType = attribute.gpuType;
  194. if ( gpuType !== attribute.gpuType ) {
  195. console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes.' );
  196. return null;
  197. }
  198. arrayLength += attribute.count * itemSize;
  199. }
  200. const array = new TypedArray( arrayLength );
  201. const result = new BufferAttribute( array, itemSize, normalized );
  202. let offset = 0;
  203. for ( let i = 0; i < attributes.length; ++ i ) {
  204. const attribute = attributes[ i ];
  205. if ( attribute.isInterleavedBufferAttribute ) {
  206. const tupleOffset = offset / itemSize;
  207. for ( let j = 0, l = attribute.count; j < l; j ++ ) {
  208. for ( let c = 0; c < itemSize; c ++ ) {
  209. const value = attribute.getComponent( j, c );
  210. result.setComponent( j + tupleOffset, c, value );
  211. }
  212. }
  213. } else {
  214. array.set( attribute.array, offset );
  215. }
  216. offset += attribute.count * itemSize;
  217. }
  218. if ( gpuType !== undefined ) {
  219. result.gpuType = gpuType;
  220. }
  221. return result;
  222. }
  223. /**
  224. * @param {BufferAttribute}
  225. * @return {BufferAttribute}
  226. */
  227. export function deepCloneAttribute( attribute ) {
  228. if ( attribute.isInstancedInterleavedBufferAttribute || attribute.isInterleavedBufferAttribute ) {
  229. return deinterleaveAttribute( attribute );
  230. }
  231. if ( attribute.isInstancedBufferAttribute ) {
  232. return new InstancedBufferAttribute().copy( attribute );
  233. }
  234. return new BufferAttribute().copy( attribute );
  235. }
  236. /**
  237. * @param {Array<BufferAttribute>} attributes
  238. * @return {Array<InterleavedBufferAttribute>}
  239. */
  240. function interleaveAttributes( attributes ) {
  241. // Interleaves the provided attributes into an InterleavedBuffer and returns
  242. // a set of InterleavedBufferAttributes for each attribute
  243. let TypedArray;
  244. let arrayLength = 0;
  245. let stride = 0;
  246. // calculate the length and type of the interleavedBuffer
  247. for ( let i = 0, l = attributes.length; i < l; ++ i ) {
  248. const attribute = attributes[ i ];
  249. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  250. if ( TypedArray !== attribute.array.constructor ) {
  251. console.error( 'AttributeBuffers of different types cannot be interleaved' );
  252. return null;
  253. }
  254. arrayLength += attribute.array.length;
  255. stride += attribute.itemSize;
  256. }
  257. // Create the set of buffer attributes
  258. const interleavedBuffer = new InterleavedBuffer( new TypedArray( arrayLength ), stride );
  259. let offset = 0;
  260. const res = [];
  261. const getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  262. const setters = [ 'setX', 'setY', 'setZ', 'setW' ];
  263. for ( let j = 0, l = attributes.length; j < l; j ++ ) {
  264. const attribute = attributes[ j ];
  265. const itemSize = attribute.itemSize;
  266. const count = attribute.count;
  267. const iba = new InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
  268. res.push( iba );
  269. offset += itemSize;
  270. // Move the data for each attribute into the new interleavedBuffer
  271. // at the appropriate offset
  272. for ( let c = 0; c < count; c ++ ) {
  273. for ( let k = 0; k < itemSize; k ++ ) {
  274. iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
  275. }
  276. }
  277. }
  278. return res;
  279. }
  280. // returns a new, non-interleaved version of the provided attribute
  281. export function deinterleaveAttribute( attribute ) {
  282. const cons = attribute.data.array.constructor;
  283. const count = attribute.count;
  284. const itemSize = attribute.itemSize;
  285. const normalized = attribute.normalized;
  286. const array = new cons( count * itemSize );
  287. let newAttribute;
  288. if ( attribute.isInstancedInterleavedBufferAttribute ) {
  289. newAttribute = new InstancedBufferAttribute( array, itemSize, normalized, attribute.meshPerAttribute );
  290. } else {
  291. newAttribute = new BufferAttribute( array, itemSize, normalized );
  292. }
  293. for ( let i = 0; i < count; i ++ ) {
  294. newAttribute.setX( i, attribute.getX( i ) );
  295. if ( itemSize >= 2 ) {
  296. newAttribute.setY( i, attribute.getY( i ) );
  297. }
  298. if ( itemSize >= 3 ) {
  299. newAttribute.setZ( i, attribute.getZ( i ) );
  300. }
  301. if ( itemSize >= 4 ) {
  302. newAttribute.setW( i, attribute.getW( i ) );
  303. }
  304. }
  305. return newAttribute;
  306. }
  307. // deinterleaves all attributes on the geometry
  308. export function deinterleaveGeometry( geometry ) {
  309. const attributes = geometry.attributes;
  310. const morphTargets = geometry.morphTargets;
  311. const attrMap = new Map();
  312. for ( const key in attributes ) {
  313. const attr = attributes[ key ];
  314. if ( attr.isInterleavedBufferAttribute ) {
  315. if ( ! attrMap.has( attr ) ) {
  316. attrMap.set( attr, deinterleaveAttribute( attr ) );
  317. }
  318. attributes[ key ] = attrMap.get( attr );
  319. }
  320. }
  321. for ( const key in morphTargets ) {
  322. const attr = morphTargets[ key ];
  323. if ( attr.isInterleavedBufferAttribute ) {
  324. if ( ! attrMap.has( attr ) ) {
  325. attrMap.set( attr, deinterleaveAttribute( attr ) );
  326. }
  327. morphTargets[ key ] = attrMap.get( attr );
  328. }
  329. }
  330. }
  331. /**
  332. * @param {BufferGeometry} geometry
  333. * @return {number}
  334. */
  335. function estimateBytesUsed( geometry ) {
  336. // Return the estimated memory used by this geometry in bytes
  337. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  338. // for InterleavedBufferAttributes.
  339. let mem = 0;
  340. for ( const name in geometry.attributes ) {
  341. const attr = geometry.getAttribute( name );
  342. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  343. }
  344. const indices = geometry.getIndex();
  345. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  346. return mem;
  347. }
  348. /**
  349. * @param {BufferGeometry} geometry
  350. * @param {number} tolerance
  351. * @return {BufferGeometry}
  352. */
  353. function mergeVertices( geometry, tolerance = 1e-4 ) {
  354. tolerance = Math.max( tolerance, Number.EPSILON );
  355. // Generate an index buffer if the geometry doesn't have one, or optimize it
  356. // if it's already available.
  357. const hashToIndex = {};
  358. const indices = geometry.getIndex();
  359. const positions = geometry.getAttribute( 'position' );
  360. const vertexCount = indices ? indices.count : positions.count;
  361. // next value for triangle indices
  362. let nextIndex = 0;
  363. // attributes and new attribute arrays
  364. const attributeNames = Object.keys( geometry.attributes );
  365. const tmpAttributes = {};
  366. const tmpMorphAttributes = {};
  367. const newIndices = [];
  368. const getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  369. const setters = [ 'setX', 'setY', 'setZ', 'setW' ];
  370. // Initialize the arrays, allocating space conservatively. Extra
  371. // space will be trimmed in the last step.
  372. for ( let i = 0, l = attributeNames.length; i < l; i ++ ) {
  373. const name = attributeNames[ i ];
  374. const attr = geometry.attributes[ name ];
  375. tmpAttributes[ name ] = new BufferAttribute(
  376. new attr.array.constructor( attr.count * attr.itemSize ),
  377. attr.itemSize,
  378. attr.normalized
  379. );
  380. const morphAttr = geometry.morphAttributes[ name ];
  381. if ( morphAttr ) {
  382. tmpMorphAttributes[ name ] = new BufferAttribute(
  383. new morphAttr.array.constructor( morphAttr.count * morphAttr.itemSize ),
  384. morphAttr.itemSize,
  385. morphAttr.normalized
  386. );
  387. }
  388. }
  389. // convert the error tolerance to an amount of decimal places to truncate to
  390. const halfTolerance = tolerance * 0.5;
  391. const exponent = Math.log10( 1 / tolerance );
  392. const hashMultiplier = Math.pow( 10, exponent );
  393. const hashAdditive = halfTolerance * hashMultiplier;
  394. for ( let i = 0; i < vertexCount; i ++ ) {
  395. const index = indices ? indices.getX( i ) : i;
  396. // Generate a hash for the vertex attributes at the current index 'i'
  397. let hash = '';
  398. for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
  399. const name = attributeNames[ j ];
  400. const attribute = geometry.getAttribute( name );
  401. const itemSize = attribute.itemSize;
  402. for ( let k = 0; k < itemSize; k ++ ) {
  403. // double tilde truncates the decimal value
  404. hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * hashMultiplier + hashAdditive ) },`;
  405. }
  406. }
  407. // Add another reference to the vertex if it's already
  408. // used by another index
  409. if ( hash in hashToIndex ) {
  410. newIndices.push( hashToIndex[ hash ] );
  411. } else {
  412. // copy data to the new index in the temporary attributes
  413. for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
  414. const name = attributeNames[ j ];
  415. const attribute = geometry.getAttribute( name );
  416. const morphAttr = geometry.morphAttributes[ name ];
  417. const itemSize = attribute.itemSize;
  418. const newarray = tmpAttributes[ name ];
  419. const newMorphArrays = tmpMorphAttributes[ name ];
  420. for ( let k = 0; k < itemSize; k ++ ) {
  421. const getterFunc = getters[ k ];
  422. const setterFunc = setters[ k ];
  423. newarray[ setterFunc ]( nextIndex, attribute[ getterFunc ]( index ) );
  424. if ( morphAttr ) {
  425. for ( let m = 0, ml = morphAttr.length; m < ml; m ++ ) {
  426. newMorphArrays[ m ][ setterFunc ]( nextIndex, morphAttr[ m ][ getterFunc ]( index ) );
  427. }
  428. }
  429. }
  430. }
  431. hashToIndex[ hash ] = nextIndex;
  432. newIndices.push( nextIndex );
  433. nextIndex ++;
  434. }
  435. }
  436. // generate result BufferGeometry
  437. const result = geometry.clone();
  438. for ( const name in geometry.attributes ) {
  439. const tmpAttribute = tmpAttributes[ name ];
  440. result.setAttribute( name, new BufferAttribute(
  441. tmpAttribute.array.slice( 0, nextIndex * tmpAttribute.itemSize ),
  442. tmpAttribute.itemSize,
  443. tmpAttribute.normalized,
  444. ) );
  445. if ( ! ( name in tmpMorphAttributes ) ) continue;
  446. for ( let j = 0; j < tmpMorphAttributes[ name ].length; j ++ ) {
  447. const tmpMorphAttribute = tmpMorphAttributes[ name ][ j ];
  448. result.morphAttributes[ name ][ j ] = new BufferAttribute(
  449. tmpMorphAttribute.array.slice( 0, nextIndex * tmpMorphAttribute.itemSize ),
  450. tmpMorphAttribute.itemSize,
  451. tmpMorphAttribute.normalized,
  452. );
  453. }
  454. }
  455. // indices
  456. result.setIndex( newIndices );
  457. return result;
  458. }
  459. /**
  460. * @param {BufferGeometry} geometry
  461. * @param {number} drawMode
  462. * @return {BufferGeometry}
  463. */
  464. function toTrianglesDrawMode( geometry, drawMode ) {
  465. if ( drawMode === TrianglesDrawMode ) {
  466. console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' );
  467. return geometry;
  468. }
  469. if ( drawMode === TriangleFanDrawMode || drawMode === TriangleStripDrawMode ) {
  470. let index = geometry.getIndex();
  471. // generate index if not present
  472. if ( index === null ) {
  473. const indices = [];
  474. const position = geometry.getAttribute( 'position' );
  475. if ( position !== undefined ) {
  476. for ( let i = 0; i < position.count; i ++ ) {
  477. indices.push( i );
  478. }
  479. geometry.setIndex( indices );
  480. index = geometry.getIndex();
  481. } else {
  482. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  483. return geometry;
  484. }
  485. }
  486. //
  487. const numberOfTriangles = index.count - 2;
  488. const newIndices = [];
  489. if ( drawMode === TriangleFanDrawMode ) {
  490. // gl.TRIANGLE_FAN
  491. for ( let i = 1; i <= numberOfTriangles; i ++ ) {
  492. newIndices.push( index.getX( 0 ) );
  493. newIndices.push( index.getX( i ) );
  494. newIndices.push( index.getX( i + 1 ) );
  495. }
  496. } else {
  497. // gl.TRIANGLE_STRIP
  498. for ( let i = 0; i < numberOfTriangles; i ++ ) {
  499. if ( i % 2 === 0 ) {
  500. newIndices.push( index.getX( i ) );
  501. newIndices.push( index.getX( i + 1 ) );
  502. newIndices.push( index.getX( i + 2 ) );
  503. } else {
  504. newIndices.push( index.getX( i + 2 ) );
  505. newIndices.push( index.getX( i + 1 ) );
  506. newIndices.push( index.getX( i ) );
  507. }
  508. }
  509. }
  510. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  511. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  512. }
  513. // build final geometry
  514. const newGeometry = geometry.clone();
  515. newGeometry.setIndex( newIndices );
  516. newGeometry.clearGroups();
  517. return newGeometry;
  518. } else {
  519. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode );
  520. return geometry;
  521. }
  522. }
  523. /**
  524. * Calculates the morphed attributes of a morphed/skinned BufferGeometry.
  525. * Helpful for Raytracing or Decals.
  526. * @param {Mesh | Line | Points} object An instance of Mesh, Line or Points.
  527. * @return {Object} An Object with original position/normal attributes and morphed ones.
  528. */
  529. function computeMorphedAttributes( object ) {
  530. const _vA = new Vector3();
  531. const _vB = new Vector3();
  532. const _vC = new Vector3();
  533. const _tempA = new Vector3();
  534. const _tempB = new Vector3();
  535. const _tempC = new Vector3();
  536. const _morphA = new Vector3();
  537. const _morphB = new Vector3();
  538. const _morphC = new Vector3();
  539. function _calculateMorphedAttributeData(
  540. object,
  541. attribute,
  542. morphAttribute,
  543. morphTargetsRelative,
  544. a,
  545. b,
  546. c,
  547. modifiedAttributeArray
  548. ) {
  549. _vA.fromBufferAttribute( attribute, a );
  550. _vB.fromBufferAttribute( attribute, b );
  551. _vC.fromBufferAttribute( attribute, c );
  552. const morphInfluences = object.morphTargetInfluences;
  553. if ( morphAttribute && morphInfluences ) {
  554. _morphA.set( 0, 0, 0 );
  555. _morphB.set( 0, 0, 0 );
  556. _morphC.set( 0, 0, 0 );
  557. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  558. const influence = morphInfluences[ i ];
  559. const morph = morphAttribute[ i ];
  560. if ( influence === 0 ) continue;
  561. _tempA.fromBufferAttribute( morph, a );
  562. _tempB.fromBufferAttribute( morph, b );
  563. _tempC.fromBufferAttribute( morph, c );
  564. if ( morphTargetsRelative ) {
  565. _morphA.addScaledVector( _tempA, influence );
  566. _morphB.addScaledVector( _tempB, influence );
  567. _morphC.addScaledVector( _tempC, influence );
  568. } else {
  569. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  570. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  571. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  572. }
  573. }
  574. _vA.add( _morphA );
  575. _vB.add( _morphB );
  576. _vC.add( _morphC );
  577. }
  578. if ( object.isSkinnedMesh ) {
  579. object.applyBoneTransform( a, _vA );
  580. object.applyBoneTransform( b, _vB );
  581. object.applyBoneTransform( c, _vC );
  582. }
  583. modifiedAttributeArray[ a * 3 + 0 ] = _vA.x;
  584. modifiedAttributeArray[ a * 3 + 1 ] = _vA.y;
  585. modifiedAttributeArray[ a * 3 + 2 ] = _vA.z;
  586. modifiedAttributeArray[ b * 3 + 0 ] = _vB.x;
  587. modifiedAttributeArray[ b * 3 + 1 ] = _vB.y;
  588. modifiedAttributeArray[ b * 3 + 2 ] = _vB.z;
  589. modifiedAttributeArray[ c * 3 + 0 ] = _vC.x;
  590. modifiedAttributeArray[ c * 3 + 1 ] = _vC.y;
  591. modifiedAttributeArray[ c * 3 + 2 ] = _vC.z;
  592. }
  593. const geometry = object.geometry;
  594. const material = object.material;
  595. let a, b, c;
  596. const index = geometry.index;
  597. const positionAttribute = geometry.attributes.position;
  598. const morphPosition = geometry.morphAttributes.position;
  599. const morphTargetsRelative = geometry.morphTargetsRelative;
  600. const normalAttribute = geometry.attributes.normal;
  601. const morphNormal = geometry.morphAttributes.position;
  602. const groups = geometry.groups;
  603. const drawRange = geometry.drawRange;
  604. let i, j, il, jl;
  605. let group;
  606. let start, end;
  607. const modifiedPosition = new Float32Array( positionAttribute.count * positionAttribute.itemSize );
  608. const modifiedNormal = new Float32Array( normalAttribute.count * normalAttribute.itemSize );
  609. if ( index !== null ) {
  610. // indexed buffer geometry
  611. if ( Array.isArray( material ) ) {
  612. for ( i = 0, il = groups.length; i < il; i ++ ) {
  613. group = groups[ i ];
  614. start = Math.max( group.start, drawRange.start );
  615. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  616. for ( j = start, jl = end; j < jl; j += 3 ) {
  617. a = index.getX( j );
  618. b = index.getX( j + 1 );
  619. c = index.getX( j + 2 );
  620. _calculateMorphedAttributeData(
  621. object,
  622. positionAttribute,
  623. morphPosition,
  624. morphTargetsRelative,
  625. a, b, c,
  626. modifiedPosition
  627. );
  628. _calculateMorphedAttributeData(
  629. object,
  630. normalAttribute,
  631. morphNormal,
  632. morphTargetsRelative,
  633. a, b, c,
  634. modifiedNormal
  635. );
  636. }
  637. }
  638. } else {
  639. start = Math.max( 0, drawRange.start );
  640. end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  641. for ( i = start, il = end; i < il; i += 3 ) {
  642. a = index.getX( i );
  643. b = index.getX( i + 1 );
  644. c = index.getX( i + 2 );
  645. _calculateMorphedAttributeData(
  646. object,
  647. positionAttribute,
  648. morphPosition,
  649. morphTargetsRelative,
  650. a, b, c,
  651. modifiedPosition
  652. );
  653. _calculateMorphedAttributeData(
  654. object,
  655. normalAttribute,
  656. morphNormal,
  657. morphTargetsRelative,
  658. a, b, c,
  659. modifiedNormal
  660. );
  661. }
  662. }
  663. } else {
  664. // non-indexed buffer geometry
  665. if ( Array.isArray( material ) ) {
  666. for ( i = 0, il = groups.length; i < il; i ++ ) {
  667. group = groups[ i ];
  668. start = Math.max( group.start, drawRange.start );
  669. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  670. for ( j = start, jl = end; j < jl; j += 3 ) {
  671. a = j;
  672. b = j + 1;
  673. c = j + 2;
  674. _calculateMorphedAttributeData(
  675. object,
  676. positionAttribute,
  677. morphPosition,
  678. morphTargetsRelative,
  679. a, b, c,
  680. modifiedPosition
  681. );
  682. _calculateMorphedAttributeData(
  683. object,
  684. normalAttribute,
  685. morphNormal,
  686. morphTargetsRelative,
  687. a, b, c,
  688. modifiedNormal
  689. );
  690. }
  691. }
  692. } else {
  693. start = Math.max( 0, drawRange.start );
  694. end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  695. for ( i = start, il = end; i < il; i += 3 ) {
  696. a = i;
  697. b = i + 1;
  698. c = i + 2;
  699. _calculateMorphedAttributeData(
  700. object,
  701. positionAttribute,
  702. morphPosition,
  703. morphTargetsRelative,
  704. a, b, c,
  705. modifiedPosition
  706. );
  707. _calculateMorphedAttributeData(
  708. object,
  709. normalAttribute,
  710. morphNormal,
  711. morphTargetsRelative,
  712. a, b, c,
  713. modifiedNormal
  714. );
  715. }
  716. }
  717. }
  718. const morphedPositionAttribute = new Float32BufferAttribute( modifiedPosition, 3 );
  719. const morphedNormalAttribute = new Float32BufferAttribute( modifiedNormal, 3 );
  720. return {
  721. positionAttribute: positionAttribute,
  722. normalAttribute: normalAttribute,
  723. morphedPositionAttribute: morphedPositionAttribute,
  724. morphedNormalAttribute: morphedNormalAttribute
  725. };
  726. }
  727. function mergeGroups( geometry ) {
  728. if ( geometry.groups.length === 0 ) {
  729. console.warn( 'THREE.BufferGeometryUtils.mergeGroups(): No groups are defined. Nothing to merge.' );
  730. return geometry;
  731. }
  732. let groups = geometry.groups;
  733. // sort groups by material index
  734. groups = groups.sort( ( a, b ) => {
  735. if ( a.materialIndex !== b.materialIndex ) return a.materialIndex - b.materialIndex;
  736. return a.start - b.start;
  737. } );
  738. // create index for non-indexed geometries
  739. if ( geometry.getIndex() === null ) {
  740. const positionAttribute = geometry.getAttribute( 'position' );
  741. const indices = [];
  742. for ( let i = 0; i < positionAttribute.count; i += 3 ) {
  743. indices.push( i, i + 1, i + 2 );
  744. }
  745. geometry.setIndex( indices );
  746. }
  747. // sort index
  748. const index = geometry.getIndex();
  749. const newIndices = [];
  750. for ( let i = 0; i < groups.length; i ++ ) {
  751. const group = groups[ i ];
  752. const groupStart = group.start;
  753. const groupLength = groupStart + group.count;
  754. for ( let j = groupStart; j < groupLength; j ++ ) {
  755. newIndices.push( index.getX( j ) );
  756. }
  757. }
  758. geometry.dispose(); // Required to force buffer recreation
  759. geometry.setIndex( newIndices );
  760. // update groups indices
  761. let start = 0;
  762. for ( let i = 0; i < groups.length; i ++ ) {
  763. const group = groups[ i ];
  764. group.start = start;
  765. start += group.count;
  766. }
  767. // merge groups
  768. let currentGroup = groups[ 0 ];
  769. geometry.groups = [ currentGroup ];
  770. for ( let i = 1; i < groups.length; i ++ ) {
  771. const group = groups[ i ];
  772. if ( currentGroup.materialIndex === group.materialIndex ) {
  773. currentGroup.count += group.count;
  774. } else {
  775. currentGroup = group;
  776. geometry.groups.push( currentGroup );
  777. }
  778. }
  779. return geometry;
  780. }
  781. /**
  782. * Modifies the supplied geometry if it is non-indexed, otherwise creates a new,
  783. * non-indexed geometry. Returns the geometry with smooth normals everywhere except
  784. * faces that meet at an angle greater than the crease angle.
  785. *
  786. * @param {BufferGeometry} geometry
  787. * @param {number} [creaseAngle]
  788. * @return {BufferGeometry}
  789. */
  790. function toCreasedNormals( geometry, creaseAngle = Math.PI / 3 /* 60 degrees */ ) {
  791. const creaseDot = Math.cos( creaseAngle );
  792. const hashMultiplier = ( 1 + 1e-10 ) * 1e2;
  793. // reusable vectors
  794. const verts = [ new Vector3(), new Vector3(), new Vector3() ];
  795. const tempVec1 = new Vector3();
  796. const tempVec2 = new Vector3();
  797. const tempNorm = new Vector3();
  798. const tempNorm2 = new Vector3();
  799. // hashes a vector
  800. function hashVertex( v ) {
  801. const x = ~ ~ ( v.x * hashMultiplier );
  802. const y = ~ ~ ( v.y * hashMultiplier );
  803. const z = ~ ~ ( v.z * hashMultiplier );
  804. return `${x},${y},${z}`;
  805. }
  806. // BufferGeometry.toNonIndexed() warns if the geometry is non-indexed
  807. // and returns the original geometry
  808. const resultGeometry = geometry.index ? geometry.toNonIndexed() : geometry;
  809. const posAttr = resultGeometry.attributes.position;
  810. const vertexMap = {};
  811. // find all the normals shared by commonly located vertices
  812. for ( let i = 0, l = posAttr.count / 3; i < l; i ++ ) {
  813. const i3 = 3 * i;
  814. const a = verts[ 0 ].fromBufferAttribute( posAttr, i3 + 0 );
  815. const b = verts[ 1 ].fromBufferAttribute( posAttr, i3 + 1 );
  816. const c = verts[ 2 ].fromBufferAttribute( posAttr, i3 + 2 );
  817. tempVec1.subVectors( c, b );
  818. tempVec2.subVectors( a, b );
  819. // add the normal to the map for all vertices
  820. const normal = new Vector3().crossVectors( tempVec1, tempVec2 ).normalize();
  821. for ( let n = 0; n < 3; n ++ ) {
  822. const vert = verts[ n ];
  823. const hash = hashVertex( vert );
  824. if ( ! ( hash in vertexMap ) ) {
  825. vertexMap[ hash ] = [];
  826. }
  827. vertexMap[ hash ].push( normal );
  828. }
  829. }
  830. // average normals from all vertices that share a common location if they are within the
  831. // provided crease threshold
  832. const normalArray = new Float32Array( posAttr.count * 3 );
  833. const normAttr = new BufferAttribute( normalArray, 3, false );
  834. for ( let i = 0, l = posAttr.count / 3; i < l; i ++ ) {
  835. // get the face normal for this vertex
  836. const i3 = 3 * i;
  837. const a = verts[ 0 ].fromBufferAttribute( posAttr, i3 + 0 );
  838. const b = verts[ 1 ].fromBufferAttribute( posAttr, i3 + 1 );
  839. const c = verts[ 2 ].fromBufferAttribute( posAttr, i3 + 2 );
  840. tempVec1.subVectors( c, b );
  841. tempVec2.subVectors( a, b );
  842. tempNorm.crossVectors( tempVec1, tempVec2 ).normalize();
  843. // average all normals that meet the threshold and set the normal value
  844. for ( let n = 0; n < 3; n ++ ) {
  845. const vert = verts[ n ];
  846. const hash = hashVertex( vert );
  847. const otherNormals = vertexMap[ hash ];
  848. tempNorm2.set( 0, 0, 0 );
  849. for ( let k = 0, lk = otherNormals.length; k < lk; k ++ ) {
  850. const otherNorm = otherNormals[ k ];
  851. if ( tempNorm.dot( otherNorm ) > creaseDot ) {
  852. tempNorm2.add( otherNorm );
  853. }
  854. }
  855. tempNorm2.normalize();
  856. normAttr.setXYZ( i3 + n, tempNorm2.x, tempNorm2.y, tempNorm2.z );
  857. }
  858. }
  859. resultGeometry.setAttribute( 'normal', normAttr );
  860. return resultGeometry;
  861. }
  862. export {
  863. computeMikkTSpaceTangents,
  864. mergeGeometries,
  865. mergeAttributes,
  866. interleaveAttributes,
  867. estimateBytesUsed,
  868. mergeVertices,
  869. toTrianglesDrawMode,
  870. computeMorphedAttributes,
  871. mergeGroups,
  872. toCreasedNormals
  873. };