BufferGeometryUtils.js 31 KB

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