GLTFExporter.js 57 KB

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