BufferGeometryUtils.js 35 KB

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