BufferGeometryUtils.js 30 KB

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