BufferGeometryUtils.js 15 KB

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