BufferGeometryUtils.js 35 KB

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