GLTFExporter.js 56 KB

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