GLTFExporter.js 59 KB

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