BufferGeometryUtils.js 30 KB

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