BufferGeometryUtils.js 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435
  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 ) break;
  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.position;
  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. };