GLTFExporter.js 57 KB

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