BufferGeometryUtils.js 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  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() {
  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 {Array<BufferAttribute>} attributes
  211. * @return {Array<InterleavedBufferAttribute>}
  212. */
  213. function interleaveAttributes( attributes ) {
  214. // Interleaves the provided attributes into an InterleavedBuffer and returns
  215. // a set of InterleavedBufferAttributes for each attribute
  216. let TypedArray;
  217. let arrayLength = 0;
  218. let stride = 0;
  219. // calculate the length and type of the interleavedBuffer
  220. for ( let i = 0, l = attributes.length; i < l; ++ i ) {
  221. const attribute = attributes[ i ];
  222. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  223. if ( TypedArray !== attribute.array.constructor ) {
  224. console.error( 'AttributeBuffers of different types cannot be interleaved' );
  225. return null;
  226. }
  227. arrayLength += attribute.array.length;
  228. stride += attribute.itemSize;
  229. }
  230. // Create the set of buffer attributes
  231. const interleavedBuffer = new InterleavedBuffer( new TypedArray( arrayLength ), stride );
  232. let offset = 0;
  233. const res = [];
  234. const getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  235. const setters = [ 'setX', 'setY', 'setZ', 'setW' ];
  236. for ( let j = 0, l = attributes.length; j < l; j ++ ) {
  237. const attribute = attributes[ j ];
  238. const itemSize = attribute.itemSize;
  239. const count = attribute.count;
  240. const iba = new InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
  241. res.push( iba );
  242. offset += itemSize;
  243. // Move the data for each attribute into the new interleavedBuffer
  244. // at the appropriate offset
  245. for ( let c = 0; c < count; c ++ ) {
  246. for ( let k = 0; k < itemSize; k ++ ) {
  247. iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
  248. }
  249. }
  250. }
  251. return res;
  252. }
  253. // returns a new, non-interleaved version of the provided attribute
  254. export function deinterleaveAttribute( attribute ) {
  255. const cons = attribute.data.array.constructor;
  256. const count = attribute.count;
  257. const itemSize = attribute.itemSize;
  258. const normalized = attribute.normalized;
  259. const array = new cons( count * itemSize );
  260. let newAttribute;
  261. if ( attribute.isInstancedInterleavedBufferAttribute ) {
  262. newAttribute = new InstancedBufferAttribute( array, itemSize, normalized, attribute.meshPerAttribute );
  263. } else {
  264. newAttribute = new BufferAttribute( array, itemSize, normalized );
  265. }
  266. for ( let i = 0; i < count; i ++ ) {
  267. newAttribute.setX( i, attribute.getX( i ) );
  268. if ( itemSize >= 2 ) {
  269. newAttribute.setY( i, attribute.getY( i ) );
  270. }
  271. if ( itemSize >= 3 ) {
  272. newAttribute.setZ( i, attribute.getZ( i ) );
  273. }
  274. if ( itemSize >= 4 ) {
  275. newAttribute.setW( i, attribute.getW( i ) );
  276. }
  277. }
  278. return newAttribute;
  279. }
  280. // deinterleaves all attributes on the geometry
  281. export function deinterleaveGeometry( geometry ) {
  282. const attributes = geometry.attributes;
  283. const morphTargets = geometry.morphTargets;
  284. const attrMap = new Map();
  285. for ( const key in attributes ) {
  286. const attr = attributes[ key ];
  287. if ( attr.isInterleavedBufferAttribute ) {
  288. if ( ! attrMap.has( attr ) ) {
  289. attrMap.set( attr, deinterleaveAttribute( attr ) );
  290. }
  291. attributes[ key ] = attrMap.get( attr );
  292. }
  293. }
  294. for ( const key in morphTargets ) {
  295. const attr = morphTargets[ key ];
  296. if ( attr.isInterleavedBufferAttribute ) {
  297. if ( ! attrMap.has( attr ) ) {
  298. attrMap.set( attr, deinterleaveAttribute( attr ) );
  299. }
  300. morphTargets[ key ] = attrMap.get( attr );
  301. }
  302. }
  303. }
  304. /**
  305. * @param {Array<BufferGeometry>} geometry
  306. * @return {number}
  307. */
  308. function estimateBytesUsed( geometry ) {
  309. // Return the estimated memory used by this geometry in bytes
  310. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  311. // for InterleavedBufferAttributes.
  312. let mem = 0;
  313. for ( const name in geometry.attributes ) {
  314. const attr = geometry.getAttribute( name );
  315. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  316. }
  317. const indices = geometry.getIndex();
  318. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  319. return mem;
  320. }
  321. /**
  322. * @param {BufferGeometry} geometry
  323. * @param {number} tolerance
  324. * @return {BufferGeometry}
  325. */
  326. function mergeVertices( geometry, tolerance = 1e-4 ) {
  327. tolerance = Math.max( tolerance, Number.EPSILON );
  328. // Generate an index buffer if the geometry doesn't have one, or optimize it
  329. // if it's already available.
  330. const hashToIndex = {};
  331. const indices = geometry.getIndex();
  332. const positions = geometry.getAttribute( 'position' );
  333. const vertexCount = indices ? indices.count : positions.count;
  334. // next value for triangle indices
  335. let nextIndex = 0;
  336. // attributes and new attribute arrays
  337. const attributeNames = Object.keys( geometry.attributes );
  338. const tmpAttributes = {};
  339. const tmpMorphAttributes = {};
  340. const newIndices = [];
  341. const getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  342. const setters = [ 'setX', 'setY', 'setZ', 'setW' ];
  343. // Initialize the arrays, allocating space conservatively. Extra
  344. // space will be trimmed in the last step.
  345. for ( let i = 0, l = attributeNames.length; i < l; i ++ ) {
  346. const name = attributeNames[ i ];
  347. const attr = geometry.attributes[ name ];
  348. tmpAttributes[ name ] = new BufferAttribute(
  349. new attr.array.constructor( attr.count * attr.itemSize ),
  350. attr.itemSize,
  351. attr.normalized
  352. );
  353. const morphAttr = geometry.morphAttributes[ name ];
  354. if ( morphAttr ) {
  355. tmpMorphAttributes[ name ] = new BufferAttribute(
  356. new morphAttr.array.constructor( morphAttr.count * morphAttr.itemSize ),
  357. morphAttr.itemSize,
  358. morphAttr.normalized
  359. );
  360. }
  361. }
  362. // convert the error tolerance to an amount of decimal places to truncate to
  363. const decimalShift = Math.log10( 1 / tolerance );
  364. const shiftMultiplier = Math.pow( 10, decimalShift );
  365. for ( let i = 0; i < vertexCount; i ++ ) {
  366. const index = indices ? indices.getX( i ) : i;
  367. // Generate a hash for the vertex attributes at the current index 'i'
  368. let hash = '';
  369. for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
  370. const name = attributeNames[ j ];
  371. const attribute = geometry.getAttribute( name );
  372. const itemSize = attribute.itemSize;
  373. for ( let k = 0; k < itemSize; k ++ ) {
  374. // double tilde truncates the decimal value
  375. hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * shiftMultiplier ) },`;
  376. }
  377. }
  378. // Add another reference to the vertex if it's already
  379. // used by another index
  380. if ( hash in hashToIndex ) {
  381. newIndices.push( hashToIndex[ hash ] );
  382. } else {
  383. // copy data to the new index in the temporary attributes
  384. for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
  385. const name = attributeNames[ j ];
  386. const attribute = geometry.getAttribute( name );
  387. const morphAttr = geometry.morphAttributes[ name ];
  388. const itemSize = attribute.itemSize;
  389. const newarray = tmpAttributes[ name ];
  390. const newMorphArrays = tmpMorphAttributes[ name ];
  391. for ( let k = 0; k < itemSize; k ++ ) {
  392. const getterFunc = getters[ k ];
  393. const setterFunc = setters[ k ];
  394. newarray[ setterFunc ]( nextIndex, attribute[ getterFunc ]( index ) );
  395. if ( morphAttr ) {
  396. for ( let m = 0, ml = morphAttr.length; m < ml; m ++ ) {
  397. newMorphArrays[ m ][ setterFunc ]( nextIndex, morphAttr[ m ][ getterFunc ]( index ) );
  398. }
  399. }
  400. }
  401. }
  402. hashToIndex[ hash ] = nextIndex;
  403. newIndices.push( nextIndex );
  404. nextIndex ++;
  405. }
  406. }
  407. // generate result BufferGeometry
  408. const result = geometry.clone();
  409. for ( const name in geometry.attributes ) {
  410. const tmpAttribute = tmpAttributes[ name ];
  411. result.setAttribute( name, new BufferAttribute(
  412. tmpAttribute.array.slice( 0, nextIndex * tmpAttribute.itemSize ),
  413. tmpAttribute.itemSize,
  414. tmpAttribute.normalized,
  415. ) );
  416. if ( ! ( name in tmpMorphAttributes ) ) continue;
  417. for ( let j = 0; j < tmpMorphAttributes[ name ].length; j ++ ) {
  418. const tmpMorphAttribute = tmpMorphAttributes[ name ][ j ];
  419. result.morphAttributes[ name ][ j ] = new BufferAttribute(
  420. tmpMorphAttribute.array.slice( 0, nextIndex * tmpMorphAttribute.itemSize ),
  421. tmpMorphAttribute.itemSize,
  422. tmpMorphAttribute.normalized,
  423. );
  424. }
  425. }
  426. // indices
  427. result.setIndex( newIndices );
  428. return result;
  429. }
  430. /**
  431. * @param {BufferGeometry} geometry
  432. * @param {number} drawMode
  433. * @return {BufferGeometry}
  434. */
  435. function toTrianglesDrawMode( geometry, drawMode ) {
  436. if ( drawMode === TrianglesDrawMode ) {
  437. console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' );
  438. return geometry;
  439. }
  440. if ( drawMode === TriangleFanDrawMode || drawMode === TriangleStripDrawMode ) {
  441. let index = geometry.getIndex();
  442. // generate index if not present
  443. if ( index === null ) {
  444. const indices = [];
  445. const position = geometry.getAttribute( 'position' );
  446. if ( position !== undefined ) {
  447. for ( let i = 0; i < position.count; i ++ ) {
  448. indices.push( i );
  449. }
  450. geometry.setIndex( indices );
  451. index = geometry.getIndex();
  452. } else {
  453. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  454. return geometry;
  455. }
  456. }
  457. //
  458. const numberOfTriangles = index.count - 2;
  459. const newIndices = [];
  460. if ( drawMode === TriangleFanDrawMode ) {
  461. // gl.TRIANGLE_FAN
  462. for ( let i = 1; i <= numberOfTriangles; i ++ ) {
  463. newIndices.push( index.getX( 0 ) );
  464. newIndices.push( index.getX( i ) );
  465. newIndices.push( index.getX( i + 1 ) );
  466. }
  467. } else {
  468. // gl.TRIANGLE_STRIP
  469. for ( let i = 0; i < numberOfTriangles; i ++ ) {
  470. if ( i % 2 === 0 ) {
  471. newIndices.push( index.getX( i ) );
  472. newIndices.push( index.getX( i + 1 ) );
  473. newIndices.push( index.getX( i + 2 ) );
  474. } else {
  475. newIndices.push( index.getX( i + 2 ) );
  476. newIndices.push( index.getX( i + 1 ) );
  477. newIndices.push( index.getX( i ) );
  478. }
  479. }
  480. }
  481. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  482. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  483. }
  484. // build final geometry
  485. const newGeometry = geometry.clone();
  486. newGeometry.setIndex( newIndices );
  487. newGeometry.clearGroups();
  488. return newGeometry;
  489. } else {
  490. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode );
  491. return geometry;
  492. }
  493. }
  494. /**
  495. * Calculates the morphed attributes of a morphed/skinned BufferGeometry.
  496. * Helpful for Raytracing or Decals.
  497. * @param {Mesh | Line | Points} object An instance of Mesh, Line or Points.
  498. * @return {Object} An Object with original position/normal attributes and morphed ones.
  499. */
  500. function computeMorphedAttributes( object ) {
  501. if ( object.geometry.isBufferGeometry !== true ) {
  502. console.error( 'THREE.BufferGeometryUtils: Geometry is not of type BufferGeometry.' );
  503. return null;
  504. }
  505. const _vA = new Vector3();
  506. const _vB = new Vector3();
  507. const _vC = new Vector3();
  508. const _tempA = new Vector3();
  509. const _tempB = new Vector3();
  510. const _tempC = new Vector3();
  511. const _morphA = new Vector3();
  512. const _morphB = new Vector3();
  513. const _morphC = new Vector3();
  514. function _calculateMorphedAttributeData(
  515. object,
  516. attribute,
  517. morphAttribute,
  518. morphTargetsRelative,
  519. a,
  520. b,
  521. c,
  522. modifiedAttributeArray
  523. ) {
  524. _vA.fromBufferAttribute( attribute, a );
  525. _vB.fromBufferAttribute( attribute, b );
  526. _vC.fromBufferAttribute( attribute, c );
  527. const morphInfluences = object.morphTargetInfluences;
  528. if ( morphAttribute && morphInfluences ) {
  529. _morphA.set( 0, 0, 0 );
  530. _morphB.set( 0, 0, 0 );
  531. _morphC.set( 0, 0, 0 );
  532. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  533. const influence = morphInfluences[ i ];
  534. const morph = morphAttribute[ i ];
  535. if ( influence === 0 ) continue;
  536. _tempA.fromBufferAttribute( morph, a );
  537. _tempB.fromBufferAttribute( morph, b );
  538. _tempC.fromBufferAttribute( morph, c );
  539. if ( morphTargetsRelative ) {
  540. _morphA.addScaledVector( _tempA, influence );
  541. _morphB.addScaledVector( _tempB, influence );
  542. _morphC.addScaledVector( _tempC, influence );
  543. } else {
  544. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  545. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  546. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  547. }
  548. }
  549. _vA.add( _morphA );
  550. _vB.add( _morphB );
  551. _vC.add( _morphC );
  552. }
  553. if ( object.isSkinnedMesh ) {
  554. object.boneTransform( a, _vA );
  555. object.boneTransform( b, _vB );
  556. object.boneTransform( c, _vC );
  557. }
  558. modifiedAttributeArray[ a * 3 + 0 ] = _vA.x;
  559. modifiedAttributeArray[ a * 3 + 1 ] = _vA.y;
  560. modifiedAttributeArray[ a * 3 + 2 ] = _vA.z;
  561. modifiedAttributeArray[ b * 3 + 0 ] = _vB.x;
  562. modifiedAttributeArray[ b * 3 + 1 ] = _vB.y;
  563. modifiedAttributeArray[ b * 3 + 2 ] = _vB.z;
  564. modifiedAttributeArray[ c * 3 + 0 ] = _vC.x;
  565. modifiedAttributeArray[ c * 3 + 1 ] = _vC.y;
  566. modifiedAttributeArray[ c * 3 + 2 ] = _vC.z;
  567. }
  568. const geometry = object.geometry;
  569. const material = object.material;
  570. let a, b, c;
  571. const index = geometry.index;
  572. const positionAttribute = geometry.attributes.position;
  573. const morphPosition = geometry.morphAttributes.position;
  574. const morphTargetsRelative = geometry.morphTargetsRelative;
  575. const normalAttribute = geometry.attributes.normal;
  576. const morphNormal = geometry.morphAttributes.position;
  577. const groups = geometry.groups;
  578. const drawRange = geometry.drawRange;
  579. let i, j, il, jl;
  580. let group;
  581. let start, end;
  582. const modifiedPosition = new Float32Array( positionAttribute.count * positionAttribute.itemSize );
  583. const modifiedNormal = new Float32Array( normalAttribute.count * normalAttribute.itemSize );
  584. if ( index !== null ) {
  585. // indexed buffer geometry
  586. if ( Array.isArray( material ) ) {
  587. for ( i = 0, il = groups.length; i < il; i ++ ) {
  588. group = groups[ i ];
  589. start = Math.max( group.start, drawRange.start );
  590. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  591. for ( j = start, jl = end; j < jl; j += 3 ) {
  592. a = index.getX( j );
  593. b = index.getX( j + 1 );
  594. c = index.getX( j + 2 );
  595. _calculateMorphedAttributeData(
  596. object,
  597. positionAttribute,
  598. morphPosition,
  599. morphTargetsRelative,
  600. a, b, c,
  601. modifiedPosition
  602. );
  603. _calculateMorphedAttributeData(
  604. object,
  605. normalAttribute,
  606. morphNormal,
  607. morphTargetsRelative,
  608. a, b, c,
  609. modifiedNormal
  610. );
  611. }
  612. }
  613. } else {
  614. start = Math.max( 0, drawRange.start );
  615. end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  616. for ( i = start, il = end; i < il; i += 3 ) {
  617. a = index.getX( i );
  618. b = index.getX( i + 1 );
  619. c = index.getX( i + 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. // non-indexed buffer geometry
  640. if ( Array.isArray( material ) ) {
  641. for ( i = 0, il = groups.length; i < il; i ++ ) {
  642. group = groups[ i ];
  643. start = Math.max( group.start, drawRange.start );
  644. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  645. for ( j = start, jl = end; j < jl; j += 3 ) {
  646. a = j;
  647. b = j + 1;
  648. c = j + 2;
  649. _calculateMorphedAttributeData(
  650. object,
  651. positionAttribute,
  652. morphPosition,
  653. morphTargetsRelative,
  654. a, b, c,
  655. modifiedPosition
  656. );
  657. _calculateMorphedAttributeData(
  658. object,
  659. normalAttribute,
  660. morphNormal,
  661. morphTargetsRelative,
  662. a, b, c,
  663. modifiedNormal
  664. );
  665. }
  666. }
  667. } else {
  668. start = Math.max( 0, drawRange.start );
  669. end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  670. for ( i = start, il = end; i < il; i += 3 ) {
  671. a = i;
  672. b = i + 1;
  673. c = i + 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. }
  693. const morphedPositionAttribute = new Float32BufferAttribute( modifiedPosition, 3 );
  694. const morphedNormalAttribute = new Float32BufferAttribute( modifiedNormal, 3 );
  695. return {
  696. positionAttribute: positionAttribute,
  697. normalAttribute: normalAttribute,
  698. morphedPositionAttribute: morphedPositionAttribute,
  699. morphedNormalAttribute: morphedNormalAttribute
  700. };
  701. }
  702. function mergeGroups( geometry ) {
  703. if ( geometry.groups.length === 0 ) {
  704. console.warn( 'THREE.BufferGeometryUtils.mergeGroups(): No groups are defined. Nothing to merge.' );
  705. return geometry;
  706. }
  707. let groups = geometry.groups;
  708. // sort groups by material index
  709. groups = groups.sort( ( a, b ) => {
  710. if ( a.materialIndex !== b.materialIndex ) return a.materialIndex - b.materialIndex;
  711. return a.start - b.start;
  712. } );
  713. // create index for non-indexed geometries
  714. if ( geometry.getIndex() === null ) {
  715. const positionAttribute = geometry.getAttribute( 'position' );
  716. const indices = [];
  717. for ( let i = 0; i < positionAttribute.count; i += 3 ) {
  718. indices.push( i, i + 1, i + 2 );
  719. }
  720. geometry.setIndex( indices );
  721. }
  722. // sort index
  723. const index = geometry.getIndex();
  724. const newIndices = [];
  725. for ( let i = 0; i < groups.length; i ++ ) {
  726. const group = groups[ i ];
  727. const groupStart = group.start;
  728. const groupLength = groupStart + group.count;
  729. for ( let j = groupStart; j < groupLength; j ++ ) {
  730. newIndices.push( index.getX( j ) );
  731. }
  732. }
  733. geometry.dispose(); // Required to force buffer recreation
  734. geometry.setIndex( newIndices );
  735. // update groups indices
  736. let start = 0;
  737. for ( let i = 0; i < groups.length; i ++ ) {
  738. const group = groups[ i ];
  739. group.start = start;
  740. start += group.count;
  741. }
  742. // merge groups
  743. let currentGroup = groups[ 0 ];
  744. geometry.groups = [ currentGroup ];
  745. for ( let i = 1; i < groups.length; i ++ ) {
  746. const group = groups[ i ];
  747. if ( currentGroup.materialIndex === group.materialIndex ) {
  748. currentGroup.count += group.count;
  749. } else {
  750. currentGroup = group;
  751. geometry.groups.push( currentGroup );
  752. }
  753. }
  754. return geometry;
  755. }
  756. export {
  757. computeTangents,
  758. computeMikkTSpaceTangents,
  759. mergeBufferGeometries,
  760. mergeBufferAttributes,
  761. interleaveAttributes,
  762. estimateBytesUsed,
  763. mergeVertices,
  764. toTrianglesDrawMode,
  765. computeMorphedAttributes,
  766. mergeGroups
  767. };