BufferGeometryUtils.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. import {
  5. BufferAttribute,
  6. BufferGeometry,
  7. InterleavedBuffer,
  8. InterleavedBufferAttribute,
  9. TriangleFanDrawMode,
  10. TriangleStripDrawMode,
  11. TrianglesDrawMode,
  12. Vector2,
  13. Vector3
  14. } from "../../../build/three.module.js";
  15. var BufferGeometryUtils = {
  16. computeTangents: function ( geometry ) {
  17. var index = geometry.index;
  18. var attributes = geometry.attributes;
  19. // based on http://www.terathon.com/code/tangent.html
  20. // (per vertex tangents)
  21. if ( index === null ||
  22. attributes.position === undefined ||
  23. attributes.normal === undefined ||
  24. attributes.uv === undefined ) {
  25. console.warn( 'THREE.BufferGeometry: Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()' );
  26. return;
  27. }
  28. var indices = index.array;
  29. var positions = attributes.position.array;
  30. var normals = attributes.normal.array;
  31. var uvs = attributes.uv.array;
  32. var nVertices = positions.length / 3;
  33. if ( attributes.tangent === undefined ) {
  34. geometry.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  35. }
  36. var tangents = attributes.tangent.array;
  37. var tan1 = [], tan2 = [];
  38. for ( var i = 0; i < nVertices; i ++ ) {
  39. tan1[ i ] = new Vector3();
  40. tan2[ i ] = new Vector3();
  41. }
  42. var vA = new Vector3(),
  43. vB = new Vector3(),
  44. vC = new Vector3(),
  45. uvA = new Vector2(),
  46. uvB = new Vector2(),
  47. uvC = new Vector2(),
  48. sdir = new Vector3(),
  49. tdir = new Vector3();
  50. function handleTriangle( a, b, c ) {
  51. vA.fromArray( positions, a * 3 );
  52. vB.fromArray( positions, b * 3 );
  53. vC.fromArray( positions, c * 3 );
  54. uvA.fromArray( uvs, a * 2 );
  55. uvB.fromArray( uvs, b * 2 );
  56. uvC.fromArray( uvs, c * 2 );
  57. vB.sub( vA );
  58. vC.sub( vA );
  59. uvB.sub( uvA );
  60. uvC.sub( uvA );
  61. var r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  62. // silently ignore degenerate uv triangles having coincident or colinear vertices
  63. if ( ! isFinite( r ) ) return;
  64. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  65. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  66. tan1[ a ].add( sdir );
  67. tan1[ b ].add( sdir );
  68. tan1[ c ].add( sdir );
  69. tan2[ a ].add( tdir );
  70. tan2[ b ].add( tdir );
  71. tan2[ c ].add( tdir );
  72. }
  73. var groups = geometry.groups;
  74. if ( groups.length === 0 ) {
  75. groups = [ {
  76. start: 0,
  77. count: indices.length
  78. } ];
  79. }
  80. for ( var i = 0, il = groups.length; i < il; ++ i ) {
  81. var group = groups[ i ];
  82. var start = group.start;
  83. var count = group.count;
  84. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  85. handleTriangle(
  86. indices[ j + 0 ],
  87. indices[ j + 1 ],
  88. indices[ j + 2 ]
  89. );
  90. }
  91. }
  92. var tmp = new Vector3(), tmp2 = new Vector3();
  93. var n = new Vector3(), n2 = new Vector3();
  94. var w, t, test;
  95. function handleVertex( v ) {
  96. n.fromArray( normals, v * 3 );
  97. n2.copy( n );
  98. t = tan1[ v ];
  99. // Gram-Schmidt orthogonalize
  100. tmp.copy( t );
  101. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  102. // Calculate handedness
  103. tmp2.crossVectors( n2, t );
  104. test = tmp2.dot( tan2[ v ] );
  105. w = ( test < 0.0 ) ? - 1.0 : 1.0;
  106. tangents[ v * 4 ] = tmp.x;
  107. tangents[ v * 4 + 1 ] = tmp.y;
  108. tangents[ v * 4 + 2 ] = tmp.z;
  109. tangents[ v * 4 + 3 ] = w;
  110. }
  111. for ( var i = 0, il = groups.length; i < il; ++ i ) {
  112. var group = groups[ i ];
  113. var start = group.start;
  114. var count = group.count;
  115. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  116. handleVertex( indices[ j + 0 ] );
  117. handleVertex( indices[ j + 1 ] );
  118. handleVertex( indices[ j + 2 ] );
  119. }
  120. }
  121. },
  122. /**
  123. * @param {Array<BufferGeometry>} geometries
  124. * @param {Boolean} useGroups
  125. * @return {BufferGeometry}
  126. */
  127. mergeBufferGeometries: function ( geometries, useGroups ) {
  128. var isIndexed = geometries[ 0 ].index !== null;
  129. var attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) );
  130. var morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) );
  131. var attributes = {};
  132. var morphAttributes = {};
  133. var morphTargetsRelative = geometries[ 0 ].morphTargetsRelative;
  134. var mergedGeometry = new BufferGeometry();
  135. var offset = 0;
  136. for ( var i = 0; i < geometries.length; ++ i ) {
  137. var geometry = geometries[ i ];
  138. // ensure that all geometries are indexed, or none
  139. if ( isIndexed !== ( geometry.index !== null ) ) return null;
  140. // gather attributes, exit early if they're different
  141. for ( var name in geometry.attributes ) {
  142. if ( ! attributesUsed.has( name ) ) return null;
  143. if ( attributes[ name ] === undefined ) attributes[ name ] = [];
  144. attributes[ name ].push( geometry.attributes[ name ] );
  145. }
  146. // gather morph attributes, exit early if they're different
  147. if ( morphTargetsRelative !== geometry.morphTargetsRelative ) return null;
  148. for ( var name in geometry.morphAttributes ) {
  149. if ( ! morphAttributesUsed.has( name ) ) return null;
  150. if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = [];
  151. morphAttributes[ name ].push( geometry.morphAttributes[ name ] );
  152. }
  153. // gather .userData
  154. mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || [];
  155. mergedGeometry.userData.mergedUserData.push( geometry.userData );
  156. if ( useGroups ) {
  157. var count;
  158. if ( isIndexed ) {
  159. count = geometry.index.count;
  160. } else if ( geometry.attributes.position !== undefined ) {
  161. count = geometry.attributes.position.count;
  162. } else {
  163. return null;
  164. }
  165. mergedGeometry.addGroup( offset, count, i );
  166. offset += count;
  167. }
  168. }
  169. // merge indices
  170. if ( isIndexed ) {
  171. var indexOffset = 0;
  172. var mergedIndex = [];
  173. for ( var i = 0; i < geometries.length; ++ i ) {
  174. var index = geometries[ i ].index;
  175. for ( var j = 0; j < index.count; ++ j ) {
  176. mergedIndex.push( index.getX( j ) + indexOffset );
  177. }
  178. indexOffset += geometries[ i ].attributes.position.count;
  179. }
  180. mergedGeometry.setIndex( mergedIndex );
  181. }
  182. // merge attributes
  183. for ( var name in attributes ) {
  184. var mergedAttribute = this.mergeBufferAttributes( attributes[ name ] );
  185. if ( ! mergedAttribute ) return null;
  186. mergedGeometry.setAttribute( name, mergedAttribute );
  187. }
  188. // merge morph attributes
  189. for ( var name in morphAttributes ) {
  190. var numMorphTargets = morphAttributes[ name ][ 0 ].length;
  191. if ( numMorphTargets === 0 ) break;
  192. mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
  193. mergedGeometry.morphAttributes[ name ] = [];
  194. for ( var i = 0; i < numMorphTargets; ++ i ) {
  195. var morphAttributesToMerge = [];
  196. for ( var j = 0; j < morphAttributes[ name ].length; ++ j ) {
  197. morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] );
  198. }
  199. var mergedMorphAttribute = this.mergeBufferAttributes( morphAttributesToMerge );
  200. if ( ! mergedMorphAttribute ) return null;
  201. mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute );
  202. }
  203. }
  204. return mergedGeometry;
  205. },
  206. /**
  207. * @param {Array<BufferAttribute>} attributes
  208. * @return {BufferAttribute}
  209. */
  210. mergeBufferAttributes: function ( attributes ) {
  211. var TypedArray;
  212. var itemSize;
  213. var normalized;
  214. var arrayLength = 0;
  215. for ( var i = 0; i < attributes.length; ++ i ) {
  216. var attribute = attributes[ i ];
  217. if ( attribute.isInterleavedBufferAttribute ) return null;
  218. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  219. if ( TypedArray !== attribute.array.constructor ) return null;
  220. if ( itemSize === undefined ) itemSize = attribute.itemSize;
  221. if ( itemSize !== attribute.itemSize ) return null;
  222. if ( normalized === undefined ) normalized = attribute.normalized;
  223. if ( normalized !== attribute.normalized ) return null;
  224. arrayLength += attribute.array.length;
  225. }
  226. var array = new TypedArray( arrayLength );
  227. var offset = 0;
  228. for ( var i = 0; i < attributes.length; ++ i ) {
  229. array.set( attributes[ i ].array, offset );
  230. offset += attributes[ i ].array.length;
  231. }
  232. return new BufferAttribute( array, itemSize, normalized );
  233. },
  234. /**
  235. * @param {Array<BufferAttribute>} attributes
  236. * @return {Array<InterleavedBufferAttribute>}
  237. */
  238. interleaveAttributes: function ( attributes ) {
  239. // Interleaves the provided attributes into an InterleavedBuffer and returns
  240. // a set of InterleavedBufferAttributes for each attribute
  241. var TypedArray;
  242. var arrayLength = 0;
  243. var stride = 0;
  244. // calculate the the length and type of the interleavedBuffer
  245. for ( var i = 0, l = attributes.length; i < l; ++ i ) {
  246. var attribute = attributes[ i ];
  247. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  248. if ( TypedArray !== attribute.array.constructor ) {
  249. console.warn( 'AttributeBuffers of different types cannot be interleaved' );
  250. return null;
  251. }
  252. arrayLength += attribute.array.length;
  253. stride += attribute.itemSize;
  254. }
  255. // Create the set of buffer attributes
  256. var interleavedBuffer = new InterleavedBuffer( new TypedArray( arrayLength ), stride );
  257. var offset = 0;
  258. var res = [];
  259. var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  260. var setters = [ 'setX', 'setY', 'setZ', 'setW' ];
  261. for ( var j = 0, l = attributes.length; j < l; j ++ ) {
  262. var attribute = attributes[ j ];
  263. var itemSize = attribute.itemSize;
  264. var count = attribute.count;
  265. var iba = new InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
  266. res.push( iba );
  267. offset += itemSize;
  268. // Move the data for each attribute into the new interleavedBuffer
  269. // at the appropriate offset
  270. for ( var c = 0; c < count; c ++ ) {
  271. for ( var k = 0; k < itemSize; k ++ ) {
  272. iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
  273. }
  274. }
  275. }
  276. return res;
  277. },
  278. /**
  279. * @param {Array<BufferGeometry>} geometry
  280. * @return {number}
  281. */
  282. estimateBytesUsed: function ( geometry ) {
  283. // Return the estimated memory used by this geometry in bytes
  284. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  285. // for InterleavedBufferAttributes.
  286. var mem = 0;
  287. for ( var name in geometry.attributes ) {
  288. var attr = geometry.getAttribute( name );
  289. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  290. }
  291. var indices = geometry.getIndex();
  292. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  293. return mem;
  294. },
  295. /**
  296. * @param {BufferGeometry} geometry
  297. * @param {number} tolerance
  298. * @return {BufferGeometry>}
  299. */
  300. mergeVertices: function ( geometry, tolerance = 1e-4 ) {
  301. tolerance = Math.max( tolerance, Number.EPSILON );
  302. // Generate an index buffer if the geometry doesn't have one, or optimize it
  303. // if it's already available.
  304. var hashToIndex = {};
  305. var indices = geometry.getIndex();
  306. var positions = geometry.getAttribute( 'position' );
  307. var vertexCount = indices ? indices.count : positions.count;
  308. // next value for triangle indices
  309. var nextIndex = 0;
  310. // attributes and new attribute arrays
  311. var attributeNames = Object.keys( geometry.attributes );
  312. var attrArrays = {};
  313. var morphAttrsArrays = {};
  314. var newIndices = [];
  315. var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  316. // initialize the arrays
  317. for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
  318. var name = attributeNames[ i ];
  319. attrArrays[ name ] = [];
  320. var morphAttr = geometry.morphAttributes[ name ];
  321. if ( morphAttr ) {
  322. morphAttrsArrays[ name ] = new Array( morphAttr.length ).fill().map( () => [] );
  323. }
  324. }
  325. // convert the error tolerance to an amount of decimal places to truncate to
  326. var decimalShift = Math.log10( 1 / tolerance );
  327. var shiftMultiplier = Math.pow( 10, decimalShift );
  328. for ( var i = 0; i < vertexCount; i ++ ) {
  329. var index = indices ? indices.getX( i ) : i;
  330. // Generate a hash for the vertex attributes at the current index 'i'
  331. var hash = '';
  332. for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
  333. var name = attributeNames[ j ];
  334. var attribute = geometry.getAttribute( name );
  335. var itemSize = attribute.itemSize;
  336. for ( var k = 0; k < itemSize; k ++ ) {
  337. // double tilde truncates the decimal value
  338. hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * shiftMultiplier ) },`;
  339. }
  340. }
  341. // Add another reference to the vertex if it's already
  342. // used by another index
  343. if ( hash in hashToIndex ) {
  344. newIndices.push( hashToIndex[ hash ] );
  345. } else {
  346. // copy data to the new index in the attribute arrays
  347. for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
  348. var name = attributeNames[ j ];
  349. var attribute = geometry.getAttribute( name );
  350. var morphAttr = geometry.morphAttributes[ name ];
  351. var itemSize = attribute.itemSize;
  352. var newarray = attrArrays[ name ];
  353. var newMorphArrays = morphAttrsArrays[ name ];
  354. for ( var k = 0; k < itemSize; k ++ ) {
  355. var getterFunc = getters[ k ];
  356. newarray.push( attribute[ getterFunc ]( index ) );
  357. if ( morphAttr ) {
  358. for ( var m = 0, ml = morphAttr.length; m < ml; m ++ ) {
  359. newMorphArrays[ m ].push( morphAttr[ m ][ getterFunc ]( index ) );
  360. }
  361. }
  362. }
  363. }
  364. hashToIndex[ hash ] = nextIndex;
  365. newIndices.push( nextIndex );
  366. nextIndex ++;
  367. }
  368. }
  369. // Generate typed arrays from new attribute arrays and update
  370. // the attributeBuffers
  371. const result = geometry.clone();
  372. for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
  373. var name = attributeNames[ i ];
  374. var oldAttribute = geometry.getAttribute( name );
  375. var buffer = new oldAttribute.array.constructor( attrArrays[ name ] );
  376. var attribute = new BufferAttribute( buffer, oldAttribute.itemSize, oldAttribute.normalized );
  377. result.setAttribute( name, attribute );
  378. // Update the attribute arrays
  379. if ( name in morphAttrsArrays ) {
  380. for ( var j = 0; j < morphAttrsArrays[ name ].length; j ++ ) {
  381. var oldMorphAttribute = geometry.morphAttributes[ name ][ j ];
  382. var buffer = new oldMorphAttribute.array.constructor( morphAttrsArrays[ name ][ j ] );
  383. var morphAttribute = new BufferAttribute( buffer, oldMorphAttribute.itemSize, oldMorphAttribute.normalized );
  384. result.morphAttributes[ name ][ j ] = morphAttribute;
  385. }
  386. }
  387. }
  388. // indices
  389. result.setIndex( newIndices );
  390. return result;
  391. },
  392. /**
  393. * @param {BufferGeometry} geometry
  394. * @param {number} drawMode
  395. * @return {BufferGeometry>}
  396. */
  397. toTrianglesDrawMode: function ( geometry, drawMode ) {
  398. if ( drawMode === TrianglesDrawMode ) {
  399. console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' );
  400. return geometry;
  401. }
  402. if ( drawMode === TriangleFanDrawMode || drawMode === TriangleStripDrawMode ) {
  403. var index = geometry.getIndex();
  404. // generate index if not present
  405. if ( index === null ) {
  406. var indices = [];
  407. var position = geometry.getAttribute( 'position' );
  408. if ( position !== undefined ) {
  409. for ( var i = 0; i < position.count; i ++ ) {
  410. indices.push( i );
  411. }
  412. geometry.setIndex( indices );
  413. index = geometry.getIndex();
  414. } else {
  415. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  416. return geometry;
  417. }
  418. }
  419. //
  420. var numberOfTriangles = index.count - 2;
  421. var newIndices = [];
  422. if ( drawMode === TriangleFanDrawMode ) {
  423. // gl.TRIANGLE_FAN
  424. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  425. newIndices.push( index.getX( 0 ) );
  426. newIndices.push( index.getX( i ) );
  427. newIndices.push( index.getX( i + 1 ) );
  428. }
  429. } else {
  430. // gl.TRIANGLE_STRIP
  431. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  432. if ( i % 2 === 0 ) {
  433. newIndices.push( index.getX( i ) );
  434. newIndices.push( index.getX( i + 1 ) );
  435. newIndices.push( index.getX( i + 2 ) );
  436. } else {
  437. newIndices.push( index.getX( i + 2 ) );
  438. newIndices.push( index.getX( i + 1 ) );
  439. newIndices.push( index.getX( i ) );
  440. }
  441. }
  442. }
  443. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  444. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  445. }
  446. // build final geometry
  447. var newGeometry = geometry.clone();
  448. newGeometry.setIndex( newIndices );
  449. newGeometry.clearGroups();
  450. return newGeometry;
  451. } else {
  452. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode );
  453. return geometry;
  454. }
  455. }
  456. };
  457. export { BufferGeometryUtils };