2
0

BufferGeometryUtils.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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.setAttribute( '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 morphTargetsRelative = geometries[ 0 ].morphTargetsRelative;
  135. var mergedGeometry = new THREE.BufferGeometry();
  136. var offset = 0;
  137. for ( var i = 0; i < geometries.length; ++ i ) {
  138. var geometry = geometries[ i ];
  139. // ensure that all geometries are indexed, or none
  140. if ( isIndexed !== ( geometry.index !== null ) ) return null;
  141. // gather attributes, exit early if they're different
  142. for ( var name in geometry.attributes ) {
  143. if ( ! attributesUsed.has( name ) ) return null;
  144. if ( attributes[ name ] === undefined ) attributes[ name ] = [];
  145. attributes[ name ].push( geometry.attributes[ name ] );
  146. }
  147. // gather morph attributes, exit early if they're different
  148. if ( morphTargetsRelative !== geometry.morphTargetsRelative ) return null;
  149. for ( var name in geometry.morphAttributes ) {
  150. if ( ! morphAttributesUsed.has( name ) ) return null;
  151. if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = [];
  152. morphAttributes[ name ].push( geometry.morphAttributes[ name ] );
  153. }
  154. // gather .userData
  155. mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || [];
  156. mergedGeometry.userData.mergedUserData.push( geometry.userData );
  157. if ( useGroups ) {
  158. var count;
  159. if ( isIndexed ) {
  160. count = geometry.index.count;
  161. } else if ( geometry.attributes.position !== undefined ) {
  162. count = geometry.attributes.position.count;
  163. } else {
  164. return null;
  165. }
  166. mergedGeometry.addGroup( offset, count, i );
  167. offset += count;
  168. }
  169. }
  170. // merge indices
  171. if ( isIndexed ) {
  172. var indexOffset = 0;
  173. var mergedIndex = [];
  174. for ( var i = 0; i < geometries.length; ++ i ) {
  175. var index = geometries[ i ].index;
  176. for ( var j = 0; j < index.count; ++ j ) {
  177. mergedIndex.push( index.getX( j ) + indexOffset );
  178. }
  179. indexOffset += geometries[ i ].attributes.position.count;
  180. }
  181. mergedGeometry.setIndex( mergedIndex );
  182. }
  183. // merge attributes
  184. for ( var name in attributes ) {
  185. var mergedAttribute = this.mergeBufferAttributes( attributes[ name ] );
  186. if ( ! mergedAttribute ) return null;
  187. mergedGeometry.setAttribute( name, mergedAttribute );
  188. }
  189. // merge morph attributes
  190. for ( var name in morphAttributes ) {
  191. var numMorphTargets = morphAttributes[ name ][ 0 ].length;
  192. if ( numMorphTargets === 0 ) break;
  193. mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
  194. mergedGeometry.morphAttributes[ name ] = [];
  195. for ( var i = 0; i < numMorphTargets; ++ i ) {
  196. var morphAttributesToMerge = [];
  197. for ( var j = 0; j < morphAttributes[ name ].length; ++ j ) {
  198. morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] );
  199. }
  200. var mergedMorphAttribute = this.mergeBufferAttributes( morphAttributesToMerge );
  201. if ( ! mergedMorphAttribute ) return null;
  202. mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute );
  203. }
  204. }
  205. return mergedGeometry;
  206. },
  207. /**
  208. * @param {Array<THREE.BufferAttribute>} attributes
  209. * @return {THREE.BufferAttribute}
  210. */
  211. mergeBufferAttributes: function ( attributes ) {
  212. var TypedArray;
  213. var itemSize;
  214. var normalized;
  215. var arrayLength = 0;
  216. for ( var i = 0; i < attributes.length; ++ i ) {
  217. var attribute = attributes[ i ];
  218. if ( attribute.isInterleavedBufferAttribute ) return null;
  219. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  220. if ( TypedArray !== attribute.array.constructor ) return null;
  221. if ( itemSize === undefined ) itemSize = attribute.itemSize;
  222. if ( itemSize !== attribute.itemSize ) return null;
  223. if ( normalized === undefined ) normalized = attribute.normalized;
  224. if ( normalized !== attribute.normalized ) return null;
  225. arrayLength += attribute.array.length;
  226. }
  227. var array = new TypedArray( arrayLength );
  228. var offset = 0;
  229. for ( var i = 0; i < attributes.length; ++ i ) {
  230. array.set( attributes[ i ].array, offset );
  231. offset += attributes[ i ].array.length;
  232. }
  233. return new THREE.BufferAttribute( array, itemSize, normalized );
  234. },
  235. /**
  236. * @param {Array<THREE.BufferAttribute>} attributes
  237. * @return {Array<THREE.InterleavedBufferAttribute>}
  238. */
  239. interleaveAttributes: function ( attributes ) {
  240. // Interleaves the provided attributes into an InterleavedBuffer and returns
  241. // a set of InterleavedBufferAttributes for each attribute
  242. var TypedArray;
  243. var arrayLength = 0;
  244. var stride = 0;
  245. // calculate the the length and type of the interleavedBuffer
  246. for ( var i = 0, l = attributes.length; i < l; ++ i ) {
  247. var attribute = attributes[ i ];
  248. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  249. if ( TypedArray !== attribute.array.constructor ) {
  250. console.warn( 'AttributeBuffers of different types cannot be interleaved' );
  251. return null;
  252. }
  253. arrayLength += attribute.array.length;
  254. stride += attribute.itemSize;
  255. }
  256. // Create the set of buffer attributes
  257. var interleavedBuffer = new THREE.InterleavedBuffer( new TypedArray( arrayLength ), stride );
  258. var offset = 0;
  259. var res = [];
  260. var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  261. var setters = [ 'setX', 'setY', 'setZ', 'setW' ];
  262. for ( var j = 0, l = attributes.length; j < l; j ++ ) {
  263. var attribute = attributes[ j ];
  264. var itemSize = attribute.itemSize;
  265. var count = attribute.count;
  266. var iba = new THREE.InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
  267. res.push( iba );
  268. offset += itemSize;
  269. // Move the data for each attribute into the new interleavedBuffer
  270. // at the appropriate offset
  271. for ( var c = 0; c < count; c ++ ) {
  272. for ( var k = 0; k < itemSize; k ++ ) {
  273. iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
  274. }
  275. }
  276. }
  277. return res;
  278. },
  279. /**
  280. * @param {Array<THREE.BufferGeometry>} geometry
  281. * @return {number}
  282. */
  283. estimateBytesUsed: function ( geometry ) {
  284. // Return the estimated memory used by this geometry in bytes
  285. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  286. // for InterleavedBufferAttributes.
  287. var mem = 0;
  288. for ( var name in geometry.attributes ) {
  289. var attr = geometry.getAttribute( name );
  290. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  291. }
  292. var indices = geometry.getIndex();
  293. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  294. return mem;
  295. },
  296. /**
  297. * @param {THREE.BufferGeometry} geometry
  298. * @param {number} tolerance
  299. * @return {THREE.BufferGeometry>}
  300. */
  301. mergeVertices: function ( geometry, tolerance = 1e-4 ) {
  302. tolerance = Math.max( tolerance, Number.EPSILON );
  303. // Generate an index buffer if the geometry doesn't have one, or optimize it
  304. // if it's already available.
  305. var hashToIndex = {};
  306. var indices = geometry.getIndex();
  307. var positions = geometry.getAttribute( 'position' );
  308. var vertexCount = indices ? indices.count : positions.count;
  309. // next value for triangle indices
  310. var nextIndex = 0;
  311. // attributes and new attribute arrays
  312. var attributeNames = Object.keys( geometry.attributes );
  313. var attrArrays = {};
  314. var morphAttrsArrays = {};
  315. var newIndices = [];
  316. var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  317. // initialize the arrays
  318. for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
  319. var name = attributeNames[ i ];
  320. attrArrays[ name ] = [];
  321. var morphAttr = geometry.morphAttributes[ name ];
  322. if ( morphAttr ) {
  323. morphAttrsArrays[ name ] = new Array( morphAttr.length ).fill().map( () => [] );
  324. }
  325. }
  326. // convert the error tolerance to an amount of decimal places to truncate to
  327. var decimalShift = Math.log10( 1 / tolerance );
  328. var shiftMultiplier = Math.pow( 10, decimalShift );
  329. for ( var i = 0; i < vertexCount; i ++ ) {
  330. var index = indices ? indices.getX( i ) : i;
  331. // Generate a hash for the vertex attributes at the current index 'i'
  332. var hash = '';
  333. for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
  334. var name = attributeNames[ j ];
  335. var attribute = geometry.getAttribute( name );
  336. var itemSize = attribute.itemSize;
  337. for ( var k = 0; k < itemSize; k ++ ) {
  338. // double tilde truncates the decimal value
  339. hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * shiftMultiplier ) },`;
  340. }
  341. }
  342. // Add another reference to the vertex if it's already
  343. // used by another index
  344. if ( hash in hashToIndex ) {
  345. newIndices.push( hashToIndex[ hash ] );
  346. } else {
  347. // copy data to the new index in the attribute arrays
  348. for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
  349. var name = attributeNames[ j ];
  350. var attribute = geometry.getAttribute( name );
  351. var morphAttr = geometry.morphAttributes[ name ];
  352. var itemSize = attribute.itemSize;
  353. var newarray = attrArrays[ name ];
  354. var newMorphArrays = morphAttrsArrays[ name ];
  355. for ( var k = 0; k < itemSize; k ++ ) {
  356. var getterFunc = getters[ k ];
  357. newarray.push( attribute[ getterFunc ]( index ) );
  358. if ( morphAttr ) {
  359. for ( var m = 0, ml = morphAttr.length; m < ml; m ++ ) {
  360. newMorphArrays[ m ].push( morphAttr[ m ][ getterFunc ]( index ) );
  361. }
  362. }
  363. }
  364. }
  365. hashToIndex[ hash ] = nextIndex;
  366. newIndices.push( nextIndex );
  367. nextIndex ++;
  368. }
  369. }
  370. // Generate typed arrays from new attribute arrays and update
  371. // the attributeBuffers
  372. const result = geometry.clone();
  373. for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
  374. var name = attributeNames[ i ];
  375. var oldAttribute = geometry.getAttribute( name );
  376. var buffer = new oldAttribute.array.constructor( attrArrays[ name ] );
  377. var attribute = new THREE.BufferAttribute( buffer, oldAttribute.itemSize, oldAttribute.normalized );
  378. result.setAttribute( name, attribute );
  379. // Update the attribute arrays
  380. if ( name in morphAttrsArrays ) {
  381. for ( var j = 0; j < morphAttrsArrays[ name ].length; j ++ ) {
  382. var oldMorphAttribute = geometry.morphAttributes[ name ][ j ];
  383. var buffer = new oldMorphAttribute.array.constructor( morphAttrsArrays[ name ][ j ] );
  384. var morphAttribute = new THREE.BufferAttribute( buffer, oldMorphAttribute.itemSize, oldMorphAttribute.normalized );
  385. result.morphAttributes[ name ][ j ] = morphAttribute;
  386. }
  387. }
  388. }
  389. // indices
  390. result.setIndex( newIndices );
  391. return result;
  392. },
  393. /**
  394. * @param {THREE.BufferGeometry} geometry
  395. * @param {number} drawMode
  396. * @return {THREE.BufferGeometry>}
  397. */
  398. convertToTriangles: function ( geometry, drawMode ) {
  399. if ( drawMode === THREE.TrianglesDrawMode ) {
  400. console.warn( 'THREE.BufferGeometryUtils.convertToTriangles(): Geometry already defined as triangles.' );
  401. return geometry;
  402. }
  403. if ( drawMode === THREE.TriangleFanDrawMode || drawMode === THREE.TriangleStripDrawMode ) {
  404. var index = geometry.getIndex();
  405. // generate index if not present
  406. if ( index === null ) {
  407. var indices = [];
  408. var position = geometry.getAttribute( 'position' );
  409. if ( position !== undefined ) {
  410. for ( var i = 0; i < position.count; i ++ ) {
  411. indices.push( i );
  412. }
  413. geometry.setIndex( indices );
  414. index = geometry.getIndex();
  415. } else {
  416. console.error( 'THREE.BufferGeometryUtils.convertToTriangles(): Undefined position attribute. Unable to perform conversion.' );
  417. return geometry;
  418. }
  419. }
  420. //
  421. var numberOfTriangles = index.count - 2;
  422. var newIndices = [];
  423. if ( drawMode === THREE.TriangleFanDrawMode ) {
  424. // gl.TRIANGLE_FAN
  425. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  426. newIndices.push( index.getX( 0 ) );
  427. newIndices.push( index.getX( i ) );
  428. newIndices.push( index.getX( i + 1 ) );
  429. }
  430. } else {
  431. // gl.TRIANGLE_STRIP
  432. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  433. if ( i % 2 === 0 ) {
  434. newIndices.push( index.getX( i ) );
  435. newIndices.push( index.getX( i + 1 ) );
  436. newIndices.push( index.getX( i + 2 ) );
  437. } else {
  438. newIndices.push( index.getX( i + 2 ) );
  439. newIndices.push( index.getX( i + 1 ) );
  440. newIndices.push( index.getX( i ) );
  441. }
  442. }
  443. }
  444. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  445. console.error( 'THREE.BufferGeometryUtils.convertToTriangles(): Unable to generate correct amount of triangles.' );
  446. }
  447. // build final geometry
  448. var newGeometry = geometry.clone();
  449. newGeometry.setIndex( newIndices );
  450. newGeometry.clearGroups();
  451. return newGeometry;
  452. } else {
  453. console.error( 'THREE.BufferGeometryUtils.convertToTriangles(): Unknown draw mode:', drawMode );
  454. return geometry;
  455. }
  456. }
  457. };