BufferGeometryUtils.js 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373
  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.count * attribute.itemSize );
  23. for ( let i = 0, j = 0; i < attribute.count; 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 gpuType = - 1;
  175. let arrayLength = 0;
  176. for ( let i = 0; i < attributes.length; ++ i ) {
  177. const attribute = attributes[ i ];
  178. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  179. if ( TypedArray !== attribute.array.constructor ) {
  180. console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.' );
  181. return null;
  182. }
  183. if ( itemSize === undefined ) itemSize = attribute.itemSize;
  184. if ( itemSize !== attribute.itemSize ) {
  185. console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.' );
  186. return null;
  187. }
  188. if ( normalized === undefined ) normalized = attribute.normalized;
  189. if ( normalized !== attribute.normalized ) {
  190. console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.' );
  191. return null;
  192. }
  193. if ( gpuType === - 1 ) gpuType = attribute.gpuType;
  194. if ( gpuType !== attribute.gpuType ) {
  195. console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes.' );
  196. return null;
  197. }
  198. arrayLength += attribute.count * itemSize;
  199. }
  200. const array = new TypedArray( arrayLength );
  201. const result = new BufferAttribute( array, itemSize, normalized );
  202. let offset = 0;
  203. for ( let i = 0; i < attributes.length; ++ i ) {
  204. const attribute = attributes[ i ];
  205. if ( attribute.isInterleavedBufferAttribute ) {
  206. const tupleOffset = offset / itemSize;
  207. for ( let j = 0, l = attribute.count; j < l; j ++ ) {
  208. for ( let c = 0; c < itemSize; c ++ ) {
  209. const value = attribute.getComponent( j, c );
  210. result.setComponent( j + tupleOffset, c, value );
  211. }
  212. }
  213. } else {
  214. array.set( attribute.array, offset );
  215. }
  216. offset += attribute.count * itemSize;
  217. }
  218. if ( gpuType !== undefined ) {
  219. result.gpuType = gpuType;
  220. }
  221. return result;
  222. }
  223. /**
  224. * @param {BufferAttribute}
  225. * @return {BufferAttribute}
  226. */
  227. export function deepCloneAttribute( attribute ) {
  228. if ( attribute.isInstancedInterleavedBufferAttribute || attribute.isInterleavedBufferAttribute ) {
  229. return deinterleaveAttribute( attribute );
  230. }
  231. if ( attribute.isInstancedBufferAttribute ) {
  232. return new InstancedBufferAttribute().copy( attribute );
  233. }
  234. return new BufferAttribute().copy( attribute );
  235. }
  236. /**
  237. * @param {Array<BufferAttribute>} attributes
  238. * @return {Array<InterleavedBufferAttribute>}
  239. */
  240. function interleaveAttributes( attributes ) {
  241. // Interleaves the provided attributes into an InterleavedBuffer and returns
  242. // a set of InterleavedBufferAttributes for each attribute
  243. let TypedArray;
  244. let arrayLength = 0;
  245. let stride = 0;
  246. // calculate the length and type of the interleavedBuffer
  247. for ( let i = 0, l = attributes.length; i < l; ++ i ) {
  248. const attribute = attributes[ i ];
  249. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  250. if ( TypedArray !== attribute.array.constructor ) {
  251. console.error( 'AttributeBuffers of different types cannot be interleaved' );
  252. return null;
  253. }
  254. arrayLength += attribute.array.length;
  255. stride += attribute.itemSize;
  256. }
  257. // Create the set of buffer attributes
  258. const interleavedBuffer = new InterleavedBuffer( new TypedArray( arrayLength ), stride );
  259. let offset = 0;
  260. const res = [];
  261. const getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  262. const setters = [ 'setX', 'setY', 'setZ', 'setW' ];
  263. for ( let j = 0, l = attributes.length; j < l; j ++ ) {
  264. const attribute = attributes[ j ];
  265. const itemSize = attribute.itemSize;
  266. const count = attribute.count;
  267. const iba = new InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
  268. res.push( iba );
  269. offset += itemSize;
  270. // Move the data for each attribute into the new interleavedBuffer
  271. // at the appropriate offset
  272. for ( let c = 0; c < count; c ++ ) {
  273. for ( let k = 0; k < itemSize; k ++ ) {
  274. iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
  275. }
  276. }
  277. }
  278. return res;
  279. }
  280. // returns a new, non-interleaved version of the provided attribute
  281. export function deinterleaveAttribute( attribute ) {
  282. const cons = attribute.data.array.constructor;
  283. const count = attribute.count;
  284. const itemSize = attribute.itemSize;
  285. const normalized = attribute.normalized;
  286. const array = new cons( count * itemSize );
  287. let newAttribute;
  288. if ( attribute.isInstancedInterleavedBufferAttribute ) {
  289. newAttribute = new InstancedBufferAttribute( array, itemSize, normalized, attribute.meshPerAttribute );
  290. } else {
  291. newAttribute = new BufferAttribute( array, itemSize, normalized );
  292. }
  293. for ( let i = 0; i < count; i ++ ) {
  294. newAttribute.setX( i, attribute.getX( i ) );
  295. if ( itemSize >= 2 ) {
  296. newAttribute.setY( i, attribute.getY( i ) );
  297. }
  298. if ( itemSize >= 3 ) {
  299. newAttribute.setZ( i, attribute.getZ( i ) );
  300. }
  301. if ( itemSize >= 4 ) {
  302. newAttribute.setW( i, attribute.getW( i ) );
  303. }
  304. }
  305. return newAttribute;
  306. }
  307. // deinterleaves all attributes on the geometry
  308. export function deinterleaveGeometry( geometry ) {
  309. const attributes = geometry.attributes;
  310. const morphTargets = geometry.morphTargets;
  311. const attrMap = new Map();
  312. for ( const key in attributes ) {
  313. const attr = attributes[ key ];
  314. if ( attr.isInterleavedBufferAttribute ) {
  315. if ( ! attrMap.has( attr ) ) {
  316. attrMap.set( attr, deinterleaveAttribute( attr ) );
  317. }
  318. attributes[ key ] = attrMap.get( attr );
  319. }
  320. }
  321. for ( const key in morphTargets ) {
  322. const attr = morphTargets[ key ];
  323. if ( attr.isInterleavedBufferAttribute ) {
  324. if ( ! attrMap.has( attr ) ) {
  325. attrMap.set( attr, deinterleaveAttribute( attr ) );
  326. }
  327. morphTargets[ key ] = attrMap.get( attr );
  328. }
  329. }
  330. }
  331. /**
  332. * @param {BufferGeometry} geometry
  333. * @return {number}
  334. */
  335. function estimateBytesUsed( geometry ) {
  336. // Return the estimated memory used by this geometry in bytes
  337. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  338. // for InterleavedBufferAttributes.
  339. let mem = 0;
  340. for ( const name in geometry.attributes ) {
  341. const attr = geometry.getAttribute( name );
  342. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  343. }
  344. const indices = geometry.getIndex();
  345. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  346. return mem;
  347. }
  348. /**
  349. * @param {BufferGeometry} geometry
  350. * @param {number} tolerance
  351. * @return {BufferGeometry}
  352. */
  353. function mergeVertices( geometry, tolerance = 1e-4 ) {
  354. tolerance = Math.max( tolerance, Number.EPSILON );
  355. // Generate an index buffer if the geometry doesn't have one, or optimize it
  356. // if it's already available.
  357. const hashToIndex = {};
  358. const indices = geometry.getIndex();
  359. const positions = geometry.getAttribute( 'position' );
  360. const vertexCount = indices ? indices.count : positions.count;
  361. // next value for triangle indices
  362. let nextIndex = 0;
  363. // attributes and new attribute arrays
  364. const attributeNames = Object.keys( geometry.attributes );
  365. const tmpAttributes = {};
  366. const tmpMorphAttributes = {};
  367. const newIndices = [];
  368. const getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  369. const setters = [ 'setX', 'setY', 'setZ', 'setW' ];
  370. // Initialize the arrays, allocating space conservatively. Extra
  371. // space will be trimmed in the last step.
  372. for ( let i = 0, l = attributeNames.length; i < l; i ++ ) {
  373. const name = attributeNames[ i ];
  374. const attr = geometry.attributes[ name ];
  375. tmpAttributes[ name ] = new attr.constructor(
  376. new attr.array.constructor( attr.count * attr.itemSize ),
  377. attr.itemSize,
  378. attr.normalized
  379. );
  380. const morphAttributes = geometry.morphAttributes[ name ];
  381. if ( morphAttributes ) {
  382. if ( ! tmpMorphAttributes[ name ] ) tmpMorphAttributes[ name ] = [];
  383. morphAttributes.forEach( ( morphAttr, i ) => {
  384. const array = new morphAttr.array.constructor( morphAttr.count * morphAttr.itemSize );
  385. tmpMorphAttributes[ name ][ i ] = new morphAttr.constructor( array, morphAttr.itemSize, morphAttr.normalized );
  386. } );
  387. }
  388. }
  389. // convert the error tolerance to an amount of decimal places to truncate to
  390. const halfTolerance = tolerance * 0.5;
  391. const exponent = Math.log10( 1 / tolerance );
  392. const hashMultiplier = Math.pow( 10, exponent );
  393. const hashAdditive = halfTolerance * hashMultiplier;
  394. for ( let i = 0; i < vertexCount; i ++ ) {
  395. const index = indices ? indices.getX( i ) : i;
  396. // Generate a hash for the vertex attributes at the current index 'i'
  397. let hash = '';
  398. for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
  399. const name = attributeNames[ j ];
  400. const attribute = geometry.getAttribute( name );
  401. const itemSize = attribute.itemSize;
  402. for ( let k = 0; k < itemSize; k ++ ) {
  403. // double tilde truncates the decimal value
  404. hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * hashMultiplier + hashAdditive ) },`;
  405. }
  406. }
  407. // Add another reference to the vertex if it's already
  408. // used by another index
  409. if ( hash in hashToIndex ) {
  410. newIndices.push( hashToIndex[ hash ] );
  411. } else {
  412. // copy data to the new index in the temporary attributes
  413. for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
  414. const name = attributeNames[ j ];
  415. const attribute = geometry.getAttribute( name );
  416. const morphAttributes = geometry.morphAttributes[ name ];
  417. const itemSize = attribute.itemSize;
  418. const newArray = tmpAttributes[ name ];
  419. const newMorphArrays = tmpMorphAttributes[ name ];
  420. for ( let k = 0; k < itemSize; k ++ ) {
  421. const getterFunc = getters[ k ];
  422. const setterFunc = setters[ k ];
  423. newArray[ setterFunc ]( nextIndex, attribute[ getterFunc ]( index ) );
  424. if ( morphAttributes ) {
  425. for ( let m = 0, ml = morphAttributes.length; m < ml; m ++ ) {
  426. newMorphArrays[ m ][ setterFunc ]( nextIndex, morphAttributes[ m ][ getterFunc ]( index ) );
  427. }
  428. }
  429. }
  430. }
  431. hashToIndex[ hash ] = nextIndex;
  432. newIndices.push( nextIndex );
  433. nextIndex ++;
  434. }
  435. }
  436. // generate result BufferGeometry
  437. const result = geometry.clone();
  438. for ( const name in geometry.attributes ) {
  439. const tmpAttribute = tmpAttributes[ name ];
  440. result.setAttribute( name, new tmpAttribute.constructor(
  441. tmpAttribute.array.slice( 0, nextIndex * tmpAttribute.itemSize ),
  442. tmpAttribute.itemSize,
  443. tmpAttribute.normalized,
  444. ) );
  445. if ( ! ( name in tmpMorphAttributes ) ) continue;
  446. for ( let j = 0; j < tmpMorphAttributes[ name ].length; j ++ ) {
  447. const tmpMorphAttribute = tmpMorphAttributes[ name ][ j ];
  448. result.morphAttributes[ name ][ j ] = new tmpMorphAttribute.constructor(
  449. tmpMorphAttribute.array.slice( 0, nextIndex * tmpMorphAttribute.itemSize ),
  450. tmpMorphAttribute.itemSize,
  451. tmpMorphAttribute.normalized,
  452. );
  453. }
  454. }
  455. // indices
  456. result.setIndex( newIndices );
  457. return result;
  458. }
  459. /**
  460. * @param {BufferGeometry} geometry
  461. * @param {number} drawMode
  462. * @return {BufferGeometry}
  463. */
  464. function toTrianglesDrawMode( geometry, drawMode ) {
  465. if ( drawMode === TrianglesDrawMode ) {
  466. console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' );
  467. return geometry;
  468. }
  469. if ( drawMode === TriangleFanDrawMode || drawMode === TriangleStripDrawMode ) {
  470. let index = geometry.getIndex();
  471. // generate index if not present
  472. if ( index === null ) {
  473. const indices = [];
  474. const position = geometry.getAttribute( 'position' );
  475. if ( position !== undefined ) {
  476. for ( let i = 0; i < position.count; i ++ ) {
  477. indices.push( i );
  478. }
  479. geometry.setIndex( indices );
  480. index = geometry.getIndex();
  481. } else {
  482. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  483. return geometry;
  484. }
  485. }
  486. //
  487. const numberOfTriangles = index.count - 2;
  488. const newIndices = [];
  489. if ( drawMode === TriangleFanDrawMode ) {
  490. // gl.TRIANGLE_FAN
  491. for ( let i = 1; i <= numberOfTriangles; i ++ ) {
  492. newIndices.push( index.getX( 0 ) );
  493. newIndices.push( index.getX( i ) );
  494. newIndices.push( index.getX( i + 1 ) );
  495. }
  496. } else {
  497. // gl.TRIANGLE_STRIP
  498. for ( let i = 0; i < numberOfTriangles; i ++ ) {
  499. if ( i % 2 === 0 ) {
  500. newIndices.push( index.getX( i ) );
  501. newIndices.push( index.getX( i + 1 ) );
  502. newIndices.push( index.getX( i + 2 ) );
  503. } else {
  504. newIndices.push( index.getX( i + 2 ) );
  505. newIndices.push( index.getX( i + 1 ) );
  506. newIndices.push( index.getX( i ) );
  507. }
  508. }
  509. }
  510. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  511. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  512. }
  513. // build final geometry
  514. const newGeometry = geometry.clone();
  515. newGeometry.setIndex( newIndices );
  516. newGeometry.clearGroups();
  517. return newGeometry;
  518. } else {
  519. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode );
  520. return geometry;
  521. }
  522. }
  523. /**
  524. * Calculates the morphed attributes of a morphed/skinned BufferGeometry.
  525. * Helpful for Raytracing or Decals.
  526. * @param {Mesh | Line | Points} object An instance of Mesh, Line or Points.
  527. * @return {Object} An Object with original position/normal attributes and morphed ones.
  528. */
  529. function computeMorphedAttributes( object ) {
  530. const _vA = new Vector3();
  531. const _vB = new Vector3();
  532. const _vC = new Vector3();
  533. const _tempA = new Vector3();
  534. const _tempB = new Vector3();
  535. const _tempC = new Vector3();
  536. const _morphA = new Vector3();
  537. const _morphB = new Vector3();
  538. const _morphC = new Vector3();
  539. function _calculateMorphedAttributeData(
  540. object,
  541. attribute,
  542. morphAttribute,
  543. morphTargetsRelative,
  544. a,
  545. b,
  546. c,
  547. modifiedAttributeArray
  548. ) {
  549. _vA.fromBufferAttribute( attribute, a );
  550. _vB.fromBufferAttribute( attribute, b );
  551. _vC.fromBufferAttribute( attribute, c );
  552. const morphInfluences = object.morphTargetInfluences;
  553. if ( morphAttribute && morphInfluences ) {
  554. _morphA.set( 0, 0, 0 );
  555. _morphB.set( 0, 0, 0 );
  556. _morphC.set( 0, 0, 0 );
  557. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  558. const influence = morphInfluences[ i ];
  559. const morph = morphAttribute[ i ];
  560. if ( influence === 0 ) continue;
  561. _tempA.fromBufferAttribute( morph, a );
  562. _tempB.fromBufferAttribute( morph, b );
  563. _tempC.fromBufferAttribute( morph, c );
  564. if ( morphTargetsRelative ) {
  565. _morphA.addScaledVector( _tempA, influence );
  566. _morphB.addScaledVector( _tempB, influence );
  567. _morphC.addScaledVector( _tempC, influence );
  568. } else {
  569. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  570. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  571. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  572. }
  573. }
  574. _vA.add( _morphA );
  575. _vB.add( _morphB );
  576. _vC.add( _morphC );
  577. }
  578. if ( object.isSkinnedMesh ) {
  579. object.applyBoneTransform( a, _vA );
  580. object.applyBoneTransform( b, _vB );
  581. object.applyBoneTransform( c, _vC );
  582. }
  583. modifiedAttributeArray[ a * 3 + 0 ] = _vA.x;
  584. modifiedAttributeArray[ a * 3 + 1 ] = _vA.y;
  585. modifiedAttributeArray[ a * 3 + 2 ] = _vA.z;
  586. modifiedAttributeArray[ b * 3 + 0 ] = _vB.x;
  587. modifiedAttributeArray[ b * 3 + 1 ] = _vB.y;
  588. modifiedAttributeArray[ b * 3 + 2 ] = _vB.z;
  589. modifiedAttributeArray[ c * 3 + 0 ] = _vC.x;
  590. modifiedAttributeArray[ c * 3 + 1 ] = _vC.y;
  591. modifiedAttributeArray[ c * 3 + 2 ] = _vC.z;
  592. }
  593. const geometry = object.geometry;
  594. const material = object.material;
  595. let a, b, c;
  596. const index = geometry.index;
  597. const positionAttribute = geometry.attributes.position;
  598. const morphPosition = geometry.morphAttributes.position;
  599. const morphTargetsRelative = geometry.morphTargetsRelative;
  600. const normalAttribute = geometry.attributes.normal;
  601. const morphNormal = geometry.morphAttributes.position;
  602. const groups = geometry.groups;
  603. const drawRange = geometry.drawRange;
  604. let i, j, il, jl;
  605. let group;
  606. let start, end;
  607. const modifiedPosition = new Float32Array( positionAttribute.count * positionAttribute.itemSize );
  608. const modifiedNormal = new Float32Array( normalAttribute.count * normalAttribute.itemSize );
  609. if ( index !== null ) {
  610. // indexed buffer geometry
  611. if ( Array.isArray( material ) ) {
  612. for ( i = 0, il = groups.length; i < il; i ++ ) {
  613. group = groups[ i ];
  614. start = Math.max( group.start, drawRange.start );
  615. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  616. for ( j = start, jl = end; j < jl; j += 3 ) {
  617. a = index.getX( j );
  618. b = index.getX( j + 1 );
  619. c = index.getX( j + 2 );
  620. _calculateMorphedAttributeData(
  621. object,
  622. positionAttribute,
  623. morphPosition,
  624. morphTargetsRelative,
  625. a, b, c,
  626. modifiedPosition
  627. );
  628. _calculateMorphedAttributeData(
  629. object,
  630. normalAttribute,
  631. morphNormal,
  632. morphTargetsRelative,
  633. a, b, c,
  634. modifiedNormal
  635. );
  636. }
  637. }
  638. } else {
  639. start = Math.max( 0, drawRange.start );
  640. end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  641. for ( i = start, il = end; i < il; i += 3 ) {
  642. a = index.getX( i );
  643. b = index.getX( i + 1 );
  644. c = index.getX( i + 2 );
  645. _calculateMorphedAttributeData(
  646. object,
  647. positionAttribute,
  648. morphPosition,
  649. morphTargetsRelative,
  650. a, b, c,
  651. modifiedPosition
  652. );
  653. _calculateMorphedAttributeData(
  654. object,
  655. normalAttribute,
  656. morphNormal,
  657. morphTargetsRelative,
  658. a, b, c,
  659. modifiedNormal
  660. );
  661. }
  662. }
  663. } else {
  664. // non-indexed buffer geometry
  665. if ( Array.isArray( material ) ) {
  666. for ( i = 0, il = groups.length; i < il; i ++ ) {
  667. group = groups[ i ];
  668. start = Math.max( group.start, drawRange.start );
  669. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  670. for ( j = start, jl = end; j < jl; j += 3 ) {
  671. a = j;
  672. b = j + 1;
  673. c = j + 2;
  674. _calculateMorphedAttributeData(
  675. object,
  676. positionAttribute,
  677. morphPosition,
  678. morphTargetsRelative,
  679. a, b, c,
  680. modifiedPosition
  681. );
  682. _calculateMorphedAttributeData(
  683. object,
  684. normalAttribute,
  685. morphNormal,
  686. morphTargetsRelative,
  687. a, b, c,
  688. modifiedNormal
  689. );
  690. }
  691. }
  692. } else {
  693. start = Math.max( 0, drawRange.start );
  694. end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  695. for ( i = start, il = end; i < il; i += 3 ) {
  696. a = i;
  697. b = i + 1;
  698. c = i + 2;
  699. _calculateMorphedAttributeData(
  700. object,
  701. positionAttribute,
  702. morphPosition,
  703. morphTargetsRelative,
  704. a, b, c,
  705. modifiedPosition
  706. );
  707. _calculateMorphedAttributeData(
  708. object,
  709. normalAttribute,
  710. morphNormal,
  711. morphTargetsRelative,
  712. a, b, c,
  713. modifiedNormal
  714. );
  715. }
  716. }
  717. }
  718. const morphedPositionAttribute = new Float32BufferAttribute( modifiedPosition, 3 );
  719. const morphedNormalAttribute = new Float32BufferAttribute( modifiedNormal, 3 );
  720. return {
  721. positionAttribute: positionAttribute,
  722. normalAttribute: normalAttribute,
  723. morphedPositionAttribute: morphedPositionAttribute,
  724. morphedNormalAttribute: morphedNormalAttribute
  725. };
  726. }
  727. function mergeGroups( geometry ) {
  728. if ( geometry.groups.length === 0 ) {
  729. console.warn( 'THREE.BufferGeometryUtils.mergeGroups(): No groups are defined. Nothing to merge.' );
  730. return geometry;
  731. }
  732. let groups = geometry.groups;
  733. // sort groups by material index
  734. groups = groups.sort( ( a, b ) => {
  735. if ( a.materialIndex !== b.materialIndex ) return a.materialIndex - b.materialIndex;
  736. return a.start - b.start;
  737. } );
  738. // create index for non-indexed geometries
  739. if ( geometry.getIndex() === null ) {
  740. const positionAttribute = geometry.getAttribute( 'position' );
  741. const indices = [];
  742. for ( let i = 0; i < positionAttribute.count; i += 3 ) {
  743. indices.push( i, i + 1, i + 2 );
  744. }
  745. geometry.setIndex( indices );
  746. }
  747. // sort index
  748. const index = geometry.getIndex();
  749. const newIndices = [];
  750. for ( let i = 0; i < groups.length; i ++ ) {
  751. const group = groups[ i ];
  752. const groupStart = group.start;
  753. const groupLength = groupStart + group.count;
  754. for ( let j = groupStart; j < groupLength; j ++ ) {
  755. newIndices.push( index.getX( j ) );
  756. }
  757. }
  758. geometry.dispose(); // Required to force buffer recreation
  759. geometry.setIndex( newIndices );
  760. // update groups indices
  761. let start = 0;
  762. for ( let i = 0; i < groups.length; i ++ ) {
  763. const group = groups[ i ];
  764. group.start = start;
  765. start += group.count;
  766. }
  767. // merge groups
  768. let currentGroup = groups[ 0 ];
  769. geometry.groups = [ currentGroup ];
  770. for ( let i = 1; i < groups.length; i ++ ) {
  771. const group = groups[ i ];
  772. if ( currentGroup.materialIndex === group.materialIndex ) {
  773. currentGroup.count += group.count;
  774. } else {
  775. currentGroup = group;
  776. geometry.groups.push( currentGroup );
  777. }
  778. }
  779. return geometry;
  780. }
  781. /**
  782. * Modifies the supplied geometry if it is non-indexed, otherwise creates a new,
  783. * non-indexed geometry. Returns the geometry with smooth normals everywhere except
  784. * faces that meet at an angle greater than the crease angle.
  785. *
  786. * @param {BufferGeometry} geometry
  787. * @param {number} [creaseAngle]
  788. * @return {BufferGeometry}
  789. */
  790. function toCreasedNormals( geometry, creaseAngle = Math.PI / 3 /* 60 degrees */ ) {
  791. const creaseDot = Math.cos( creaseAngle );
  792. const hashMultiplier = ( 1 + 1e-10 ) * 1e2;
  793. // reusable vectors
  794. const verts = [ new Vector3(), new Vector3(), new Vector3() ];
  795. const tempVec1 = new Vector3();
  796. const tempVec2 = new Vector3();
  797. const tempNorm = new Vector3();
  798. const tempNorm2 = new Vector3();
  799. // hashes a vector
  800. function hashVertex( v ) {
  801. const x = ~ ~ ( v.x * hashMultiplier );
  802. const y = ~ ~ ( v.y * hashMultiplier );
  803. const z = ~ ~ ( v.z * hashMultiplier );
  804. return `${x},${y},${z}`;
  805. }
  806. // BufferGeometry.toNonIndexed() warns if the geometry is non-indexed
  807. // and returns the original geometry
  808. const resultGeometry = geometry.index ? geometry.toNonIndexed() : geometry;
  809. const posAttr = resultGeometry.attributes.position;
  810. const vertexMap = {};
  811. // find all the normals shared by commonly located vertices
  812. for ( let i = 0, l = posAttr.count / 3; i < l; i ++ ) {
  813. const i3 = 3 * i;
  814. const a = verts[ 0 ].fromBufferAttribute( posAttr, i3 + 0 );
  815. const b = verts[ 1 ].fromBufferAttribute( posAttr, i3 + 1 );
  816. const c = verts[ 2 ].fromBufferAttribute( posAttr, i3 + 2 );
  817. tempVec1.subVectors( c, b );
  818. tempVec2.subVectors( a, b );
  819. // add the normal to the map for all vertices
  820. const normal = new Vector3().crossVectors( tempVec1, tempVec2 ).normalize();
  821. for ( let n = 0; n < 3; n ++ ) {
  822. const vert = verts[ n ];
  823. const hash = hashVertex( vert );
  824. if ( ! ( hash in vertexMap ) ) {
  825. vertexMap[ hash ] = [];
  826. }
  827. vertexMap[ hash ].push( normal );
  828. }
  829. }
  830. // average normals from all vertices that share a common location if they are within the
  831. // provided crease threshold
  832. const normalArray = new Float32Array( posAttr.count * 3 );
  833. const normAttr = new BufferAttribute( normalArray, 3, false );
  834. for ( let i = 0, l = posAttr.count / 3; i < l; i ++ ) {
  835. // get the face normal for this vertex
  836. const i3 = 3 * i;
  837. const a = verts[ 0 ].fromBufferAttribute( posAttr, i3 + 0 );
  838. const b = verts[ 1 ].fromBufferAttribute( posAttr, i3 + 1 );
  839. const c = verts[ 2 ].fromBufferAttribute( posAttr, i3 + 2 );
  840. tempVec1.subVectors( c, b );
  841. tempVec2.subVectors( a, b );
  842. tempNorm.crossVectors( tempVec1, tempVec2 ).normalize();
  843. // average all normals that meet the threshold and set the normal value
  844. for ( let n = 0; n < 3; n ++ ) {
  845. const vert = verts[ n ];
  846. const hash = hashVertex( vert );
  847. const otherNormals = vertexMap[ hash ];
  848. tempNorm2.set( 0, 0, 0 );
  849. for ( let k = 0, lk = otherNormals.length; k < lk; k ++ ) {
  850. const otherNorm = otherNormals[ k ];
  851. if ( tempNorm.dot( otherNorm ) > creaseDot ) {
  852. tempNorm2.add( otherNorm );
  853. }
  854. }
  855. tempNorm2.normalize();
  856. normAttr.setXYZ( i3 + n, tempNorm2.x, tempNorm2.y, tempNorm2.z );
  857. }
  858. }
  859. resultGeometry.setAttribute( 'normal', normAttr );
  860. return resultGeometry;
  861. }
  862. export {
  863. computeMikkTSpaceTangents,
  864. mergeGeometries,
  865. mergeAttributes,
  866. interleaveAttributes,
  867. estimateBytesUsed,
  868. mergeVertices,
  869. toTrianglesDrawMode,
  870. computeMorphedAttributes,
  871. mergeGroups,
  872. toCreasedNormals
  873. };