GLTFExporter.js 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428
  1. //------------------------------------------------------------------------------
  2. // Constants
  3. //------------------------------------------------------------------------------
  4. var WEBGL_CONSTANTS = {
  5. POINTS: 0x0000,
  6. LINES: 0x0001,
  7. LINE_LOOP: 0x0002,
  8. LINE_STRIP: 0x0003,
  9. TRIANGLES: 0x0004,
  10. TRIANGLE_STRIP: 0x0005,
  11. TRIANGLE_FAN: 0x0006,
  12. UNSIGNED_BYTE: 0x1401,
  13. UNSIGNED_SHORT: 0x1403,
  14. FLOAT: 0x1406,
  15. UNSIGNED_INT: 0x1405,
  16. ARRAY_BUFFER: 0x8892,
  17. ELEMENT_ARRAY_BUFFER: 0x8893,
  18. NEAREST: 0x2600,
  19. LINEAR: 0x2601,
  20. NEAREST_MIPMAP_NEAREST: 0x2700,
  21. LINEAR_MIPMAP_NEAREST: 0x2701,
  22. NEAREST_MIPMAP_LINEAR: 0x2702,
  23. LINEAR_MIPMAP_LINEAR: 0x2703,
  24. CLAMP_TO_EDGE: 33071,
  25. MIRRORED_REPEAT: 33648,
  26. REPEAT: 10497
  27. };
  28. var identityArray = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ];
  29. var THREE_TO_WEBGL = {};
  30. THREE_TO_WEBGL[ THREE.NearestFilter ] = WEBGL_CONSTANTS.NEAREST;
  31. THREE_TO_WEBGL[ THREE.NearestMipmapNearestFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST;
  32. THREE_TO_WEBGL[ THREE.NearestMipmapLinearFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR;
  33. THREE_TO_WEBGL[ THREE.LinearFilter ] = WEBGL_CONSTANTS.LINEAR;
  34. THREE_TO_WEBGL[ THREE.LinearMipmapNearestFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST;
  35. THREE_TO_WEBGL[ THREE.LinearMipmapLinearFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR;
  36. THREE_TO_WEBGL[ THREE.ClampToEdgeWrapping ] = WEBGL_CONSTANTS.CLAMP_TO_EDGE;
  37. THREE_TO_WEBGL[ THREE.RepeatWrapping ] = WEBGL_CONSTANTS.REPEAT;
  38. THREE_TO_WEBGL[ THREE.MirroredRepeatWrapping ] = WEBGL_CONSTANTS.MIRRORED_REPEAT;
  39. var PATH_PROPERTIES = {
  40. scale: 'scale',
  41. position: 'translation',
  42. quaternion: 'rotation',
  43. morphTargetInfluences: 'weights'
  44. };
  45. //------------------------------------------------------------------------------
  46. // GLTF Exporter
  47. //------------------------------------------------------------------------------
  48. THREE.GLTFExporter = function () {};
  49. THREE.GLTFExporter.prototype = {
  50. constructor: THREE.GLTFExporter,
  51. /**
  52. * Parse scenes and generate GLTF output
  53. * @param {THREE.Scene or [THREE.Scenes]} input THREE.Scene or Array of THREE.Scenes
  54. * @param {Function} onDone Callback on completed
  55. * @param {Object} options options
  56. */
  57. parse: function ( input, onDone, options ) {
  58. var DEFAULT_OPTIONS = {
  59. binary: false,
  60. trs: false,
  61. onlyVisible: true,
  62. truncateDrawRange: true,
  63. embedImages: true,
  64. maxTextureSize: Infinity,
  65. animations: [],
  66. forcePowerOfTwoTextures: false,
  67. includeCustomExtensions: false
  68. };
  69. options = Object.assign( {}, DEFAULT_OPTIONS, options );
  70. if ( options.animations.length > 0 ) {
  71. // Only TRS properties, and not matrices, may be targeted by animation.
  72. options.trs = true;
  73. }
  74. var outputJSON = {
  75. asset: {
  76. version: "2.0",
  77. generator: "THREE.GLTFExporter"
  78. }
  79. };
  80. var byteOffset = 0;
  81. var buffers = [];
  82. var pending = [];
  83. var nodeMap = new Map();
  84. var skins = [];
  85. var extensionsUsed = {};
  86. var cachedData = {
  87. meshes: new Map(),
  88. attributes: new Map(),
  89. attributesNormalized: new Map(),
  90. materials: new Map(),
  91. textures: new Map(),
  92. images: new Map()
  93. };
  94. var cachedCanvas;
  95. var uids = new Map();
  96. var uid = 0;
  97. /**
  98. * Assign and return a temporal unique id for an object
  99. * especially which doesn't have .uuid
  100. * @param {Object} object
  101. * @return {Integer}
  102. */
  103. function getUID( object ) {
  104. if ( ! uids.has( object ) ) uids.set( object, uid ++ );
  105. return uids.get( object );
  106. }
  107. /**
  108. * Compare two arrays
  109. * @param {Array} array1 Array 1 to compare
  110. * @param {Array} array2 Array 2 to compare
  111. * @return {Boolean} Returns true if both arrays are equal
  112. */
  113. function equalArray( array1, array2 ) {
  114. return ( array1.length === array2.length ) && array1.every( function ( element, index ) {
  115. return element === array2[ index ];
  116. } );
  117. }
  118. /**
  119. * Is identity matrix
  120. *
  121. * @param {THREE.Matrix4} matrix
  122. * @returns {Boolean} Returns true, if parameter is identity matrix
  123. */
  124. function isIdentityMatrix( matrix ) {
  125. return equalArray( matrix.elements, identityArray );
  126. }
  127. /**
  128. * Converts a string to an ArrayBuffer.
  129. * @param {string} text
  130. * @return {ArrayBuffer}
  131. */
  132. function stringToArrayBuffer( text ) {
  133. if ( window.TextEncoder !== undefined ) {
  134. return new TextEncoder().encode( text ).buffer;
  135. }
  136. var array = new Uint8Array( new ArrayBuffer( text.length ) );
  137. for ( var i = 0, il = text.length; i < il; i ++ ) {
  138. var value = text.charCodeAt( i );
  139. // Replacing multi-byte character with space(0x20).
  140. array[ i ] = value > 0xFF ? 0x20 : value;
  141. }
  142. return array.buffer;
  143. }
  144. /**
  145. * Get the min and max vectors from the given attribute
  146. * @param {THREE.BufferAttribute} attribute Attribute to find the min/max in range from start to start + count
  147. * @param {Integer} start
  148. * @param {Integer} count
  149. * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
  150. */
  151. function getMinMax( attribute, start, count ) {
  152. var output = {
  153. min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
  154. max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
  155. };
  156. for ( var i = start; i < start + count; i ++ ) {
  157. for ( var a = 0; a < attribute.itemSize; a ++ ) {
  158. var value = attribute.array[ i * attribute.itemSize + a ];
  159. output.min[ a ] = Math.min( output.min[ a ], value );
  160. output.max[ a ] = Math.max( output.max[ a ], value );
  161. }
  162. }
  163. return output;
  164. }
  165. /**
  166. * Checks if image size is POT.
  167. *
  168. * @param {Image} image The image to be checked.
  169. * @returns {Boolean} Returns true if image size is POT.
  170. *
  171. */
  172. function isPowerOfTwo( image ) {
  173. return THREE.MathUtils.isPowerOfTwo( image.width ) && THREE.MathUtils.isPowerOfTwo( image.height );
  174. }
  175. /**
  176. * Creates an ImageData instance from a DataTexture image information, regardless of format
  177. *
  178. * @param {{ data: ArrayBuffer, width: number, height: number }} image
  179. * @param {number} format
  180. * @param {canvas} canvas
  181. */
  182. function toImageData( image, format, canvas ) {
  183. // Initialize RGBA array
  184. let data = new Uint8ClampedArray( image.height * image.width * 4 );
  185. let pixelStride = 4;
  186. let convertFunction;
  187. switch ( format ) {
  188. // No conversion needed
  189. case THREE.RGBAIntegerFormat:
  190. case THREE.RGBAFormat:
  191. case THREE.RGBEFormat:
  192. break;
  193. case THREE.RGBIntegerFormat:
  194. case THREE.RGBFormat:
  195. pixelStride = 3;
  196. convertFunction = function ( pixelData ) {
  197. return [ pixelData[ 0 ], pixelData[ 1 ], pixelData[ 2 ], 255 ];
  198. };
  199. break;
  200. case THREE.RGIntegerFormat:
  201. case THREE.RGFormat:
  202. pixelStride = 2;
  203. convertFunction = function ( pixelData ) {
  204. return [ pixelData[ 0 ], pixelData[ 1 ], 0, 255 ];
  205. };
  206. break;
  207. case THREE.RedIntegerFormat:
  208. case THREE.RedFormat:
  209. pixelStride = 1;
  210. convertFunction = function ( pixelData ) {
  211. return [ pixelData[ 0 ], pixelData[ 1 ], pixelData[ 2 ], 255 ];
  212. };
  213. break;
  214. default:
  215. throw "Format not supported";
  216. }
  217. if ( convertFunction != null ) {
  218. const array = [ 0, 0, 0, 0 ];
  219. for ( let i = 0; i < image.data.length / pixelStride; i ++ ) {
  220. for ( let j = 0; j < pixelStride; j ++ )
  221. array[ j ] = image.data[ pixelStride * i + j ];
  222. const result = convertFunction( array );
  223. for ( let j = 0; j < 4; j ++ )
  224. data[ 4 * i + j ] = result[ j ];
  225. }
  226. }
  227. // Downscale the image
  228. if ( canvas.width !== image.width || canvas.height !== image.height ) {
  229. const newData = new Uint8ClampedArray( 4 * canvas.width * canvas.height );
  230. for ( let y = 0; y < canvas.height; y ++ ) {
  231. const sY = y * image.height / canvas.height;
  232. const fY = Math.floor( sY );
  233. const cY = Math.ceil( sY );
  234. const iY = sY - fY;
  235. for ( let x = 0; x < canvas.width; x ++ ) {
  236. const sX = x * image.width / canvas.width;
  237. const fX = Math.floor( sX );
  238. const cX = Math.ceil( sX );
  239. const iX = sX - fX;
  240. for ( let i = 0; i < 4; i ++ ) {
  241. const p1 = data[ 4 * ( fX + image.height * sY ) + i ];
  242. const p2 = data[ 4 * ( fX + image.height * cY ) + i ];
  243. const p3 = data[ 4 * ( cX + image.height * sY ) + i ];
  244. const p4 = data[ 4 * ( cX + image.height * cY ) + i ];
  245. newData[ 4 * ( x + canvas.height * y ) + i ] = Math.round(
  246. p1 * iX * iY +
  247. p2 * iX * ( 1 - iY ) +
  248. p3 * ( 1 - iX ) * iY +
  249. p4 * ( 1 - iX ) * ( 1 - iY )
  250. );
  251. }
  252. }
  253. }
  254. data = newData;
  255. }
  256. return new ImageData( data, image.width, image.height );
  257. }
  258. /**
  259. * Checks if normal attribute values are normalized.
  260. *
  261. * @param {THREE.BufferAttribute} normal
  262. * @returns {Boolean}
  263. *
  264. */
  265. function isNormalizedNormalAttribute( normal ) {
  266. if ( cachedData.attributesNormalized.has( normal ) ) {
  267. return false;
  268. }
  269. var v = new THREE.Vector3();
  270. for ( var i = 0, il = normal.count; i < il; i ++ ) {
  271. // 0.0005 is from glTF-validator
  272. if ( Math.abs( v.fromArray( normal.array, i * 3 ).length() - 1.0 ) > 0.0005 ) return false;
  273. }
  274. return true;
  275. }
  276. /**
  277. * Creates normalized normal buffer attribute.
  278. *
  279. * @param {THREE.BufferAttribute} normal
  280. * @returns {THREE.BufferAttribute}
  281. *
  282. */
  283. function createNormalizedNormalAttribute( normal ) {
  284. if ( cachedData.attributesNormalized.has( normal ) ) {
  285. return cachedData.attributesNormalized.get( normal );
  286. }
  287. var attribute = normal.clone();
  288. var v = new THREE.Vector3();
  289. for ( var i = 0, il = attribute.count; i < il; i ++ ) {
  290. v.fromArray( attribute.array, i * 3 );
  291. if ( v.x === 0 && v.y === 0 && v.z === 0 ) {
  292. // if values can't be normalized set (1, 0, 0)
  293. v.setX( 1.0 );
  294. } else {
  295. v.normalize();
  296. }
  297. v.toArray( attribute.array, i * 3 );
  298. }
  299. cachedData.attributesNormalized.set( normal, attribute );
  300. return attribute;
  301. }
  302. /**
  303. * Get the required size + padding for a buffer, rounded to the next 4-byte boundary.
  304. * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
  305. *
  306. * @param {Integer} bufferSize The size the original buffer.
  307. * @returns {Integer} new buffer size with required padding.
  308. *
  309. */
  310. function getPaddedBufferSize( bufferSize ) {
  311. return Math.ceil( bufferSize / 4 ) * 4;
  312. }
  313. /**
  314. * Returns a buffer aligned to 4-byte boundary.
  315. *
  316. * @param {ArrayBuffer} arrayBuffer Buffer to pad
  317. * @param {Integer} paddingByte (Optional)
  318. * @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer
  319. */
  320. function getPaddedArrayBuffer( arrayBuffer, paddingByte ) {
  321. paddingByte = paddingByte || 0;
  322. var paddedLength = getPaddedBufferSize( arrayBuffer.byteLength );
  323. if ( paddedLength !== arrayBuffer.byteLength ) {
  324. var array = new Uint8Array( paddedLength );
  325. array.set( new Uint8Array( arrayBuffer ) );
  326. if ( paddingByte !== 0 ) {
  327. for ( var i = arrayBuffer.byteLength; i < paddedLength; i ++ ) {
  328. array[ i ] = paddingByte;
  329. }
  330. }
  331. return array.buffer;
  332. }
  333. return arrayBuffer;
  334. }
  335. /**
  336. * Serializes a userData.
  337. *
  338. * @param {THREE.Object3D|THREE.Material} object
  339. * @param {Object} gltfProperty
  340. */
  341. function serializeUserData( object, gltfProperty ) {
  342. if ( Object.keys( object.userData ).length === 0 ) {
  343. return;
  344. }
  345. try {
  346. var json = JSON.parse( JSON.stringify( object.userData ) );
  347. if ( options.includeCustomExtensions && json.gltfExtensions ) {
  348. if ( gltfProperty.extensions === undefined ) {
  349. gltfProperty.extensions = {};
  350. }
  351. for ( var extensionName in json.gltfExtensions ) {
  352. gltfProperty.extensions[ extensionName ] = json.gltfExtensions[ extensionName ];
  353. extensionsUsed[ extensionName ] = true;
  354. }
  355. delete json.gltfExtensions;
  356. }
  357. if ( Object.keys( json ).length > 0 ) {
  358. gltfProperty.extras = json;
  359. }
  360. } catch ( error ) {
  361. console.warn( 'THREE.GLTFExporter: userData of \'' + object.name + '\' ' +
  362. 'won\'t be serialized because of JSON.stringify error - ' + error.message );
  363. }
  364. }
  365. /**
  366. * Applies a texture transform, if present, to the map definition. Requires
  367. * the KHR_texture_transform extension.
  368. */
  369. function applyTextureTransform( mapDef, texture ) {
  370. var didTransform = false;
  371. var transformDef = {};
  372. if ( texture.offset.x !== 0 || texture.offset.y !== 0 ) {
  373. transformDef.offset = texture.offset.toArray();
  374. didTransform = true;
  375. }
  376. if ( texture.rotation !== 0 ) {
  377. transformDef.rotation = texture.rotation;
  378. didTransform = true;
  379. }
  380. if ( texture.repeat.x !== 1 || texture.repeat.y !== 1 ) {
  381. transformDef.scale = texture.repeat.toArray();
  382. didTransform = true;
  383. }
  384. if ( didTransform ) {
  385. mapDef.extensions = mapDef.extensions || {};
  386. mapDef.extensions[ 'KHR_texture_transform' ] = transformDef;
  387. extensionsUsed[ 'KHR_texture_transform' ] = true;
  388. }
  389. }
  390. /**
  391. * Process a buffer to append to the default one.
  392. * @param {ArrayBuffer} buffer
  393. * @return {Integer}
  394. */
  395. function processBuffer( buffer ) {
  396. if ( ! outputJSON.buffers ) {
  397. outputJSON.buffers = [ { byteLength: 0 } ];
  398. }
  399. // All buffers are merged before export.
  400. buffers.push( buffer );
  401. return 0;
  402. }
  403. /**
  404. * Process and generate a BufferView
  405. * @param {THREE.BufferAttribute} attribute
  406. * @param {number} componentType
  407. * @param {number} start
  408. * @param {number} count
  409. * @param {number} target (Optional) Target usage of the BufferView
  410. * @return {Object}
  411. */
  412. function processBufferView( attribute, componentType, start, count, target ) {
  413. if ( ! outputJSON.bufferViews ) {
  414. outputJSON.bufferViews = [];
  415. }
  416. // Create a new dataview and dump the attribute's array into it
  417. var componentSize;
  418. if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
  419. componentSize = 1;
  420. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  421. componentSize = 2;
  422. } else {
  423. componentSize = 4;
  424. }
  425. var byteLength = getPaddedBufferSize( count * attribute.itemSize * componentSize );
  426. var dataView = new DataView( new ArrayBuffer( byteLength ) );
  427. var offset = 0;
  428. for ( var i = start; i < start + count; i ++ ) {
  429. for ( var a = 0; a < attribute.itemSize; a ++ ) {
  430. var value;
  431. if ( attribute.itemSize > 4 ) {
  432. // no support for interleaved data for itemSize > 4
  433. value = attribute.array[ i * attribute.itemSize + a ];
  434. } else {
  435. if ( a === 0 ) value = attribute.getX( i );
  436. else if ( a === 1 ) value = attribute.getY( i );
  437. else if ( a === 2 ) value = attribute.getZ( i );
  438. else if ( a === 3 ) value = attribute.getW( i );
  439. }
  440. if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
  441. dataView.setFloat32( offset, value, true );
  442. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
  443. dataView.setUint32( offset, value, true );
  444. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  445. dataView.setUint16( offset, value, true );
  446. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
  447. dataView.setUint8( offset, value );
  448. }
  449. offset += componentSize;
  450. }
  451. }
  452. var gltfBufferView = {
  453. buffer: processBuffer( dataView.buffer ),
  454. byteOffset: byteOffset,
  455. byteLength: byteLength
  456. };
  457. if ( target !== undefined ) gltfBufferView.target = target;
  458. if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
  459. // Only define byteStride for vertex attributes.
  460. gltfBufferView.byteStride = attribute.itemSize * componentSize;
  461. }
  462. byteOffset += byteLength;
  463. outputJSON.bufferViews.push( gltfBufferView );
  464. // @TODO Merge bufferViews where possible.
  465. var output = {
  466. id: outputJSON.bufferViews.length - 1,
  467. byteLength: 0
  468. };
  469. return output;
  470. }
  471. /**
  472. * Process and generate a BufferView from an image Blob.
  473. * @param {Blob} blob
  474. * @return {Promise<Integer>}
  475. */
  476. function processBufferViewImage( blob ) {
  477. if ( ! outputJSON.bufferViews ) {
  478. outputJSON.bufferViews = [];
  479. }
  480. return new Promise( function ( resolve ) {
  481. var reader = new window.FileReader();
  482. reader.readAsArrayBuffer( blob );
  483. reader.onloadend = function () {
  484. var buffer = getPaddedArrayBuffer( reader.result );
  485. var bufferView = {
  486. buffer: processBuffer( buffer ),
  487. byteOffset: byteOffset,
  488. byteLength: buffer.byteLength
  489. };
  490. byteOffset += buffer.byteLength;
  491. outputJSON.bufferViews.push( bufferView );
  492. resolve( outputJSON.bufferViews.length - 1 );
  493. };
  494. } );
  495. }
  496. /**
  497. * Process attribute to generate an accessor
  498. * @param {THREE.BufferAttribute} attribute Attribute to process
  499. * @param {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range
  500. * @param {Integer} start (Optional)
  501. * @param {Integer} count (Optional)
  502. * @return {Integer} Index of the processed accessor on the "accessors" array
  503. */
  504. function processAccessor( attribute, geometry, start, count ) {
  505. var types = {
  506. 1: 'SCALAR',
  507. 2: 'VEC2',
  508. 3: 'VEC3',
  509. 4: 'VEC4',
  510. 16: 'MAT4'
  511. };
  512. var componentType;
  513. // Detect the component type of the attribute array (float, uint or ushort)
  514. if ( attribute.array.constructor === Float32Array ) {
  515. componentType = WEBGL_CONSTANTS.FLOAT;
  516. } else if ( attribute.array.constructor === Uint32Array ) {
  517. componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
  518. } else if ( attribute.array.constructor === Uint16Array ) {
  519. componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
  520. } else if ( attribute.array.constructor === Uint8Array ) {
  521. componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE;
  522. } else {
  523. throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type.' );
  524. }
  525. if ( start === undefined ) start = 0;
  526. if ( count === undefined ) count = attribute.count;
  527. // @TODO Indexed buffer geometry with drawRange not supported yet
  528. if ( options.truncateDrawRange && geometry !== undefined && geometry.index === null ) {
  529. var end = start + count;
  530. var end2 = geometry.drawRange.count === Infinity
  531. ? attribute.count
  532. : geometry.drawRange.start + geometry.drawRange.count;
  533. start = Math.max( start, geometry.drawRange.start );
  534. count = Math.min( end, end2 ) - start;
  535. if ( count < 0 ) count = 0;
  536. }
  537. // Skip creating an accessor if the attribute doesn't have data to export
  538. if ( count === 0 ) {
  539. return null;
  540. }
  541. var minMax = getMinMax( attribute, start, count );
  542. var bufferViewTarget;
  543. // If geometry isn't provided, don't infer the target usage of the bufferView. For
  544. // animation samplers, target must not be set.
  545. if ( geometry !== undefined ) {
  546. bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER;
  547. }
  548. var bufferView = processBufferView( attribute, componentType, start, count, bufferViewTarget );
  549. var gltfAccessor = {
  550. bufferView: bufferView.id,
  551. byteOffset: bufferView.byteOffset,
  552. componentType: componentType,
  553. count: count,
  554. max: minMax.max,
  555. min: minMax.min,
  556. type: types[ attribute.itemSize ]
  557. };
  558. if ( attribute.normalized === true ) {
  559. gltfAccessor.normalized = true;
  560. }
  561. if ( ! outputJSON.accessors ) {
  562. outputJSON.accessors = [];
  563. }
  564. outputJSON.accessors.push( gltfAccessor );
  565. return outputJSON.accessors.length - 1;
  566. }
  567. /**
  568. * Process image
  569. * @param {Image} image to process
  570. * @param {Integer} format of the image (e.g. THREE.RGBFormat, THREE.RGBAFormat etc)
  571. * @param {Boolean} flipY before writing out the image
  572. * @return {Integer} Index of the processed texture in the "images" array
  573. */
  574. function processImage( image, format, flipY ) {
  575. if ( ! cachedData.images.has( image ) ) {
  576. cachedData.images.set( image, {} );
  577. }
  578. var cachedImages = cachedData.images.get( image );
  579. var mimeType = format === THREE.RGBAFormat ? 'image/png' : 'image/jpeg';
  580. var key = mimeType + ":flipY/" + flipY.toString();
  581. if ( cachedImages[ key ] !== undefined ) {
  582. return cachedImages[ key ];
  583. }
  584. if ( ! outputJSON.images ) {
  585. outputJSON.images = [];
  586. }
  587. var gltfImage = { mimeType: mimeType };
  588. if ( options.embedImages ) {
  589. var canvas = cachedCanvas = cachedCanvas || document.createElement( 'canvas' );
  590. canvas.width = Math.min( image.width, options.maxTextureSize );
  591. canvas.height = Math.min( image.height, options.maxTextureSize );
  592. if ( options.forcePowerOfTwoTextures && ! isPowerOfTwo( canvas ) ) {
  593. console.warn( 'GLTFExporter: Resized non-power-of-two image.', image );
  594. canvas.width = THREE.MathUtils.floorPowerOfTwo( canvas.width );
  595. canvas.height = THREE.MathUtils.floorPowerOfTwo( canvas.height );
  596. }
  597. var ctx = canvas.getContext( '2d' );
  598. if ( flipY === true ) {
  599. ctx.translate( 0, canvas.height );
  600. ctx.scale( 1, - 1 );
  601. }
  602. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  603. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  604. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  605. ctx.drawImage( image, 0, 0, canvas.width, canvas.height );
  606. } else {
  607. const imageData = toImageData( image, format, canvas );
  608. ctx.putImageData( imageData, 0, 0, 0, 0, canvas.width, canvas.height );
  609. }
  610. if ( options.binary === true ) {
  611. pending.push( new Promise( function ( resolve ) {
  612. canvas.toBlob( function ( blob ) {
  613. processBufferViewImage( blob ).then( function ( bufferViewIndex ) {
  614. gltfImage.bufferView = bufferViewIndex;
  615. resolve();
  616. } );
  617. }, mimeType );
  618. } ) );
  619. } else {
  620. gltfImage.uri = canvas.toDataURL( mimeType );
  621. }
  622. } else {
  623. gltfImage.uri = image.src;
  624. }
  625. outputJSON.images.push( gltfImage );
  626. var index = outputJSON.images.length - 1;
  627. cachedImages[ key ] = index;
  628. return index;
  629. }
  630. /**
  631. * Process sampler
  632. * @param {Texture} map Texture to process
  633. * @return {Integer} Index of the processed texture in the "samplers" array
  634. */
  635. function processSampler( map ) {
  636. if ( ! outputJSON.samplers ) {
  637. outputJSON.samplers = [];
  638. }
  639. var gltfSampler = {
  640. magFilter: THREE_TO_WEBGL[ map.magFilter ],
  641. minFilter: THREE_TO_WEBGL[ map.minFilter ],
  642. wrapS: THREE_TO_WEBGL[ map.wrapS ],
  643. wrapT: THREE_TO_WEBGL[ map.wrapT ]
  644. };
  645. outputJSON.samplers.push( gltfSampler );
  646. return outputJSON.samplers.length - 1;
  647. }
  648. /**
  649. * Process texture
  650. * @param {Texture} map Map to process
  651. * @return {Integer} Index of the processed texture in the "textures" array
  652. */
  653. function processTexture( map ) {
  654. if ( cachedData.textures.has( map ) ) {
  655. return cachedData.textures.get( map );
  656. }
  657. if ( ! outputJSON.textures ) {
  658. outputJSON.textures = [];
  659. }
  660. var gltfTexture = {
  661. sampler: processSampler( map ),
  662. source: processImage( map.image, map.format, map.flipY )
  663. };
  664. if ( map.name ) {
  665. gltfTexture.name = map.name;
  666. }
  667. outputJSON.textures.push( gltfTexture );
  668. var index = outputJSON.textures.length - 1;
  669. cachedData.textures.set( map, index );
  670. return index;
  671. }
  672. /**
  673. * Process material
  674. * @param {THREE.Material} material Material to process
  675. * @return {Integer} Index of the processed material in the "materials" array
  676. */
  677. function processMaterial( material ) {
  678. if ( cachedData.materials.has( material ) ) {
  679. return cachedData.materials.get( material );
  680. }
  681. if ( material.isShaderMaterial ) {
  682. console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
  683. return null;
  684. }
  685. if ( ! outputJSON.materials ) {
  686. outputJSON.materials = [];
  687. }
  688. // @QUESTION Should we avoid including any attribute that has the default value?
  689. var gltfMaterial = {
  690. pbrMetallicRoughness: {}
  691. };
  692. if ( material.isMeshBasicMaterial ) {
  693. gltfMaterial.extensions = { KHR_materials_unlit: {} };
  694. extensionsUsed[ 'KHR_materials_unlit' ] = true;
  695. } else if ( material.isGLTFSpecularGlossinessMaterial ) {
  696. gltfMaterial.extensions = { KHR_materials_pbrSpecularGlossiness: {} };
  697. extensionsUsed[ 'KHR_materials_pbrSpecularGlossiness' ] = true;
  698. } else if ( ! material.isMeshStandardMaterial ) {
  699. console.warn( 'GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.' );
  700. }
  701. // pbrMetallicRoughness.baseColorFactor
  702. var color = material.color.toArray().concat( [ material.opacity ] );
  703. if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
  704. gltfMaterial.pbrMetallicRoughness.baseColorFactor = color;
  705. }
  706. if ( material.isMeshStandardMaterial ) {
  707. gltfMaterial.pbrMetallicRoughness.metallicFactor = material.metalness;
  708. gltfMaterial.pbrMetallicRoughness.roughnessFactor = material.roughness;
  709. } else if ( material.isMeshBasicMaterial ) {
  710. gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.0;
  711. gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.9;
  712. } else {
  713. gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.5;
  714. gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.5;
  715. }
  716. // pbrSpecularGlossiness diffuse, specular and glossiness factor
  717. if ( material.isGLTFSpecularGlossinessMaterial ) {
  718. if ( gltfMaterial.pbrMetallicRoughness.baseColorFactor ) {
  719. gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.diffuseFactor = gltfMaterial.pbrMetallicRoughness.baseColorFactor;
  720. }
  721. var specularFactor = [ 1, 1, 1 ];
  722. material.specular.toArray( specularFactor, 0 );
  723. gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.specularFactor = specularFactor;
  724. gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.glossinessFactor = material.glossiness;
  725. }
  726. // pbrMetallicRoughness.metallicRoughnessTexture
  727. if ( material.metalnessMap || material.roughnessMap ) {
  728. if ( material.metalnessMap === material.roughnessMap ) {
  729. var metalRoughMapDef = { index: processTexture( material.metalnessMap ) };
  730. applyTextureTransform( metalRoughMapDef, material.metalnessMap );
  731. gltfMaterial.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
  732. } else {
  733. console.warn( 'THREE.GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.' );
  734. }
  735. }
  736. // pbrMetallicRoughness.baseColorTexture or pbrSpecularGlossiness diffuseTexture
  737. if ( material.map ) {
  738. var baseColorMapDef = { index: processTexture( material.map ) };
  739. applyTextureTransform( baseColorMapDef, material.map );
  740. if ( material.isGLTFSpecularGlossinessMaterial ) {
  741. gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.diffuseTexture = baseColorMapDef;
  742. }
  743. gltfMaterial.pbrMetallicRoughness.baseColorTexture = baseColorMapDef;
  744. }
  745. // pbrSpecularGlossiness specular map
  746. if ( material.isGLTFSpecularGlossinessMaterial && material.specularMap ) {
  747. var specularMapDef = { index: processTexture( material.specularMap ) };
  748. applyTextureTransform( specularMapDef, material.specularMap );
  749. gltfMaterial.extensions.KHR_materials_pbrSpecularGlossiness.specularGlossinessTexture = specularMapDef;
  750. }
  751. if ( material.emissive ) {
  752. // emissiveFactor
  753. var emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity ).toArray();
  754. if ( ! equalArray( emissive, [ 0, 0, 0 ] ) ) {
  755. gltfMaterial.emissiveFactor = emissive;
  756. }
  757. // emissiveTexture
  758. if ( material.emissiveMap ) {
  759. var emissiveMapDef = { index: processTexture( material.emissiveMap ) };
  760. applyTextureTransform( emissiveMapDef, material.emissiveMap );
  761. gltfMaterial.emissiveTexture = emissiveMapDef;
  762. }
  763. }
  764. // normalTexture
  765. if ( material.normalMap ) {
  766. var normalMapDef = { index: processTexture( material.normalMap ) };
  767. if ( material.normalScale && material.normalScale.x !== - 1 ) {
  768. if ( material.normalScale.x !== material.normalScale.y ) {
  769. console.warn( 'THREE.GLTFExporter: Normal scale components are different, ignoring Y and exporting X.' );
  770. }
  771. normalMapDef.scale = material.normalScale.x;
  772. }
  773. applyTextureTransform( normalMapDef, material.normalMap );
  774. gltfMaterial.normalTexture = normalMapDef;
  775. }
  776. // occlusionTexture
  777. if ( material.aoMap ) {
  778. var occlusionMapDef = {
  779. index: processTexture( material.aoMap ),
  780. texCoord: 1
  781. };
  782. if ( material.aoMapIntensity !== 1.0 ) {
  783. occlusionMapDef.strength = material.aoMapIntensity;
  784. }
  785. applyTextureTransform( occlusionMapDef, material.aoMap );
  786. gltfMaterial.occlusionTexture = occlusionMapDef;
  787. }
  788. // alphaMode
  789. if ( material.transparent ) {
  790. gltfMaterial.alphaMode = 'BLEND';
  791. } else {
  792. if ( material.alphaTest > 0.0 ) {
  793. gltfMaterial.alphaMode = 'MASK';
  794. gltfMaterial.alphaCutoff = material.alphaTest;
  795. }
  796. }
  797. // doubleSided
  798. if ( material.side === THREE.DoubleSide ) {
  799. gltfMaterial.doubleSided = true;
  800. }
  801. if ( material.name !== '' ) {
  802. gltfMaterial.name = material.name;
  803. }
  804. serializeUserData( material, gltfMaterial );
  805. outputJSON.materials.push( gltfMaterial );
  806. var index = outputJSON.materials.length - 1;
  807. cachedData.materials.set( material, index );
  808. return index;
  809. }
  810. /**
  811. * Process mesh
  812. * @param {THREE.Mesh} mesh Mesh to process
  813. * @return {Integer} Index of the processed mesh in the "meshes" array
  814. */
  815. function processMesh( mesh ) {
  816. var meshCacheKeyParts = [ mesh.geometry.uuid ];
  817. if ( Array.isArray( mesh.material ) ) {
  818. for ( var i = 0, l = mesh.material.length; i < l; i ++ ) {
  819. meshCacheKeyParts.push( mesh.material[ i ].uuid );
  820. }
  821. } else {
  822. meshCacheKeyParts.push( mesh.material.uuid );
  823. }
  824. var meshCacheKey = meshCacheKeyParts.join( ':' );
  825. if ( cachedData.meshes.has( meshCacheKey ) ) {
  826. return cachedData.meshes.get( meshCacheKey );
  827. }
  828. var geometry = mesh.geometry;
  829. var mode;
  830. // Use the correct mode
  831. if ( mesh.isLineSegments ) {
  832. mode = WEBGL_CONSTANTS.LINES;
  833. } else if ( mesh.isLineLoop ) {
  834. mode = WEBGL_CONSTANTS.LINE_LOOP;
  835. } else if ( mesh.isLine ) {
  836. mode = WEBGL_CONSTANTS.LINE_STRIP;
  837. } else if ( mesh.isPoints ) {
  838. mode = WEBGL_CONSTANTS.POINTS;
  839. } else {
  840. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
  841. }
  842. if ( ! geometry.isBufferGeometry ) {
  843. console.warn( 'GLTFExporter: Exporting THREE.Geometry will increase file size. Use THREE.BufferGeometry instead.' );
  844. geometry = new THREE.BufferGeometry().setFromObject( mesh );
  845. }
  846. var gltfMesh = {};
  847. var attributes = {};
  848. var primitives = [];
  849. var targets = [];
  850. // Conversion between attributes names in threejs and gltf spec
  851. var nameConversion = {
  852. uv: 'TEXCOORD_0',
  853. uv2: 'TEXCOORD_1',
  854. color: 'COLOR_0',
  855. skinWeight: 'WEIGHTS_0',
  856. skinIndex: 'JOINTS_0'
  857. };
  858. var originalNormal = geometry.getAttribute( 'normal' );
  859. if ( originalNormal !== undefined && ! isNormalizedNormalAttribute( originalNormal ) ) {
  860. console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' );
  861. geometry.setAttribute( 'normal', createNormalizedNormalAttribute( originalNormal ) );
  862. }
  863. // @QUESTION Detect if .vertexColors = true?
  864. // For every attribute create an accessor
  865. var modifiedAttribute = null;
  866. for ( var attributeName in geometry.attributes ) {
  867. // Ignore morph target attributes, which are exported later.
  868. if ( attributeName.substr( 0, 5 ) === 'morph' ) continue;
  869. var attribute = geometry.attributes[ attributeName ];
  870. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
  871. // Prefix all geometry attributes except the ones specifically
  872. // listed in the spec; non-spec attributes are considered custom.
  873. var validVertexAttributes =
  874. /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;
  875. if ( ! validVertexAttributes.test( attributeName ) ) {
  876. attributeName = '_' + attributeName;
  877. }
  878. if ( cachedData.attributes.has( getUID( attribute ) ) ) {
  879. attributes[ attributeName ] = cachedData.attributes.get( getUID( attribute ) );
  880. continue;
  881. }
  882. // JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT.
  883. modifiedAttribute = null;
  884. var array = attribute.array;
  885. if ( attributeName === 'JOINTS_0' &&
  886. ! ( array instanceof Uint16Array ) &&
  887. ! ( array instanceof Uint8Array ) ) {
  888. console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' );
  889. modifiedAttribute = new THREE.BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized );
  890. }
  891. var accessor = processAccessor( modifiedAttribute || attribute, geometry );
  892. if ( accessor !== null ) {
  893. attributes[ attributeName ] = accessor;
  894. cachedData.attributes.set( getUID( attribute ), accessor );
  895. }
  896. }
  897. if ( originalNormal !== undefined ) geometry.setAttribute( 'normal', originalNormal );
  898. // Skip if no exportable attributes found
  899. if ( Object.keys( attributes ).length === 0 ) {
  900. return null;
  901. }
  902. // Morph targets
  903. if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
  904. var weights = [];
  905. var targetNames = [];
  906. var reverseDictionary = {};
  907. if ( mesh.morphTargetDictionary !== undefined ) {
  908. for ( var key in mesh.morphTargetDictionary ) {
  909. reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;
  910. }
  911. }
  912. for ( var i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
  913. var target = {};
  914. var warned = false;
  915. for ( var attributeName in geometry.morphAttributes ) {
  916. // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
  917. // Three.js doesn't support TANGENT yet.
  918. if ( attributeName !== 'position' && attributeName !== 'normal' ) {
  919. if ( ! warned ) {
  920. console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
  921. warned = true;
  922. }
  923. continue;
  924. }
  925. var attribute = geometry.morphAttributes[ attributeName ][ i ];
  926. var gltfAttributeName = attributeName.toUpperCase();
  927. // Three.js morph attribute has absolute values while the one of glTF has relative values.
  928. //
  929. // glTF 2.0 Specification:
  930. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets
  931. var baseAttribute = geometry.attributes[ attributeName ];
  932. if ( cachedData.attributes.has( getUID( attribute ) ) ) {
  933. target[ gltfAttributeName ] = cachedData.attributes.get( getUID( attribute ) );
  934. continue;
  935. }
  936. // Clones attribute not to override
  937. var relativeAttribute = attribute.clone();
  938. if ( ! geometry.morphTargetsRelative ) {
  939. for ( var j = 0, jl = attribute.count; j < jl; j ++ ) {
  940. relativeAttribute.setXYZ(
  941. j,
  942. attribute.getX( j ) - baseAttribute.getX( j ),
  943. attribute.getY( j ) - baseAttribute.getY( j ),
  944. attribute.getZ( j ) - baseAttribute.getZ( j )
  945. );
  946. }
  947. }
  948. target[ gltfAttributeName ] = processAccessor( relativeAttribute, geometry );
  949. cachedData.attributes.set( getUID( baseAttribute ), target[ gltfAttributeName ] );
  950. }
  951. targets.push( target );
  952. weights.push( mesh.morphTargetInfluences[ i ] );
  953. if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
  954. }
  955. gltfMesh.weights = weights;
  956. if ( targetNames.length > 0 ) {
  957. gltfMesh.extras = {};
  958. gltfMesh.extras.targetNames = targetNames;
  959. }
  960. }
  961. var isMultiMaterial = Array.isArray( mesh.material );
  962. if ( isMultiMaterial && geometry.groups.length === 0 ) return null;
  963. var materials = isMultiMaterial ? mesh.material : [ mesh.material ];
  964. var groups = isMultiMaterial ? geometry.groups : [ { materialIndex: 0, start: undefined, count: undefined } ];
  965. for ( var i = 0, il = groups.length; i < il; i ++ ) {
  966. var primitive = {
  967. mode: mode,
  968. attributes: attributes,
  969. };
  970. serializeUserData( geometry, primitive );
  971. if ( targets.length > 0 ) primitive.targets = targets;
  972. if ( geometry.index !== null ) {
  973. var cacheKey = getUID( geometry.index );
  974. if ( groups[ i ].start !== undefined || groups[ i ].count !== undefined ) {
  975. cacheKey += ':' + groups[ i ].start + ':' + groups[ i ].count;
  976. }
  977. if ( cachedData.attributes.has( cacheKey ) ) {
  978. primitive.indices = cachedData.attributes.get( cacheKey );
  979. } else {
  980. primitive.indices = processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
  981. cachedData.attributes.set( cacheKey, primitive.indices );
  982. }
  983. if ( primitive.indices === null ) delete primitive.indices;
  984. }
  985. var material = processMaterial( materials[ groups[ i ].materialIndex ] );
  986. if ( material !== null ) {
  987. primitive.material = material;
  988. }
  989. primitives.push( primitive );
  990. }
  991. gltfMesh.primitives = primitives;
  992. if ( ! outputJSON.meshes ) {
  993. outputJSON.meshes = [];
  994. }
  995. outputJSON.meshes.push( gltfMesh );
  996. var index = outputJSON.meshes.length - 1;
  997. cachedData.meshes.set( meshCacheKey, index );
  998. return index;
  999. }
  1000. /**
  1001. * Process camera
  1002. * @param {THREE.Camera} camera Camera to process
  1003. * @return {Integer} Index of the processed mesh in the "camera" array
  1004. */
  1005. function processCamera( camera ) {
  1006. if ( ! outputJSON.cameras ) {
  1007. outputJSON.cameras = [];
  1008. }
  1009. var isOrtho = camera.isOrthographicCamera;
  1010. var gltfCamera = {
  1011. type: isOrtho ? 'orthographic' : 'perspective'
  1012. };
  1013. if ( isOrtho ) {
  1014. gltfCamera.orthographic = {
  1015. xmag: camera.right * 2,
  1016. ymag: camera.top * 2,
  1017. zfar: camera.far <= 0 ? 0.001 : camera.far,
  1018. znear: camera.near < 0 ? 0 : camera.near
  1019. };
  1020. } else {
  1021. gltfCamera.perspective = {
  1022. aspectRatio: camera.aspect,
  1023. yfov: THREE.MathUtils.degToRad( camera.fov ),
  1024. zfar: camera.far <= 0 ? 0.001 : camera.far,
  1025. znear: camera.near < 0 ? 0 : camera.near
  1026. };
  1027. }
  1028. if ( camera.name !== '' ) {
  1029. gltfCamera.name = camera.type;
  1030. }
  1031. outputJSON.cameras.push( gltfCamera );
  1032. return outputJSON.cameras.length - 1;
  1033. }
  1034. /**
  1035. * Creates glTF animation entry from AnimationClip object.
  1036. *
  1037. * Status:
  1038. * - Only properties listed in PATH_PROPERTIES may be animated.
  1039. *
  1040. * @param {THREE.AnimationClip} clip
  1041. * @param {THREE.Object3D} root
  1042. * @return {number}
  1043. */
  1044. function processAnimation( clip, root ) {
  1045. if ( ! outputJSON.animations ) {
  1046. outputJSON.animations = [];
  1047. }
  1048. clip = THREE.GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root );
  1049. var tracks = clip.tracks;
  1050. var channels = [];
  1051. var samplers = [];
  1052. for ( var i = 0; i < tracks.length; ++ i ) {
  1053. var track = tracks[ i ];
  1054. var trackBinding = THREE.PropertyBinding.parseTrackName( track.name );
  1055. var trackNode = THREE.PropertyBinding.findNode( root, trackBinding.nodeName );
  1056. var trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
  1057. if ( trackBinding.objectName === 'bones' ) {
  1058. if ( trackNode.isSkinnedMesh === true ) {
  1059. trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
  1060. } else {
  1061. trackNode = undefined;
  1062. }
  1063. }
  1064. if ( ! trackNode || ! trackProperty ) {
  1065. console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
  1066. return null;
  1067. }
  1068. var inputItemSize = 1;
  1069. var outputItemSize = track.values.length / track.times.length;
  1070. if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
  1071. outputItemSize /= trackNode.morphTargetInfluences.length;
  1072. }
  1073. var interpolation;
  1074. // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
  1075. // Detecting glTF cubic spline interpolant by checking factory method's special property
  1076. // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
  1077. // valid value from .getInterpolation().
  1078. if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
  1079. interpolation = 'CUBICSPLINE';
  1080. // itemSize of CUBICSPLINE keyframe is 9
  1081. // (VEC3 * 3: inTangent, splineVertex, and outTangent)
  1082. // but needs to be stored as VEC3 so dividing by 3 here.
  1083. outputItemSize /= 3;
  1084. } else if ( track.getInterpolation() === THREE.InterpolateDiscrete ) {
  1085. interpolation = 'STEP';
  1086. } else {
  1087. interpolation = 'LINEAR';
  1088. }
  1089. samplers.push( {
  1090. input: processAccessor( new THREE.BufferAttribute( track.times, inputItemSize ) ),
  1091. output: processAccessor( new THREE.BufferAttribute( track.values, outputItemSize ) ),
  1092. interpolation: interpolation
  1093. } );
  1094. channels.push( {
  1095. sampler: samplers.length - 1,
  1096. target: {
  1097. node: nodeMap.get( trackNode ),
  1098. path: trackProperty
  1099. }
  1100. } );
  1101. }
  1102. outputJSON.animations.push( {
  1103. name: clip.name || 'clip_' + outputJSON.animations.length,
  1104. samplers: samplers,
  1105. channels: channels
  1106. } );
  1107. return outputJSON.animations.length - 1;
  1108. }
  1109. function processSkin( object ) {
  1110. var node = outputJSON.nodes[ nodeMap.get( object ) ];
  1111. var skeleton = object.skeleton;
  1112. if ( skeleton === undefined ) return null;
  1113. var rootJoint = object.skeleton.bones[ 0 ];
  1114. if ( rootJoint === undefined ) return null;
  1115. var joints = [];
  1116. var inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
  1117. for ( var i = 0; i < skeleton.bones.length; ++ i ) {
  1118. joints.push( nodeMap.get( skeleton.bones[ i ] ) );
  1119. skeleton.boneInverses[ i ].toArray( inverseBindMatrices, i * 16 );
  1120. }
  1121. if ( outputJSON.skins === undefined ) {
  1122. outputJSON.skins = [];
  1123. }
  1124. outputJSON.skins.push( {
  1125. inverseBindMatrices: processAccessor( new THREE.BufferAttribute( inverseBindMatrices, 16 ) ),
  1126. joints: joints,
  1127. skeleton: nodeMap.get( rootJoint )
  1128. } );
  1129. var skinIndex = node.skin = outputJSON.skins.length - 1;
  1130. return skinIndex;
  1131. }
  1132. function processLight( light ) {
  1133. var lightDef = {};
  1134. if ( light.name ) lightDef.name = light.name;
  1135. lightDef.color = light.color.toArray();
  1136. lightDef.intensity = light.intensity;
  1137. if ( light.isDirectionalLight ) {
  1138. lightDef.type = 'directional';
  1139. } else if ( light.isPointLight ) {
  1140. lightDef.type = 'point';
  1141. if ( light.distance > 0 ) lightDef.range = light.distance;
  1142. } else if ( light.isSpotLight ) {
  1143. lightDef.type = 'spot';
  1144. if ( light.distance > 0 ) lightDef.range = light.distance;
  1145. lightDef.spot = {};
  1146. lightDef.spot.innerConeAngle = ( light.penumbra - 1.0 ) * light.angle * - 1.0;
  1147. lightDef.spot.outerConeAngle = light.angle;
  1148. }
  1149. if ( light.decay !== undefined && light.decay !== 2 ) {
  1150. console.warn( 'THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, '
  1151. + 'and expects light.decay=2.' );
  1152. }
  1153. if ( light.target
  1154. && ( light.target.parent !== light
  1155. || light.target.position.x !== 0
  1156. || light.target.position.y !== 0
  1157. || light.target.position.z !== - 1 ) ) {
  1158. console.warn( 'THREE.GLTFExporter: Light direction may be lost. For best results, '
  1159. + 'make light.target a child of the light with position 0,0,-1.' );
  1160. }
  1161. var lights = outputJSON.extensions[ 'KHR_lights_punctual' ].lights;
  1162. lights.push( lightDef );
  1163. return lights.length - 1;
  1164. }
  1165. /**
  1166. * Process Object3D node
  1167. * @param {THREE.Object3D} node Object3D to processNode
  1168. * @return {Integer} Index of the node in the nodes list
  1169. */
  1170. function processNode( object ) {
  1171. if ( ! outputJSON.nodes ) {
  1172. outputJSON.nodes = [];
  1173. }
  1174. var gltfNode = {};
  1175. if ( options.trs ) {
  1176. var rotation = object.quaternion.toArray();
  1177. var position = object.position.toArray();
  1178. var scale = object.scale.toArray();
  1179. if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
  1180. gltfNode.rotation = rotation;
  1181. }
  1182. if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
  1183. gltfNode.translation = position;
  1184. }
  1185. if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
  1186. gltfNode.scale = scale;
  1187. }
  1188. } else {
  1189. if ( object.matrixAutoUpdate ) {
  1190. object.updateMatrix();
  1191. }
  1192. if ( isIdentityMatrix( object.matrix ) === false ) {
  1193. gltfNode.matrix = object.matrix.elements;
  1194. }
  1195. }
  1196. // We don't export empty strings name because it represents no-name in Three.js.
  1197. if ( object.name !== '' ) {
  1198. gltfNode.name = String( object.name );
  1199. }
  1200. serializeUserData( object, gltfNode );
  1201. if ( object.isMesh || object.isLine || object.isPoints ) {
  1202. var mesh = processMesh( object );
  1203. if ( mesh !== null ) {
  1204. gltfNode.mesh = mesh;
  1205. }
  1206. } else if ( object.isCamera ) {
  1207. gltfNode.camera = processCamera( object );
  1208. } else if ( object.isDirectionalLight || object.isPointLight || object.isSpotLight ) {
  1209. if ( ! extensionsUsed[ 'KHR_lights_punctual' ] ) {
  1210. outputJSON.extensions = outputJSON.extensions || {};
  1211. outputJSON.extensions[ 'KHR_lights_punctual' ] = { lights: [] };
  1212. extensionsUsed[ 'KHR_lights_punctual' ] = true;
  1213. }
  1214. gltfNode.extensions = gltfNode.extensions || {};
  1215. gltfNode.extensions[ 'KHR_lights_punctual' ] = { light: processLight( object ) };
  1216. } else if ( object.isLight ) {
  1217. console.warn( 'THREE.GLTFExporter: Only directional, point, and spot lights are supported.', object );
  1218. return null;
  1219. }
  1220. if ( object.isSkinnedMesh ) {
  1221. skins.push( object );
  1222. }
  1223. if ( object.children.length > 0 ) {
  1224. var children = [];
  1225. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  1226. var child = object.children[ i ];
  1227. if ( child.visible || options.onlyVisible === false ) {
  1228. var node = processNode( child );
  1229. if ( node !== null ) {
  1230. children.push( node );
  1231. }
  1232. }
  1233. }
  1234. if ( children.length > 0 ) {
  1235. gltfNode.children = children;
  1236. }
  1237. }
  1238. outputJSON.nodes.push( gltfNode );
  1239. var nodeIndex = outputJSON.nodes.length - 1;
  1240. nodeMap.set( object, nodeIndex );
  1241. return nodeIndex;
  1242. }
  1243. /**
  1244. * Process Scene
  1245. * @param {THREE.Scene} node Scene to process
  1246. */
  1247. function processScene( scene ) {
  1248. if ( ! outputJSON.scenes ) {
  1249. outputJSON.scenes = [];
  1250. outputJSON.scene = 0;
  1251. }
  1252. var gltfScene = {};
  1253. if ( scene.name !== '' ) {
  1254. gltfScene.name = scene.name;
  1255. }
  1256. outputJSON.scenes.push( gltfScene );
  1257. var nodes = [];
  1258. for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
  1259. var child = scene.children[ i ];
  1260. if ( child.visible || options.onlyVisible === false ) {
  1261. var node = processNode( child );
  1262. if ( node !== null ) {
  1263. nodes.push( node );
  1264. }
  1265. }
  1266. }
  1267. if ( nodes.length > 0 ) {
  1268. gltfScene.nodes = nodes;
  1269. }
  1270. serializeUserData( scene, gltfScene );
  1271. }
  1272. /**
  1273. * Creates a THREE.Scene to hold a list of objects and parse it
  1274. * @param {Array} objects List of objects to process
  1275. */
  1276. function processObjects( objects ) {
  1277. var scene = new THREE.Scene();
  1278. scene.name = 'AuxScene';
  1279. for ( var i = 0; i < objects.length; i ++ ) {
  1280. // We push directly to children instead of calling `add` to prevent
  1281. // modify the .parent and break its original scene and hierarchy
  1282. scene.children.push( objects[ i ] );
  1283. }
  1284. processScene( scene );
  1285. }
  1286. function processInput( input ) {
  1287. input = input instanceof Array ? input : [ input ];
  1288. var objectsWithoutScene = [];
  1289. for ( var i = 0; i < input.length; i ++ ) {
  1290. if ( input[ i ] instanceof THREE.Scene ) {
  1291. processScene( input[ i ] );
  1292. } else {
  1293. objectsWithoutScene.push( input[ i ] );
  1294. }
  1295. }
  1296. if ( objectsWithoutScene.length > 0 ) {
  1297. processObjects( objectsWithoutScene );
  1298. }
  1299. for ( var i = 0; i < skins.length; ++ i ) {
  1300. processSkin( skins[ i ] );
  1301. }
  1302. for ( var i = 0; i < options.animations.length; ++ i ) {
  1303. processAnimation( options.animations[ i ], input[ 0 ] );
  1304. }
  1305. }
  1306. processInput( input );
  1307. Promise.all( pending ).then( function () {
  1308. // Merge buffers.
  1309. var blob = new Blob( buffers, { type: 'application/octet-stream' } );
  1310. // Declare extensions.
  1311. var extensionsUsedList = Object.keys( extensionsUsed );
  1312. if ( extensionsUsedList.length > 0 ) outputJSON.extensionsUsed = extensionsUsedList;
  1313. // Update bytelength of the single buffer.
  1314. if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) outputJSON.buffers[ 0 ].byteLength = blob.size;
  1315. if ( options.binary === true ) {
  1316. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
  1317. var GLB_HEADER_BYTES = 12;
  1318. var GLB_HEADER_MAGIC = 0x46546C67;
  1319. var GLB_VERSION = 2;
  1320. var GLB_CHUNK_PREFIX_BYTES = 8;
  1321. var GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
  1322. var GLB_CHUNK_TYPE_BIN = 0x004E4942;
  1323. var reader = new window.FileReader();
  1324. reader.readAsArrayBuffer( blob );
  1325. reader.onloadend = function () {
  1326. // Binary chunk.
  1327. var binaryChunk = getPaddedArrayBuffer( reader.result );
  1328. var binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  1329. binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
  1330. binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );
  1331. // JSON chunk.
  1332. var jsonChunk = getPaddedArrayBuffer( stringToArrayBuffer( JSON.stringify( outputJSON ) ), 0x20 );
  1333. var jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  1334. jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
  1335. jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );
  1336. // GLB header.
  1337. var header = new ArrayBuffer( GLB_HEADER_BYTES );
  1338. var headerView = new DataView( header );
  1339. headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
  1340. headerView.setUint32( 4, GLB_VERSION, true );
  1341. var totalByteLength = GLB_HEADER_BYTES
  1342. + jsonChunkPrefix.byteLength + jsonChunk.byteLength
  1343. + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
  1344. headerView.setUint32( 8, totalByteLength, true );
  1345. var glbBlob = new Blob( [
  1346. header,
  1347. jsonChunkPrefix,
  1348. jsonChunk,
  1349. binaryChunkPrefix,
  1350. binaryChunk
  1351. ], { type: 'application/octet-stream' } );
  1352. var glbReader = new window.FileReader();
  1353. glbReader.readAsArrayBuffer( glbBlob );
  1354. glbReader.onloadend = function () {
  1355. onDone( glbReader.result );
  1356. };
  1357. };
  1358. } else {
  1359. if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
  1360. var reader = new window.FileReader();
  1361. reader.readAsDataURL( blob );
  1362. reader.onloadend = function () {
  1363. var base64data = reader.result;
  1364. outputJSON.buffers[ 0 ].uri = base64data;
  1365. onDone( outputJSON );
  1366. };
  1367. } else {
  1368. onDone( outputJSON );
  1369. }
  1370. }
  1371. } );
  1372. }
  1373. };
  1374. THREE.GLTFExporter.Utils = {
  1375. insertKeyframe: function ( track, time ) {
  1376. var tolerance = 0.001; // 1ms
  1377. var valueSize = track.getValueSize();
  1378. var times = new track.TimeBufferType( track.times.length + 1 );
  1379. var values = new track.ValueBufferType( track.values.length + valueSize );
  1380. var interpolant = track.createInterpolant( new track.ValueBufferType( valueSize ) );
  1381. var index;
  1382. if ( track.times.length === 0 ) {
  1383. times[ 0 ] = time;
  1384. for ( var i = 0; i < valueSize; i ++ ) {
  1385. values[ i ] = 0;
  1386. }
  1387. index = 0;
  1388. } else if ( time < track.times[ 0 ] ) {
  1389. if ( Math.abs( track.times[ 0 ] - time ) < tolerance ) return 0;
  1390. times[ 0 ] = time;
  1391. times.set( track.times, 1 );
  1392. values.set( interpolant.evaluate( time ), 0 );
  1393. values.set( track.values, valueSize );
  1394. index = 0;
  1395. } else if ( time > track.times[ track.times.length - 1 ] ) {
  1396. if ( Math.abs( track.times[ track.times.length - 1 ] - time ) < tolerance ) {
  1397. return track.times.length - 1;
  1398. }
  1399. times[ times.length - 1 ] = time;
  1400. times.set( track.times, 0 );
  1401. values.set( track.values, 0 );
  1402. values.set( interpolant.evaluate( time ), track.values.length );
  1403. index = times.length - 1;
  1404. } else {
  1405. for ( var i = 0; i < track.times.length; i ++ ) {
  1406. if ( Math.abs( track.times[ i ] - time ) < tolerance ) return i;
  1407. if ( track.times[ i ] < time && track.times[ i + 1 ] > time ) {
  1408. times.set( track.times.slice( 0, i + 1 ), 0 );
  1409. times[ i + 1 ] = time;
  1410. times.set( track.times.slice( i + 1 ), i + 2 );
  1411. values.set( track.values.slice( 0, ( i + 1 ) * valueSize ), 0 );
  1412. values.set( interpolant.evaluate( time ), ( i + 1 ) * valueSize );
  1413. values.set( track.values.slice( ( i + 1 ) * valueSize ), ( i + 2 ) * valueSize );
  1414. index = i + 1;
  1415. break;
  1416. }
  1417. }
  1418. }
  1419. track.times = times;
  1420. track.values = values;
  1421. return index;
  1422. },
  1423. mergeMorphTargetTracks: function ( clip, root ) {
  1424. var tracks = [];
  1425. var mergedTracks = {};
  1426. var sourceTracks = clip.tracks;
  1427. for ( var i = 0; i < sourceTracks.length; ++ i ) {
  1428. var sourceTrack = sourceTracks[ i ];
  1429. var sourceTrackBinding = THREE.PropertyBinding.parseTrackName( sourceTrack.name );
  1430. var sourceTrackNode = THREE.PropertyBinding.findNode( root, sourceTrackBinding.nodeName );
  1431. if ( sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined ) {
  1432. // Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is.
  1433. tracks.push( sourceTrack );
  1434. continue;
  1435. }
  1436. if ( sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete
  1437. && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear ) {
  1438. if ( sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  1439. // This should never happen, because glTF morph target animations
  1440. // affect all targets already.
  1441. throw new Error( 'THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.' );
  1442. }
  1443. console.warn( 'THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.' );
  1444. sourceTrack = sourceTrack.clone();
  1445. sourceTrack.setInterpolation( THREE.InterpolateLinear );
  1446. }
  1447. var targetCount = sourceTrackNode.morphTargetInfluences.length;
  1448. var targetIndex = sourceTrackNode.morphTargetDictionary[ sourceTrackBinding.propertyIndex ];
  1449. if ( targetIndex === undefined ) {
  1450. throw new Error( 'THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex );
  1451. }
  1452. var mergedTrack;
  1453. // If this is the first time we've seen this object, create a new
  1454. // track to store merged keyframe data for each morph target.
  1455. if ( mergedTracks[ sourceTrackNode.uuid ] === undefined ) {
  1456. mergedTrack = sourceTrack.clone();
  1457. var values = new mergedTrack.ValueBufferType( targetCount * mergedTrack.times.length );
  1458. for ( var j = 0; j < mergedTrack.times.length; j ++ ) {
  1459. values[ j * targetCount + targetIndex ] = mergedTrack.values[ j ];
  1460. }
  1461. // We need to take into consideration the intended target node
  1462. // of our original un-merged morphTarget animation.
  1463. mergedTrack.name = sourceTrackBinding.nodeName + '.morphTargetInfluences';
  1464. mergedTrack.values = values;
  1465. mergedTracks[ sourceTrackNode.uuid ] = mergedTrack;
  1466. tracks.push( mergedTrack );
  1467. continue;
  1468. }
  1469. var sourceInterpolant = sourceTrack.createInterpolant( new sourceTrack.ValueBufferType( 1 ) );
  1470. mergedTrack = mergedTracks[ sourceTrackNode.uuid ];
  1471. // For every existing keyframe of the merged track, write a (possibly
  1472. // interpolated) value from the source track.
  1473. for ( var j = 0; j < mergedTrack.times.length; j ++ ) {
  1474. mergedTrack.values[ j * targetCount + targetIndex ] = sourceInterpolant.evaluate( mergedTrack.times[ j ] );
  1475. }
  1476. // For every existing keyframe of the source track, write a (possibly
  1477. // new) keyframe to the merged track. Values from the previous loop may
  1478. // be written again, but keyframes are de-duplicated.
  1479. for ( var j = 0; j < sourceTrack.times.length; j ++ ) {
  1480. var keyframeIndex = this.insertKeyframe( mergedTrack, sourceTrack.times[ j ] );
  1481. mergedTrack.values[ keyframeIndex * targetCount + targetIndex ] = sourceTrack.values[ j ];
  1482. }
  1483. }
  1484. clip.tracks = tracks;
  1485. return clip;
  1486. }
  1487. };