BufferGeometryUtils.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332
  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.getCount() * attribute.itemSize );
  23. for ( let i = 0, j = 0; i < attribute.getCount(); 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 mergeBufferGeometries( 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: .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.' );
  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: .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.' );
  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: .mergeBufferGeometries() 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: .mergeBufferGeometries() 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: .mergeBufferGeometries() 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: .mergeBufferGeometries() 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 = mergeBufferAttributes( attributes[ name ] );
  139. if ( ! mergedAttribute ) {
  140. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() 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 = mergeBufferAttributes( morphAttributesToMerge );
  157. if ( ! mergedMorphAttribute ) {
  158. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() 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 mergeBufferAttributes( attributes ) {
  171. let TypedArray;
  172. let itemSize;
  173. let normalized;
  174. let arrayLength = 0;
  175. for ( let i = 0; i < attributes.length; ++ i ) {
  176. const attribute = attributes[ i ];
  177. if ( attribute.isInterleavedBufferAttribute ) {
  178. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported.' );
  179. return null;
  180. }
  181. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  182. if ( TypedArray !== attribute.array.constructor ) {
  183. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.' );
  184. return null;
  185. }
  186. if ( itemSize === undefined ) itemSize = attribute.itemSize;
  187. if ( itemSize !== attribute.itemSize ) {
  188. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.' );
  189. return null;
  190. }
  191. if ( normalized === undefined ) normalized = attribute.normalized;
  192. if ( normalized !== attribute.normalized ) {
  193. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.' );
  194. return null;
  195. }
  196. arrayLength += attribute.array.length;
  197. }
  198. const array = new TypedArray( arrayLength );
  199. let offset = 0;
  200. for ( let i = 0; i < attributes.length; ++ i ) {
  201. array.set( attributes[ i ].array, offset );
  202. offset += attributes[ i ].array.length;
  203. }
  204. return new BufferAttribute( array, itemSize, normalized );
  205. }
  206. /**
  207. * @param {BufferAttribute}
  208. * @return {BufferAttribute}
  209. */
  210. export function deepCloneAttribute( attribute ) {
  211. if ( attribute.isInstancedInterleavedBufferAttribute || attribute.isInterleavedBufferAttribute ) {
  212. return deinterleaveAttribute( attribute );
  213. }
  214. if ( attribute.isInstancedBufferAttribute ) {
  215. return new InstancedBufferAttribute().copy( attribute );
  216. }
  217. return new BufferAttribute().copy( attribute );
  218. }
  219. /**
  220. * @param {Array<BufferAttribute>} attributes
  221. * @return {Array<InterleavedBufferAttribute>}
  222. */
  223. function interleaveAttributes( attributes ) {
  224. // Interleaves the provided attributes into an InterleavedBuffer and returns
  225. // a set of InterleavedBufferAttributes for each attribute
  226. let TypedArray;
  227. let arrayLength = 0;
  228. let stride = 0;
  229. // calculate the length and type of the interleavedBuffer
  230. for ( let i = 0, l = attributes.length; i < l; ++ i ) {
  231. const attribute = attributes[ i ];
  232. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  233. if ( TypedArray !== attribute.array.constructor ) {
  234. console.error( 'AttributeBuffers of different types cannot be interleaved' );
  235. return null;
  236. }
  237. arrayLength += attribute.array.length;
  238. stride += attribute.itemSize;
  239. }
  240. // Create the set of buffer attributes
  241. const interleavedBuffer = new InterleavedBuffer( new TypedArray( arrayLength ), stride );
  242. let offset = 0;
  243. const res = [];
  244. const getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  245. const setters = [ 'setX', 'setY', 'setZ', 'setW' ];
  246. for ( let j = 0, l = attributes.length; j < l; j ++ ) {
  247. const attribute = attributes[ j ];
  248. const itemSize = attribute.itemSize;
  249. const count = attribute.count;
  250. const iba = new InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
  251. res.push( iba );
  252. offset += itemSize;
  253. // Move the data for each attribute into the new interleavedBuffer
  254. // at the appropriate offset
  255. for ( let c = 0; c < count; c ++ ) {
  256. for ( let k = 0; k < itemSize; k ++ ) {
  257. iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
  258. }
  259. }
  260. }
  261. return res;
  262. }
  263. // returns a new, non-interleaved version of the provided attribute
  264. export function deinterleaveAttribute( attribute ) {
  265. const cons = attribute.data.array.constructor;
  266. const count = attribute.count;
  267. const itemSize = attribute.itemSize;
  268. const normalized = attribute.normalized;
  269. const array = new cons( count * itemSize );
  270. let newAttribute;
  271. if ( attribute.isInstancedInterleavedBufferAttribute ) {
  272. newAttribute = new InstancedBufferAttribute( array, itemSize, normalized, attribute.meshPerAttribute );
  273. } else {
  274. newAttribute = new BufferAttribute( array, itemSize, normalized );
  275. }
  276. for ( let i = 0; i < count; i ++ ) {
  277. newAttribute.setX( i, attribute.getX( i ) );
  278. if ( itemSize >= 2 ) {
  279. newAttribute.setY( i, attribute.getY( i ) );
  280. }
  281. if ( itemSize >= 3 ) {
  282. newAttribute.setZ( i, attribute.getZ( i ) );
  283. }
  284. if ( itemSize >= 4 ) {
  285. newAttribute.setW( i, attribute.getW( i ) );
  286. }
  287. }
  288. return newAttribute;
  289. }
  290. // deinterleaves all attributes on the geometry
  291. export function deinterleaveGeometry( geometry ) {
  292. const attributes = geometry.attributes;
  293. const morphTargets = geometry.morphTargets;
  294. const attrMap = new Map();
  295. for ( const key in attributes ) {
  296. const attr = attributes[ key ];
  297. if ( attr.isInterleavedBufferAttribute ) {
  298. if ( ! attrMap.has( attr ) ) {
  299. attrMap.set( attr, deinterleaveAttribute( attr ) );
  300. }
  301. attributes[ key ] = attrMap.get( attr );
  302. }
  303. }
  304. for ( const key in morphTargets ) {
  305. const attr = morphTargets[ key ];
  306. if ( attr.isInterleavedBufferAttribute ) {
  307. if ( ! attrMap.has( attr ) ) {
  308. attrMap.set( attr, deinterleaveAttribute( attr ) );
  309. }
  310. morphTargets[ key ] = attrMap.get( attr );
  311. }
  312. }
  313. }
  314. /**
  315. * @param {Array<BufferGeometry>} geometry
  316. * @return {number}
  317. */
  318. function estimateBytesUsed( geometry ) {
  319. // Return the estimated memory used by this geometry in bytes
  320. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  321. // for InterleavedBufferAttributes.
  322. let mem = 0;
  323. for ( const name in geometry.attributes ) {
  324. const attr = geometry.getAttribute( name );
  325. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  326. }
  327. const indices = geometry.getIndex();
  328. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  329. return mem;
  330. }
  331. /**
  332. * @param {BufferGeometry} geometry
  333. * @param {number} tolerance
  334. * @return {BufferGeometry}
  335. */
  336. function mergeVertices( geometry, tolerance = 1e-4 ) {
  337. tolerance = Math.max( tolerance, Number.EPSILON );
  338. // Generate an index buffer if the geometry doesn't have one, or optimize it
  339. // if it's already available.
  340. const hashToIndex = {};
  341. const indices = geometry.getIndex();
  342. const positions = geometry.getAttribute( 'position' );
  343. const vertexCount = indices ? indices.count : positions.count;
  344. // next value for triangle indices
  345. let nextIndex = 0;
  346. // attributes and new attribute arrays
  347. const attributeNames = Object.keys( geometry.attributes );
  348. const tmpAttributes = {};
  349. const tmpMorphAttributes = {};
  350. const newIndices = [];
  351. const getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  352. const setters = [ 'setX', 'setY', 'setZ', 'setW' ];
  353. // Initialize the arrays, allocating space conservatively. Extra
  354. // space will be trimmed in the last step.
  355. for ( let i = 0, l = attributeNames.length; i < l; i ++ ) {
  356. const name = attributeNames[ i ];
  357. const attr = geometry.attributes[ name ];
  358. tmpAttributes[ name ] = new BufferAttribute(
  359. new attr.array.constructor( attr.count * attr.itemSize ),
  360. attr.itemSize,
  361. attr.normalized
  362. );
  363. const morphAttr = geometry.morphAttributes[ name ];
  364. if ( morphAttr ) {
  365. tmpMorphAttributes[ name ] = new BufferAttribute(
  366. new morphAttr.array.constructor( morphAttr.count * morphAttr.itemSize ),
  367. morphAttr.itemSize,
  368. morphAttr.normalized
  369. );
  370. }
  371. }
  372. // convert the error tolerance to an amount of decimal places to truncate to
  373. const decimalShift = Math.log10( 1 / tolerance );
  374. const shiftMultiplier = Math.pow( 10, decimalShift );
  375. for ( let i = 0; i < vertexCount; i ++ ) {
  376. const index = indices ? indices.getX( i ) : i;
  377. // Generate a hash for the vertex attributes at the current index 'i'
  378. let hash = '';
  379. for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
  380. const name = attributeNames[ j ];
  381. const attribute = geometry.getAttribute( name );
  382. const itemSize = attribute.itemSize;
  383. for ( let k = 0; k < itemSize; k ++ ) {
  384. // double tilde truncates the decimal value
  385. hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * shiftMultiplier ) },`;
  386. }
  387. }
  388. // Add another reference to the vertex if it's already
  389. // used by another index
  390. if ( hash in hashToIndex ) {
  391. newIndices.push( hashToIndex[ hash ] );
  392. } else {
  393. // copy data to the new index in the temporary attributes
  394. for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
  395. const name = attributeNames[ j ];
  396. const attribute = geometry.getAttribute( name );
  397. const morphAttr = geometry.morphAttributes[ name ];
  398. const itemSize = attribute.itemSize;
  399. const newarray = tmpAttributes[ name ];
  400. const newMorphArrays = tmpMorphAttributes[ name ];
  401. for ( let k = 0; k < itemSize; k ++ ) {
  402. const getterFunc = getters[ k ];
  403. const setterFunc = setters[ k ];
  404. newarray[ setterFunc ]( nextIndex, attribute[ getterFunc ]( index ) );
  405. if ( morphAttr ) {
  406. for ( let m = 0, ml = morphAttr.length; m < ml; m ++ ) {
  407. newMorphArrays[ m ][ setterFunc ]( nextIndex, morphAttr[ m ][ getterFunc ]( index ) );
  408. }
  409. }
  410. }
  411. }
  412. hashToIndex[ hash ] = nextIndex;
  413. newIndices.push( nextIndex );
  414. nextIndex ++;
  415. }
  416. }
  417. // generate result BufferGeometry
  418. const result = geometry.clone();
  419. for ( const name in geometry.attributes ) {
  420. const tmpAttribute = tmpAttributes[ name ];
  421. result.setAttribute( name, new BufferAttribute(
  422. tmpAttribute.array.slice( 0, nextIndex * tmpAttribute.itemSize ),
  423. tmpAttribute.itemSize,
  424. tmpAttribute.normalized,
  425. ) );
  426. if ( ! ( name in tmpMorphAttributes ) ) continue;
  427. for ( let j = 0; j < tmpMorphAttributes[ name ].length; j ++ ) {
  428. const tmpMorphAttribute = tmpMorphAttributes[ name ][ j ];
  429. result.morphAttributes[ name ][ j ] = new BufferAttribute(
  430. tmpMorphAttribute.array.slice( 0, nextIndex * tmpMorphAttribute.itemSize ),
  431. tmpMorphAttribute.itemSize,
  432. tmpMorphAttribute.normalized,
  433. );
  434. }
  435. }
  436. // indices
  437. result.setIndex( newIndices );
  438. return result;
  439. }
  440. /**
  441. * @param {BufferGeometry} geometry
  442. * @param {number} drawMode
  443. * @return {BufferGeometry}
  444. */
  445. function toTrianglesDrawMode( geometry, drawMode ) {
  446. if ( drawMode === TrianglesDrawMode ) {
  447. console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' );
  448. return geometry;
  449. }
  450. if ( drawMode === TriangleFanDrawMode || drawMode === TriangleStripDrawMode ) {
  451. let index = geometry.getIndex();
  452. // generate index if not present
  453. if ( index === null ) {
  454. const indices = [];
  455. const position = geometry.getAttribute( 'position' );
  456. if ( position !== undefined ) {
  457. for ( let i = 0; i < position.count; i ++ ) {
  458. indices.push( i );
  459. }
  460. geometry.setIndex( indices );
  461. index = geometry.getIndex();
  462. } else {
  463. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  464. return geometry;
  465. }
  466. }
  467. //
  468. const numberOfTriangles = index.count - 2;
  469. const newIndices = [];
  470. if ( drawMode === TriangleFanDrawMode ) {
  471. // gl.TRIANGLE_FAN
  472. for ( let i = 1; i <= numberOfTriangles; i ++ ) {
  473. newIndices.push( index.getX( 0 ) );
  474. newIndices.push( index.getX( i ) );
  475. newIndices.push( index.getX( i + 1 ) );
  476. }
  477. } else {
  478. // gl.TRIANGLE_STRIP
  479. for ( let i = 0; i < numberOfTriangles; i ++ ) {
  480. if ( i % 2 === 0 ) {
  481. newIndices.push( index.getX( i ) );
  482. newIndices.push( index.getX( i + 1 ) );
  483. newIndices.push( index.getX( i + 2 ) );
  484. } else {
  485. newIndices.push( index.getX( i + 2 ) );
  486. newIndices.push( index.getX( i + 1 ) );
  487. newIndices.push( index.getX( i ) );
  488. }
  489. }
  490. }
  491. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  492. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  493. }
  494. // build final geometry
  495. const newGeometry = geometry.clone();
  496. newGeometry.setIndex( newIndices );
  497. newGeometry.clearGroups();
  498. return newGeometry;
  499. } else {
  500. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode );
  501. return geometry;
  502. }
  503. }
  504. /**
  505. * Calculates the morphed attributes of a morphed/skinned BufferGeometry.
  506. * Helpful for Raytracing or Decals.
  507. * @param {Mesh | Line | Points} object An instance of Mesh, Line or Points.
  508. * @return {Object} An Object with original position/normal attributes and morphed ones.
  509. */
  510. function computeMorphedAttributes( object ) {
  511. const _vA = new Vector3();
  512. const _vB = new Vector3();
  513. const _vC = new Vector3();
  514. const _tempA = new Vector3();
  515. const _tempB = new Vector3();
  516. const _tempC = new Vector3();
  517. const _morphA = new Vector3();
  518. const _morphB = new Vector3();
  519. const _morphC = new Vector3();
  520. function _calculateMorphedAttributeData(
  521. object,
  522. attribute,
  523. morphAttribute,
  524. morphTargetsRelative,
  525. a,
  526. b,
  527. c,
  528. modifiedAttributeArray
  529. ) {
  530. _vA.fromBufferAttribute( attribute, a );
  531. _vB.fromBufferAttribute( attribute, b );
  532. _vC.fromBufferAttribute( attribute, c );
  533. const morphInfluences = object.morphTargetInfluences;
  534. if ( morphAttribute && morphInfluences ) {
  535. _morphA.set( 0, 0, 0 );
  536. _morphB.set( 0, 0, 0 );
  537. _morphC.set( 0, 0, 0 );
  538. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  539. const influence = morphInfluences[ i ];
  540. const morph = morphAttribute[ i ];
  541. if ( influence === 0 ) continue;
  542. _tempA.fromBufferAttribute( morph, a );
  543. _tempB.fromBufferAttribute( morph, b );
  544. _tempC.fromBufferAttribute( morph, c );
  545. if ( morphTargetsRelative ) {
  546. _morphA.addScaledVector( _tempA, influence );
  547. _morphB.addScaledVector( _tempB, influence );
  548. _morphC.addScaledVector( _tempC, influence );
  549. } else {
  550. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  551. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  552. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  553. }
  554. }
  555. _vA.add( _morphA );
  556. _vB.add( _morphB );
  557. _vC.add( _morphC );
  558. }
  559. if ( object.isSkinnedMesh ) {
  560. object.applyBoneTransform( a, _vA );
  561. object.applyBoneTransform( b, _vB );
  562. object.applyBoneTransform( c, _vC );
  563. }
  564. modifiedAttributeArray[ a * 3 + 0 ] = _vA.x;
  565. modifiedAttributeArray[ a * 3 + 1 ] = _vA.y;
  566. modifiedAttributeArray[ a * 3 + 2 ] = _vA.z;
  567. modifiedAttributeArray[ b * 3 + 0 ] = _vB.x;
  568. modifiedAttributeArray[ b * 3 + 1 ] = _vB.y;
  569. modifiedAttributeArray[ b * 3 + 2 ] = _vB.z;
  570. modifiedAttributeArray[ c * 3 + 0 ] = _vC.x;
  571. modifiedAttributeArray[ c * 3 + 1 ] = _vC.y;
  572. modifiedAttributeArray[ c * 3 + 2 ] = _vC.z;
  573. }
  574. const geometry = object.geometry;
  575. const material = object.material;
  576. let a, b, c;
  577. const index = geometry.index;
  578. const positionAttribute = geometry.attributes.position;
  579. const morphPosition = geometry.morphAttributes.position;
  580. const morphTargetsRelative = geometry.morphTargetsRelative;
  581. const normalAttribute = geometry.attributes.normal;
  582. const morphNormal = geometry.morphAttributes.position;
  583. const groups = geometry.groups;
  584. const drawRange = geometry.drawRange;
  585. let i, j, il, jl;
  586. let group;
  587. let start, end;
  588. const modifiedPosition = new Float32Array( positionAttribute.count * positionAttribute.itemSize );
  589. const modifiedNormal = new Float32Array( normalAttribute.count * normalAttribute.itemSize );
  590. if ( index !== null ) {
  591. // indexed buffer geometry
  592. if ( Array.isArray( material ) ) {
  593. for ( i = 0, il = groups.length; i < il; i ++ ) {
  594. group = groups[ i ];
  595. start = Math.max( group.start, drawRange.start );
  596. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  597. for ( j = start, jl = end; j < jl; j += 3 ) {
  598. a = index.getX( j );
  599. b = index.getX( j + 1 );
  600. c = index.getX( j + 2 );
  601. _calculateMorphedAttributeData(
  602. object,
  603. positionAttribute,
  604. morphPosition,
  605. morphTargetsRelative,
  606. a, b, c,
  607. modifiedPosition
  608. );
  609. _calculateMorphedAttributeData(
  610. object,
  611. normalAttribute,
  612. morphNormal,
  613. morphTargetsRelative,
  614. a, b, c,
  615. modifiedNormal
  616. );
  617. }
  618. }
  619. } else {
  620. start = Math.max( 0, drawRange.start );
  621. end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  622. for ( i = start, il = end; i < il; i += 3 ) {
  623. a = index.getX( i );
  624. b = index.getX( i + 1 );
  625. c = index.getX( i + 2 );
  626. _calculateMorphedAttributeData(
  627. object,
  628. positionAttribute,
  629. morphPosition,
  630. morphTargetsRelative,
  631. a, b, c,
  632. modifiedPosition
  633. );
  634. _calculateMorphedAttributeData(
  635. object,
  636. normalAttribute,
  637. morphNormal,
  638. morphTargetsRelative,
  639. a, b, c,
  640. modifiedNormal
  641. );
  642. }
  643. }
  644. } else {
  645. // non-indexed buffer geometry
  646. if ( Array.isArray( material ) ) {
  647. for ( i = 0, il = groups.length; i < il; i ++ ) {
  648. group = groups[ i ];
  649. start = Math.max( group.start, drawRange.start );
  650. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  651. for ( j = start, jl = end; j < jl; j += 3 ) {
  652. a = j;
  653. b = j + 1;
  654. c = j + 2;
  655. _calculateMorphedAttributeData(
  656. object,
  657. positionAttribute,
  658. morphPosition,
  659. morphTargetsRelative,
  660. a, b, c,
  661. modifiedPosition
  662. );
  663. _calculateMorphedAttributeData(
  664. object,
  665. normalAttribute,
  666. morphNormal,
  667. morphTargetsRelative,
  668. a, b, c,
  669. modifiedNormal
  670. );
  671. }
  672. }
  673. } else {
  674. start = Math.max( 0, drawRange.start );
  675. end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  676. for ( i = start, il = end; i < il; i += 3 ) {
  677. a = i;
  678. b = i + 1;
  679. c = i + 2;
  680. _calculateMorphedAttributeData(
  681. object,
  682. positionAttribute,
  683. morphPosition,
  684. morphTargetsRelative,
  685. a, b, c,
  686. modifiedPosition
  687. );
  688. _calculateMorphedAttributeData(
  689. object,
  690. normalAttribute,
  691. morphNormal,
  692. morphTargetsRelative,
  693. a, b, c,
  694. modifiedNormal
  695. );
  696. }
  697. }
  698. }
  699. const morphedPositionAttribute = new Float32BufferAttribute( modifiedPosition, 3 );
  700. const morphedNormalAttribute = new Float32BufferAttribute( modifiedNormal, 3 );
  701. return {
  702. positionAttribute: positionAttribute,
  703. normalAttribute: normalAttribute,
  704. morphedPositionAttribute: morphedPositionAttribute,
  705. morphedNormalAttribute: morphedNormalAttribute
  706. };
  707. }
  708. function mergeGroups( geometry ) {
  709. if ( geometry.groups.length === 0 ) {
  710. console.warn( 'THREE.BufferGeometryUtils.mergeGroups(): No groups are defined. Nothing to merge.' );
  711. return geometry;
  712. }
  713. let groups = geometry.groups;
  714. // sort groups by material index
  715. groups = groups.sort( ( a, b ) => {
  716. if ( a.materialIndex !== b.materialIndex ) return a.materialIndex - b.materialIndex;
  717. return a.start - b.start;
  718. } );
  719. // create index for non-indexed geometries
  720. if ( geometry.getIndex() === null ) {
  721. const positionAttribute = geometry.getAttribute( 'position' );
  722. const indices = [];
  723. for ( let i = 0; i < positionAttribute.count; i += 3 ) {
  724. indices.push( i, i + 1, i + 2 );
  725. }
  726. geometry.setIndex( indices );
  727. }
  728. // sort index
  729. const index = geometry.getIndex();
  730. const newIndices = [];
  731. for ( let i = 0; i < groups.length; i ++ ) {
  732. const group = groups[ i ];
  733. const groupStart = group.start;
  734. const groupLength = groupStart + group.count;
  735. for ( let j = groupStart; j < groupLength; j ++ ) {
  736. newIndices.push( index.getX( j ) );
  737. }
  738. }
  739. geometry.dispose(); // Required to force buffer recreation
  740. geometry.setIndex( newIndices );
  741. // update groups indices
  742. let start = 0;
  743. for ( let i = 0; i < groups.length; i ++ ) {
  744. const group = groups[ i ];
  745. group.start = start;
  746. start += group.count;
  747. }
  748. // merge groups
  749. let currentGroup = groups[ 0 ];
  750. geometry.groups = [ currentGroup ];
  751. for ( let i = 1; i < groups.length; i ++ ) {
  752. const group = groups[ i ];
  753. if ( currentGroup.materialIndex === group.materialIndex ) {
  754. currentGroup.count += group.count;
  755. } else {
  756. currentGroup = group;
  757. geometry.groups.push( currentGroup );
  758. }
  759. }
  760. return geometry;
  761. }
  762. // Creates a new, non-indexed geometry with smooth normals everywhere except faces that meet at
  763. // an angle greater than the crease angle.
  764. function toCreasedNormals( geometry, creaseAngle = Math.PI / 3 /* 60 degrees */ ) {
  765. const creaseDot = Math.cos( creaseAngle );
  766. const hashMultiplier = ( 1 + 1e-10 ) * 1e2;
  767. // reusable vertors
  768. const verts = [ new Vector3(), new Vector3(), new Vector3() ];
  769. const tempVec1 = new Vector3();
  770. const tempVec2 = new Vector3();
  771. const tempNorm = new Vector3();
  772. const tempNorm2 = new Vector3();
  773. // hashes a vector
  774. function hashVertex( v ) {
  775. const x = ~ ~ ( v.x * hashMultiplier );
  776. const y = ~ ~ ( v.y * hashMultiplier );
  777. const z = ~ ~ ( v.z * hashMultiplier );
  778. return `${x},${y},${z}`;
  779. }
  780. const resultGeometry = geometry.toNonIndexed();
  781. const posAttr = resultGeometry.attributes.position;
  782. const vertexMap = {};
  783. // find all the normals shared by commonly located vertices
  784. for ( let i = 0, l = posAttr.count / 3; i < l; i ++ ) {
  785. const i3 = 3 * i;
  786. const a = verts[ 0 ].fromBufferAttribute( posAttr, i3 + 0 );
  787. const b = verts[ 1 ].fromBufferAttribute( posAttr, i3 + 1 );
  788. const c = verts[ 2 ].fromBufferAttribute( posAttr, i3 + 2 );
  789. tempVec1.subVectors( c, b );
  790. tempVec2.subVectors( a, b );
  791. // add the normal to the map for all vertices
  792. const normal = new Vector3().crossVectors( tempVec1, tempVec2 ).normalize();
  793. for ( let n = 0; n < 3; n ++ ) {
  794. const vert = verts[ n ];
  795. const hash = hashVertex( vert );
  796. if ( ! ( hash in vertexMap ) ) {
  797. vertexMap[ hash ] = [];
  798. }
  799. vertexMap[ hash ].push( normal );
  800. }
  801. }
  802. // average normals from all vertices that share a common location if they are within the
  803. // provided crease threshold
  804. const normalArray = new Float32Array( posAttr.count * 3 );
  805. const normAttr = new BufferAttribute( normalArray, 3, false );
  806. for ( let i = 0, l = posAttr.count / 3; i < l; i ++ ) {
  807. // get the face normal for this vertex
  808. const i3 = 3 * i;
  809. const a = verts[ 0 ].fromBufferAttribute( posAttr, i3 + 0 );
  810. const b = verts[ 1 ].fromBufferAttribute( posAttr, i3 + 1 );
  811. const c = verts[ 2 ].fromBufferAttribute( posAttr, i3 + 2 );
  812. tempVec1.subVectors( c, b );
  813. tempVec2.subVectors( a, b );
  814. tempNorm.crossVectors( tempVec1, tempVec2 ).normalize();
  815. // average all normals that meet the threshold and set the normal value
  816. for ( let n = 0; n < 3; n ++ ) {
  817. const vert = verts[ n ];
  818. const hash = hashVertex( vert );
  819. const otherNormals = vertexMap[ hash ];
  820. tempNorm2.set( 0, 0, 0 );
  821. for ( let k = 0, lk = otherNormals.length; k < lk; k ++ ) {
  822. const otherNorm = otherNormals[ k ];
  823. if ( tempNorm.dot( otherNorm ) > creaseDot ) {
  824. tempNorm2.add( otherNorm );
  825. }
  826. }
  827. tempNorm2.normalize();
  828. normAttr.setXYZ( i3 + n, tempNorm2.x, tempNorm2.y, tempNorm2.z );
  829. }
  830. }
  831. resultGeometry.setAttribute( 'normal', normAttr );
  832. return resultGeometry;
  833. }
  834. export {
  835. computeMikkTSpaceTangents,
  836. mergeBufferGeometries,
  837. mergeBufferAttributes,
  838. interleaveAttributes,
  839. estimateBytesUsed,
  840. mergeVertices,
  841. toTrianglesDrawMode,
  842. computeMorphedAttributes,
  843. mergeGroups,
  844. toCreasedNormals
  845. };