GLTFExporter.js 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163
  1. import {
  2. BufferAttribute,
  3. ClampToEdgeWrapping,
  4. Color,
  5. DoubleSide,
  6. InterpolateDiscrete,
  7. InterpolateLinear,
  8. NoColorSpace,
  9. LinearFilter,
  10. LinearMipmapLinearFilter,
  11. LinearMipmapNearestFilter,
  12. MathUtils,
  13. Matrix4,
  14. MirroredRepeatWrapping,
  15. NearestFilter,
  16. NearestMipmapLinearFilter,
  17. NearestMipmapNearestFilter,
  18. PropertyBinding,
  19. RGBAFormat,
  20. RepeatWrapping,
  21. Scene,
  22. Source,
  23. sRGBEncoding,
  24. CompressedTexture,
  25. Vector3
  26. } from 'three';
  27. import { decompress } from './../utils/TextureUtils.js';
  28. /**
  29. * The KHR_mesh_quantization extension allows these extra attribute component types
  30. *
  31. * @see https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_mesh_quantization/README.md#extending-mesh-attributes
  32. */
  33. const KHR_mesh_quantization_ExtraAttrTypes = {
  34. POSITION: [
  35. 'byte',
  36. 'byte normalized',
  37. 'unsigned byte',
  38. 'unsigned byte normalized',
  39. 'short',
  40. 'short normalized',
  41. 'unsigned short',
  42. 'unsigned short normalized',
  43. ],
  44. NORMAL: [
  45. 'byte normalized',
  46. 'short normalized',
  47. ],
  48. TANGENT: [
  49. 'byte normalized',
  50. 'short normalized',
  51. ],
  52. TEXCOORD: [
  53. 'byte',
  54. 'byte normalized',
  55. 'unsigned byte',
  56. 'short',
  57. 'short normalized',
  58. 'unsigned short',
  59. ],
  60. };
  61. class GLTFExporter {
  62. constructor() {
  63. this.pluginCallbacks = [];
  64. this.register( function ( writer ) {
  65. return new GLTFLightExtension( writer );
  66. } );
  67. this.register( function ( writer ) {
  68. return new GLTFMaterialsUnlitExtension( writer );
  69. } );
  70. this.register( function ( writer ) {
  71. return new GLTFMaterialsTransmissionExtension( writer );
  72. } );
  73. this.register( function ( writer ) {
  74. return new GLTFMaterialsVolumeExtension( writer );
  75. } );
  76. this.register( function ( writer ) {
  77. return new GLTFMaterialsIorExtension( writer );
  78. } );
  79. this.register( function ( writer ) {
  80. return new GLTFMaterialsSpecularExtension( writer );
  81. } );
  82. this.register( function ( writer ) {
  83. return new GLTFMaterialsClearcoatExtension( writer );
  84. } );
  85. this.register( function ( writer ) {
  86. return new GLTFMaterialsIridescenceExtension( writer );
  87. } );
  88. this.register( function ( writer ) {
  89. return new GLTFMaterialsSheenExtension( writer );
  90. } );
  91. this.register( function ( writer ) {
  92. return new GLTFMaterialsAnisotropyExtension( writer );
  93. } );
  94. this.register( function ( writer ) {
  95. return new GLTFMaterialsEmissiveStrengthExtension( writer );
  96. } );
  97. }
  98. register( callback ) {
  99. if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
  100. this.pluginCallbacks.push( callback );
  101. }
  102. return this;
  103. }
  104. unregister( callback ) {
  105. if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
  106. this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
  107. }
  108. return this;
  109. }
  110. /**
  111. * Parse scenes and generate GLTF output
  112. * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes
  113. * @param {Function} onDone Callback on completed
  114. * @param {Function} onError Callback on errors
  115. * @param {Object} options options
  116. */
  117. parse( input, onDone, onError, options ) {
  118. const writer = new GLTFWriter();
  119. const plugins = [];
  120. for ( let i = 0, il = this.pluginCallbacks.length; i < il; i ++ ) {
  121. plugins.push( this.pluginCallbacks[ i ]( writer ) );
  122. }
  123. writer.setPlugins( plugins );
  124. writer.write( input, onDone, options ).catch( onError );
  125. }
  126. parseAsync( input, options ) {
  127. const scope = this;
  128. return new Promise( function ( resolve, reject ) {
  129. scope.parse( input, resolve, reject, options );
  130. } );
  131. }
  132. }
  133. //------------------------------------------------------------------------------
  134. // Constants
  135. //------------------------------------------------------------------------------
  136. const WEBGL_CONSTANTS = {
  137. POINTS: 0x0000,
  138. LINES: 0x0001,
  139. LINE_LOOP: 0x0002,
  140. LINE_STRIP: 0x0003,
  141. TRIANGLES: 0x0004,
  142. TRIANGLE_STRIP: 0x0005,
  143. TRIANGLE_FAN: 0x0006,
  144. BYTE: 0x1400,
  145. UNSIGNED_BYTE: 0x1401,
  146. SHORT: 0x1402,
  147. UNSIGNED_SHORT: 0x1403,
  148. INT: 0x1404,
  149. UNSIGNED_INT: 0x1405,
  150. FLOAT: 0x1406,
  151. ARRAY_BUFFER: 0x8892,
  152. ELEMENT_ARRAY_BUFFER: 0x8893,
  153. NEAREST: 0x2600,
  154. LINEAR: 0x2601,
  155. NEAREST_MIPMAP_NEAREST: 0x2700,
  156. LINEAR_MIPMAP_NEAREST: 0x2701,
  157. NEAREST_MIPMAP_LINEAR: 0x2702,
  158. LINEAR_MIPMAP_LINEAR: 0x2703,
  159. CLAMP_TO_EDGE: 33071,
  160. MIRRORED_REPEAT: 33648,
  161. REPEAT: 10497
  162. };
  163. const KHR_MESH_QUANTIZATION = 'KHR_mesh_quantization';
  164. const THREE_TO_WEBGL = {};
  165. THREE_TO_WEBGL[ NearestFilter ] = WEBGL_CONSTANTS.NEAREST;
  166. THREE_TO_WEBGL[ NearestMipmapNearestFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST;
  167. THREE_TO_WEBGL[ NearestMipmapLinearFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR;
  168. THREE_TO_WEBGL[ LinearFilter ] = WEBGL_CONSTANTS.LINEAR;
  169. THREE_TO_WEBGL[ LinearMipmapNearestFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST;
  170. THREE_TO_WEBGL[ LinearMipmapLinearFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR;
  171. THREE_TO_WEBGL[ ClampToEdgeWrapping ] = WEBGL_CONSTANTS.CLAMP_TO_EDGE;
  172. THREE_TO_WEBGL[ RepeatWrapping ] = WEBGL_CONSTANTS.REPEAT;
  173. THREE_TO_WEBGL[ MirroredRepeatWrapping ] = WEBGL_CONSTANTS.MIRRORED_REPEAT;
  174. const PATH_PROPERTIES = {
  175. scale: 'scale',
  176. position: 'translation',
  177. quaternion: 'rotation',
  178. morphTargetInfluences: 'weights'
  179. };
  180. const DEFAULT_SPECULAR_COLOR = new Color();
  181. // GLB constants
  182. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
  183. const GLB_HEADER_BYTES = 12;
  184. const GLB_HEADER_MAGIC = 0x46546C67;
  185. const GLB_VERSION = 2;
  186. const GLB_CHUNK_PREFIX_BYTES = 8;
  187. const GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
  188. const GLB_CHUNK_TYPE_BIN = 0x004E4942;
  189. //------------------------------------------------------------------------------
  190. // Utility functions
  191. //------------------------------------------------------------------------------
  192. /**
  193. * Compare two arrays
  194. * @param {Array} array1 Array 1 to compare
  195. * @param {Array} array2 Array 2 to compare
  196. * @return {Boolean} Returns true if both arrays are equal
  197. */
  198. function equalArray( array1, array2 ) {
  199. return ( array1.length === array2.length ) && array1.every( function ( element, index ) {
  200. return element === array2[ index ];
  201. } );
  202. }
  203. /**
  204. * Converts a string to an ArrayBuffer.
  205. * @param {string} text
  206. * @return {ArrayBuffer}
  207. */
  208. function stringToArrayBuffer( text ) {
  209. return new TextEncoder().encode( text ).buffer;
  210. }
  211. /**
  212. * Is identity matrix
  213. *
  214. * @param {Matrix4} matrix
  215. * @returns {Boolean} Returns true, if parameter is identity matrix
  216. */
  217. function isIdentityMatrix( matrix ) {
  218. return equalArray( matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] );
  219. }
  220. /**
  221. * Get the min and max vectors from the given attribute
  222. * @param {BufferAttribute} attribute Attribute to find the min/max in range from start to start + count
  223. * @param {Integer} start
  224. * @param {Integer} count
  225. * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
  226. */
  227. function getMinMax( attribute, start, count ) {
  228. const output = {
  229. min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
  230. max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
  231. };
  232. for ( let i = start; i < start + count; i ++ ) {
  233. for ( let a = 0; a < attribute.itemSize; a ++ ) {
  234. let value;
  235. if ( attribute.itemSize > 4 ) {
  236. // no support for interleaved data for itemSize > 4
  237. value = attribute.array[ i * attribute.itemSize + a ];
  238. } else {
  239. if ( a === 0 ) value = attribute.getX( i );
  240. else if ( a === 1 ) value = attribute.getY( i );
  241. else if ( a === 2 ) value = attribute.getZ( i );
  242. else if ( a === 3 ) value = attribute.getW( i );
  243. if ( attribute.normalized === true ) {
  244. value = MathUtils.normalize( value, attribute.array );
  245. }
  246. }
  247. output.min[ a ] = Math.min( output.min[ a ], value );
  248. output.max[ a ] = Math.max( output.max[ a ], value );
  249. }
  250. }
  251. return output;
  252. }
  253. /**
  254. * Get the required size + padding for a buffer, rounded to the next 4-byte boundary.
  255. * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
  256. *
  257. * @param {Integer} bufferSize The size the original buffer.
  258. * @returns {Integer} new buffer size with required padding.
  259. *
  260. */
  261. function getPaddedBufferSize( bufferSize ) {
  262. return Math.ceil( bufferSize / 4 ) * 4;
  263. }
  264. /**
  265. * Returns a buffer aligned to 4-byte boundary.
  266. *
  267. * @param {ArrayBuffer} arrayBuffer Buffer to pad
  268. * @param {Integer} paddingByte (Optional)
  269. * @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer
  270. */
  271. function getPaddedArrayBuffer( arrayBuffer, paddingByte = 0 ) {
  272. const paddedLength = getPaddedBufferSize( arrayBuffer.byteLength );
  273. if ( paddedLength !== arrayBuffer.byteLength ) {
  274. const array = new Uint8Array( paddedLength );
  275. array.set( new Uint8Array( arrayBuffer ) );
  276. if ( paddingByte !== 0 ) {
  277. for ( let i = arrayBuffer.byteLength; i < paddedLength; i ++ ) {
  278. array[ i ] = paddingByte;
  279. }
  280. }
  281. return array.buffer;
  282. }
  283. return arrayBuffer;
  284. }
  285. function getCanvas() {
  286. if ( typeof document === 'undefined' && typeof OffscreenCanvas !== 'undefined' ) {
  287. return new OffscreenCanvas( 1, 1 );
  288. }
  289. return document.createElement( 'canvas' );
  290. }
  291. function getToBlobPromise( canvas, mimeType ) {
  292. if ( canvas.toBlob !== undefined ) {
  293. return new Promise( ( resolve ) => canvas.toBlob( resolve, mimeType ) );
  294. }
  295. let quality;
  296. // Blink's implementation of convertToBlob seems to default to a quality level of 100%
  297. // Use the Blink default quality levels of toBlob instead so that file sizes are comparable.
  298. if ( mimeType === 'image/jpeg' ) {
  299. quality = 0.92;
  300. } else if ( mimeType === 'image/webp' ) {
  301. quality = 0.8;
  302. }
  303. return canvas.convertToBlob( {
  304. type: mimeType,
  305. quality: quality
  306. } );
  307. }
  308. /**
  309. * Writer
  310. */
  311. class GLTFWriter {
  312. constructor() {
  313. this.plugins = [];
  314. this.options = {};
  315. this.pending = [];
  316. this.buffers = [];
  317. this.byteOffset = 0;
  318. this.buffers = [];
  319. this.nodeMap = new Map();
  320. this.skins = [];
  321. this.extensionsUsed = {};
  322. this.extensionsRequired = {};
  323. this.uids = new Map();
  324. this.uid = 0;
  325. this.json = {
  326. asset: {
  327. version: '2.0',
  328. generator: 'THREE.GLTFExporter'
  329. }
  330. };
  331. this.cache = {
  332. meshes: new Map(),
  333. attributes: new Map(),
  334. attributesNormalized: new Map(),
  335. materials: new Map(),
  336. textures: new Map(),
  337. images: new Map()
  338. };
  339. }
  340. setPlugins( plugins ) {
  341. this.plugins = plugins;
  342. }
  343. /**
  344. * Parse scenes and generate GLTF output
  345. * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes
  346. * @param {Function} onDone Callback on completed
  347. * @param {Object} options options
  348. */
  349. async write( input, onDone, options = {} ) {
  350. this.options = Object.assign( {
  351. // default options
  352. binary: false,
  353. trs: false,
  354. onlyVisible: true,
  355. maxTextureSize: Infinity,
  356. animations: [],
  357. includeCustomExtensions: false
  358. }, options );
  359. if ( this.options.animations.length > 0 ) {
  360. // Only TRS properties, and not matrices, may be targeted by animation.
  361. this.options.trs = true;
  362. }
  363. this.processInput( input );
  364. await Promise.all( this.pending );
  365. const writer = this;
  366. const buffers = writer.buffers;
  367. const json = writer.json;
  368. options = writer.options;
  369. const extensionsUsed = writer.extensionsUsed;
  370. const extensionsRequired = writer.extensionsRequired;
  371. // Merge buffers.
  372. const blob = new Blob( buffers, { type: 'application/octet-stream' } );
  373. // Declare extensions.
  374. const extensionsUsedList = Object.keys( extensionsUsed );
  375. const extensionsRequiredList = Object.keys( extensionsRequired );
  376. if ( extensionsUsedList.length > 0 ) json.extensionsUsed = extensionsUsedList;
  377. if ( extensionsRequiredList.length > 0 ) json.extensionsRequired = extensionsRequiredList;
  378. // Update bytelength of the single buffer.
  379. if ( json.buffers && json.buffers.length > 0 ) json.buffers[ 0 ].byteLength = blob.size;
  380. if ( options.binary === true ) {
  381. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
  382. const reader = new FileReader();
  383. reader.readAsArrayBuffer( blob );
  384. reader.onloadend = function () {
  385. // Binary chunk.
  386. const binaryChunk = getPaddedArrayBuffer( reader.result );
  387. const binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  388. binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
  389. binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );
  390. // JSON chunk.
  391. const jsonChunk = getPaddedArrayBuffer( stringToArrayBuffer( JSON.stringify( json ) ), 0x20 );
  392. const jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  393. jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
  394. jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );
  395. // GLB header.
  396. const header = new ArrayBuffer( GLB_HEADER_BYTES );
  397. const headerView = new DataView( header );
  398. headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
  399. headerView.setUint32( 4, GLB_VERSION, true );
  400. const totalByteLength = GLB_HEADER_BYTES
  401. + jsonChunkPrefix.byteLength + jsonChunk.byteLength
  402. + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
  403. headerView.setUint32( 8, totalByteLength, true );
  404. const glbBlob = new Blob( [
  405. header,
  406. jsonChunkPrefix,
  407. jsonChunk,
  408. binaryChunkPrefix,
  409. binaryChunk
  410. ], { type: 'application/octet-stream' } );
  411. const glbReader = new FileReader();
  412. glbReader.readAsArrayBuffer( glbBlob );
  413. glbReader.onloadend = function () {
  414. onDone( glbReader.result );
  415. };
  416. };
  417. } else {
  418. if ( json.buffers && json.buffers.length > 0 ) {
  419. const reader = new FileReader();
  420. reader.readAsDataURL( blob );
  421. reader.onloadend = function () {
  422. const base64data = reader.result;
  423. json.buffers[ 0 ].uri = base64data;
  424. onDone( json );
  425. };
  426. } else {
  427. onDone( json );
  428. }
  429. }
  430. }
  431. /**
  432. * Serializes a userData.
  433. *
  434. * @param {THREE.Object3D|THREE.Material} object
  435. * @param {Object} objectDef
  436. */
  437. serializeUserData( object, objectDef ) {
  438. if ( Object.keys( object.userData ).length === 0 ) return;
  439. const options = this.options;
  440. const extensionsUsed = this.extensionsUsed;
  441. try {
  442. const json = JSON.parse( JSON.stringify( object.userData ) );
  443. if ( options.includeCustomExtensions && json.gltfExtensions ) {
  444. if ( objectDef.extensions === undefined ) objectDef.extensions = {};
  445. for ( const extensionName in json.gltfExtensions ) {
  446. objectDef.extensions[ extensionName ] = json.gltfExtensions[ extensionName ];
  447. extensionsUsed[ extensionName ] = true;
  448. }
  449. delete json.gltfExtensions;
  450. }
  451. if ( Object.keys( json ).length > 0 ) objectDef.extras = json;
  452. } catch ( error ) {
  453. console.warn( 'THREE.GLTFExporter: userData of \'' + object.name + '\' ' +
  454. 'won\'t be serialized because of JSON.stringify error - ' + error.message );
  455. }
  456. }
  457. /**
  458. * Returns ids for buffer attributes.
  459. * @param {Object} object
  460. * @return {Integer}
  461. */
  462. getUID( attribute, isRelativeCopy = false ) {
  463. if ( this.uids.has( attribute ) === false ) {
  464. const uids = new Map();
  465. uids.set( true, this.uid ++ );
  466. uids.set( false, this.uid ++ );
  467. this.uids.set( attribute, uids );
  468. }
  469. const uids = this.uids.get( attribute );
  470. return uids.get( isRelativeCopy );
  471. }
  472. /**
  473. * Checks if normal attribute values are normalized.
  474. *
  475. * @param {BufferAttribute} normal
  476. * @returns {Boolean}
  477. */
  478. isNormalizedNormalAttribute( normal ) {
  479. const cache = this.cache;
  480. if ( cache.attributesNormalized.has( normal ) ) return false;
  481. const v = new Vector3();
  482. for ( let i = 0, il = normal.count; i < il; i ++ ) {
  483. // 0.0005 is from glTF-validator
  484. if ( Math.abs( v.fromBufferAttribute( normal, i ).length() - 1.0 ) > 0.0005 ) return false;
  485. }
  486. return true;
  487. }
  488. /**
  489. * Creates normalized normal buffer attribute.
  490. *
  491. * @param {BufferAttribute} normal
  492. * @returns {BufferAttribute}
  493. *
  494. */
  495. createNormalizedNormalAttribute( normal ) {
  496. const cache = this.cache;
  497. if ( cache.attributesNormalized.has( normal ) ) return cache.attributesNormalized.get( normal );
  498. const attribute = normal.clone();
  499. const v = new Vector3();
  500. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  501. v.fromBufferAttribute( attribute, i );
  502. if ( v.x === 0 && v.y === 0 && v.z === 0 ) {
  503. // if values can't be normalized set (1, 0, 0)
  504. v.setX( 1.0 );
  505. } else {
  506. v.normalize();
  507. }
  508. attribute.setXYZ( i, v.x, v.y, v.z );
  509. }
  510. cache.attributesNormalized.set( normal, attribute );
  511. return attribute;
  512. }
  513. /**
  514. * Applies a texture transform, if present, to the map definition. Requires
  515. * the KHR_texture_transform extension.
  516. *
  517. * @param {Object} mapDef
  518. * @param {THREE.Texture} texture
  519. */
  520. applyTextureTransform( mapDef, texture ) {
  521. let didTransform = false;
  522. const transformDef = {};
  523. if ( texture.offset.x !== 0 || texture.offset.y !== 0 ) {
  524. transformDef.offset = texture.offset.toArray();
  525. didTransform = true;
  526. }
  527. if ( texture.rotation !== 0 ) {
  528. transformDef.rotation = texture.rotation;
  529. didTransform = true;
  530. }
  531. if ( texture.repeat.x !== 1 || texture.repeat.y !== 1 ) {
  532. transformDef.scale = texture.repeat.toArray();
  533. didTransform = true;
  534. }
  535. if ( didTransform ) {
  536. mapDef.extensions = mapDef.extensions || {};
  537. mapDef.extensions[ 'KHR_texture_transform' ] = transformDef;
  538. this.extensionsUsed[ 'KHR_texture_transform' ] = true;
  539. }
  540. }
  541. buildMetalRoughTexture( metalnessMap, roughnessMap ) {
  542. if ( metalnessMap === roughnessMap ) return metalnessMap;
  543. function getEncodingConversion( map ) {
  544. if ( map.colorSpace === SRGBColorSpace ) {
  545. return function SRGBToLinear( c ) {
  546. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  547. };
  548. }
  549. return function LinearToLinear( c ) {
  550. return c;
  551. };
  552. }
  553. console.warn( 'THREE.GLTFExporter: Merged metalnessMap and roughnessMap textures.' );
  554. if ( metalnessMap instanceof CompressedTexture ) {
  555. metalnessMap = decompress( metalnessMap );
  556. }
  557. if ( roughnessMap instanceof CompressedTexture ) {
  558. roughnessMap = decompress( roughnessMap );
  559. }
  560. const metalness = metalnessMap?.image;
  561. const roughness = roughnessMap?.image;
  562. const width = Math.max( metalness ? metalness.width : 0, roughness ? roughness.width : 0 );
  563. const height = Math.max( metalness ? metalness.height : 0, roughness ? roughness.height : 0 );
  564. const canvas = getCanvas();
  565. canvas.width = width;
  566. canvas.height = height;
  567. const context = canvas.getContext( '2d' );
  568. context.fillStyle = '#00ffff';
  569. context.fillRect( 0, 0, width, height );
  570. const composite = context.getImageData( 0, 0, width, height );
  571. if ( metalness ) {
  572. context.drawImage( metalness, 0, 0, width, height );
  573. const convert = getEncodingConversion( metalnessMap );
  574. const data = context.getImageData( 0, 0, width, height ).data;
  575. for ( let i = 2; i < data.length; i += 4 ) {
  576. composite.data[ i ] = convert( data[ i ] / 256 ) * 256;
  577. }
  578. }
  579. if ( roughness ) {
  580. context.drawImage( roughness, 0, 0, width, height );
  581. const convert = getEncodingConversion( roughnessMap );
  582. const data = context.getImageData( 0, 0, width, height ).data;
  583. for ( let i = 1; i < data.length; i += 4 ) {
  584. composite.data[ i ] = convert( data[ i ] / 256 ) * 256;
  585. }
  586. }
  587. context.putImageData( composite, 0, 0 );
  588. //
  589. const reference = metalnessMap || roughnessMap;
  590. const texture = reference.clone();
  591. texture.source = new Source( canvas );
  592. texture.colorSpace = NoColorSpace;
  593. texture.channel = ( metalnessMap || roughnessMap ).channel;
  594. if ( metalnessMap && roughnessMap && metalnessMap.channel !== roughnessMap.channel ) {
  595. console.warn( 'THREE.GLTFExporter: UV channels for metalnessMap and roughnessMap textures must match.' );
  596. }
  597. return texture;
  598. }
  599. /**
  600. * Process a buffer to append to the default one.
  601. * @param {ArrayBuffer} buffer
  602. * @return {Integer}
  603. */
  604. processBuffer( buffer ) {
  605. const json = this.json;
  606. const buffers = this.buffers;
  607. if ( ! json.buffers ) json.buffers = [ { byteLength: 0 } ];
  608. // All buffers are merged before export.
  609. buffers.push( buffer );
  610. return 0;
  611. }
  612. /**
  613. * Process and generate a BufferView
  614. * @param {BufferAttribute} attribute
  615. * @param {number} componentType
  616. * @param {number} start
  617. * @param {number} count
  618. * @param {number} target (Optional) Target usage of the BufferView
  619. * @return {Object}
  620. */
  621. processBufferView( attribute, componentType, start, count, target ) {
  622. const json = this.json;
  623. if ( ! json.bufferViews ) json.bufferViews = [];
  624. // Create a new dataview and dump the attribute's array into it
  625. let componentSize;
  626. switch ( componentType ) {
  627. case WEBGL_CONSTANTS.BYTE:
  628. case WEBGL_CONSTANTS.UNSIGNED_BYTE:
  629. componentSize = 1;
  630. break;
  631. case WEBGL_CONSTANTS.SHORT:
  632. case WEBGL_CONSTANTS.UNSIGNED_SHORT:
  633. componentSize = 2;
  634. break;
  635. default:
  636. componentSize = 4;
  637. }
  638. const byteLength = getPaddedBufferSize( count * attribute.itemSize * componentSize );
  639. const dataView = new DataView( new ArrayBuffer( byteLength ) );
  640. let offset = 0;
  641. for ( let i = start; i < start + count; i ++ ) {
  642. for ( let a = 0; a < attribute.itemSize; a ++ ) {
  643. let value;
  644. if ( attribute.itemSize > 4 ) {
  645. // no support for interleaved data for itemSize > 4
  646. value = attribute.array[ i * attribute.itemSize + a ];
  647. } else {
  648. if ( a === 0 ) value = attribute.getX( i );
  649. else if ( a === 1 ) value = attribute.getY( i );
  650. else if ( a === 2 ) value = attribute.getZ( i );
  651. else if ( a === 3 ) value = attribute.getW( i );
  652. if ( attribute.normalized === true ) {
  653. value = MathUtils.normalize( value, attribute.array );
  654. }
  655. }
  656. if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
  657. dataView.setFloat32( offset, value, true );
  658. } else if ( componentType === WEBGL_CONSTANTS.INT ) {
  659. dataView.setInt32( offset, value, true );
  660. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
  661. dataView.setUint32( offset, value, true );
  662. } else if ( componentType === WEBGL_CONSTANTS.SHORT ) {
  663. dataView.setInt16( offset, value, true );
  664. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  665. dataView.setUint16( offset, value, true );
  666. } else if ( componentType === WEBGL_CONSTANTS.BYTE ) {
  667. dataView.setInt8( offset, value );
  668. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
  669. dataView.setUint8( offset, value );
  670. }
  671. offset += componentSize;
  672. }
  673. }
  674. const bufferViewDef = {
  675. buffer: this.processBuffer( dataView.buffer ),
  676. byteOffset: this.byteOffset,
  677. byteLength: byteLength
  678. };
  679. if ( target !== undefined ) bufferViewDef.target = target;
  680. if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
  681. // Only define byteStride for vertex attributes.
  682. bufferViewDef.byteStride = attribute.itemSize * componentSize;
  683. }
  684. this.byteOffset += byteLength;
  685. json.bufferViews.push( bufferViewDef );
  686. // @TODO Merge bufferViews where possible.
  687. const output = {
  688. id: json.bufferViews.length - 1,
  689. byteLength: 0
  690. };
  691. return output;
  692. }
  693. /**
  694. * Process and generate a BufferView from an image Blob.
  695. * @param {Blob} blob
  696. * @return {Promise<Integer>}
  697. */
  698. processBufferViewImage( blob ) {
  699. const writer = this;
  700. const json = writer.json;
  701. if ( ! json.bufferViews ) json.bufferViews = [];
  702. return new Promise( function ( resolve ) {
  703. const reader = new FileReader();
  704. reader.readAsArrayBuffer( blob );
  705. reader.onloadend = function () {
  706. const buffer = getPaddedArrayBuffer( reader.result );
  707. const bufferViewDef = {
  708. buffer: writer.processBuffer( buffer ),
  709. byteOffset: writer.byteOffset,
  710. byteLength: buffer.byteLength
  711. };
  712. writer.byteOffset += buffer.byteLength;
  713. resolve( json.bufferViews.push( bufferViewDef ) - 1 );
  714. };
  715. } );
  716. }
  717. /**
  718. * Process attribute to generate an accessor
  719. * @param {BufferAttribute} attribute Attribute to process
  720. * @param {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range
  721. * @param {Integer} start (Optional)
  722. * @param {Integer} count (Optional)
  723. * @return {Integer|null} Index of the processed accessor on the "accessors" array
  724. */
  725. processAccessor( attribute, geometry, start, count ) {
  726. const json = this.json;
  727. const types = {
  728. 1: 'SCALAR',
  729. 2: 'VEC2',
  730. 3: 'VEC3',
  731. 4: 'VEC4',
  732. 9: 'MAT3',
  733. 16: 'MAT4'
  734. };
  735. let componentType;
  736. // Detect the component type of the attribute array
  737. if ( attribute.array.constructor === Float32Array ) {
  738. componentType = WEBGL_CONSTANTS.FLOAT;
  739. } else if ( attribute.array.constructor === Int32Array ) {
  740. componentType = WEBGL_CONSTANTS.INT;
  741. } else if ( attribute.array.constructor === Uint32Array ) {
  742. componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
  743. } else if ( attribute.array.constructor === Int16Array ) {
  744. componentType = WEBGL_CONSTANTS.SHORT;
  745. } else if ( attribute.array.constructor === Uint16Array ) {
  746. componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
  747. } else if ( attribute.array.constructor === Int8Array ) {
  748. componentType = WEBGL_CONSTANTS.BYTE;
  749. } else if ( attribute.array.constructor === Uint8Array ) {
  750. componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE;
  751. } else {
  752. throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type: ' + attribute.array.constructor );
  753. }
  754. if ( start === undefined ) start = 0;
  755. if ( count === undefined ) count = attribute.count;
  756. // Skip creating an accessor if the attribute doesn't have data to export
  757. if ( count === 0 ) return null;
  758. const minMax = getMinMax( attribute, start, count );
  759. let bufferViewTarget;
  760. // If geometry isn't provided, don't infer the target usage of the bufferView. For
  761. // animation samplers, target must not be set.
  762. if ( geometry !== undefined ) {
  763. bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER;
  764. }
  765. const bufferView = this.processBufferView( attribute, componentType, start, count, bufferViewTarget );
  766. const accessorDef = {
  767. bufferView: bufferView.id,
  768. byteOffset: bufferView.byteOffset,
  769. componentType: componentType,
  770. count: count,
  771. max: minMax.max,
  772. min: minMax.min,
  773. type: types[ attribute.itemSize ]
  774. };
  775. if ( attribute.normalized === true ) accessorDef.normalized = true;
  776. if ( ! json.accessors ) json.accessors = [];
  777. return json.accessors.push( accessorDef ) - 1;
  778. }
  779. /**
  780. * Process image
  781. * @param {Image} image to process
  782. * @param {Integer} format of the image (RGBAFormat)
  783. * @param {Boolean} flipY before writing out the image
  784. * @param {String} mimeType export format
  785. * @return {Integer} Index of the processed texture in the "images" array
  786. */
  787. processImage( image, format, flipY, mimeType = 'image/png' ) {
  788. if ( image !== null ) {
  789. const writer = this;
  790. const cache = writer.cache;
  791. const json = writer.json;
  792. const options = writer.options;
  793. const pending = writer.pending;
  794. if ( ! cache.images.has( image ) ) cache.images.set( image, {} );
  795. const cachedImages = cache.images.get( image );
  796. const key = mimeType + ':flipY/' + flipY.toString();
  797. if ( cachedImages[ key ] !== undefined ) return cachedImages[ key ];
  798. if ( ! json.images ) json.images = [];
  799. const imageDef = { mimeType: mimeType };
  800. const canvas = getCanvas();
  801. canvas.width = Math.min( image.width, options.maxTextureSize );
  802. canvas.height = Math.min( image.height, options.maxTextureSize );
  803. const ctx = canvas.getContext( '2d' );
  804. if ( flipY === true ) {
  805. ctx.translate( 0, canvas.height );
  806. ctx.scale( 1, - 1 );
  807. }
  808. if ( image.data !== undefined ) { // THREE.DataTexture
  809. if ( format !== RGBAFormat ) {
  810. console.error( 'GLTFExporter: Only RGBAFormat is supported.', image );
  811. }
  812. if ( image.width > options.maxTextureSize || image.height > options.maxTextureSize ) {
  813. console.warn( 'GLTFExporter: Image size is bigger than maxTextureSize', image );
  814. }
  815. const data = new Uint8ClampedArray( image.height * image.width * 4 );
  816. for ( let i = 0; i < data.length; i += 4 ) {
  817. data[ i + 0 ] = image.data[ i + 0 ];
  818. data[ i + 1 ] = image.data[ i + 1 ];
  819. data[ i + 2 ] = image.data[ i + 2 ];
  820. data[ i + 3 ] = image.data[ i + 3 ];
  821. }
  822. ctx.putImageData( new ImageData( data, image.width, image.height ), 0, 0 );
  823. } else {
  824. ctx.drawImage( image, 0, 0, canvas.width, canvas.height );
  825. }
  826. if ( options.binary === true ) {
  827. pending.push(
  828. getToBlobPromise( canvas, mimeType )
  829. .then( blob => writer.processBufferViewImage( blob ) )
  830. .then( bufferViewIndex => {
  831. imageDef.bufferView = bufferViewIndex;
  832. } )
  833. );
  834. } else {
  835. if ( canvas.toDataURL !== undefined ) {
  836. imageDef.uri = canvas.toDataURL( mimeType );
  837. } else {
  838. pending.push(
  839. getToBlobPromise( canvas, mimeType )
  840. .then( blob => new FileReader().readAsDataURL( blob ) )
  841. .then( dataURL => {
  842. imageDef.uri = dataURL;
  843. } )
  844. );
  845. }
  846. }
  847. const index = json.images.push( imageDef ) - 1;
  848. cachedImages[ key ] = index;
  849. return index;
  850. } else {
  851. throw new Error( 'THREE.GLTFExporter: No valid image data found. Unable to process texture.' );
  852. }
  853. }
  854. /**
  855. * Process sampler
  856. * @param {Texture} map Texture to process
  857. * @return {Integer} Index of the processed texture in the "samplers" array
  858. */
  859. processSampler( map ) {
  860. const json = this.json;
  861. if ( ! json.samplers ) json.samplers = [];
  862. const samplerDef = {
  863. magFilter: THREE_TO_WEBGL[ map.magFilter ],
  864. minFilter: THREE_TO_WEBGL[ map.minFilter ],
  865. wrapS: THREE_TO_WEBGL[ map.wrapS ],
  866. wrapT: THREE_TO_WEBGL[ map.wrapT ]
  867. };
  868. return json.samplers.push( samplerDef ) - 1;
  869. }
  870. /**
  871. * Process texture
  872. * @param {Texture} map Map to process
  873. * @return {Integer} Index of the processed texture in the "textures" array
  874. */
  875. processTexture( map ) {
  876. const writer = this;
  877. const options = writer.options;
  878. const cache = this.cache;
  879. const json = this.json;
  880. if ( cache.textures.has( map ) ) return cache.textures.get( map );
  881. if ( ! json.textures ) json.textures = [];
  882. // make non-readable textures (e.g. CompressedTexture) readable by blitting them into a new texture
  883. if ( map instanceof CompressedTexture ) {
  884. map = decompress( map, options.maxTextureSize );
  885. // remove from cache, as the underlaying canvas is always the same between decompressed textures
  886. cache.images.delete( map.image );
  887. }
  888. let mimeType = map.userData.mimeType;
  889. if ( mimeType === 'image/webp' ) mimeType = 'image/png';
  890. const textureDef = {
  891. sampler: this.processSampler( map ),
  892. source: this.processImage( map.image, map.format, map.flipY, mimeType )
  893. };
  894. if ( map.name ) textureDef.name = map.name;
  895. this._invokeAll( function ( ext ) {
  896. ext.writeTexture && ext.writeTexture( map, textureDef );
  897. } );
  898. const index = json.textures.push( textureDef ) - 1;
  899. cache.textures.set( map, index );
  900. return index;
  901. }
  902. /**
  903. * Process material
  904. * @param {THREE.Material} material Material to process
  905. * @return {Integer|null} Index of the processed material in the "materials" array
  906. */
  907. processMaterial( material ) {
  908. const cache = this.cache;
  909. const json = this.json;
  910. if ( cache.materials.has( material ) ) return cache.materials.get( material );
  911. if ( material.isShaderMaterial ) {
  912. console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
  913. return null;
  914. }
  915. if ( ! json.materials ) json.materials = [];
  916. // @QUESTION Should we avoid including any attribute that has the default value?
  917. const materialDef = { pbrMetallicRoughness: {} };
  918. if ( material.isMeshStandardMaterial !== true && material.isMeshBasicMaterial !== true ) {
  919. console.warn( 'GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.' );
  920. }
  921. // pbrMetallicRoughness.baseColorFactor
  922. const color = material.color.toArray().concat( [ material.opacity ] );
  923. if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
  924. materialDef.pbrMetallicRoughness.baseColorFactor = color;
  925. }
  926. if ( material.isMeshStandardMaterial ) {
  927. materialDef.pbrMetallicRoughness.metallicFactor = material.metalness;
  928. materialDef.pbrMetallicRoughness.roughnessFactor = material.roughness;
  929. } else {
  930. materialDef.pbrMetallicRoughness.metallicFactor = 0.5;
  931. materialDef.pbrMetallicRoughness.roughnessFactor = 0.5;
  932. }
  933. // pbrMetallicRoughness.metallicRoughnessTexture
  934. if ( material.metalnessMap || material.roughnessMap ) {
  935. const metalRoughTexture = this.buildMetalRoughTexture( material.metalnessMap, material.roughnessMap );
  936. const metalRoughMapDef = {
  937. index: this.processTexture( metalRoughTexture ),
  938. channel: metalRoughTexture.channel
  939. };
  940. this.applyTextureTransform( metalRoughMapDef, metalRoughTexture );
  941. materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
  942. }
  943. // pbrMetallicRoughness.baseColorTexture
  944. if ( material.map ) {
  945. const baseColorMapDef = {
  946. index: this.processTexture( material.map ),
  947. texCoord: material.map.channel
  948. };
  949. this.applyTextureTransform( baseColorMapDef, material.map );
  950. materialDef.pbrMetallicRoughness.baseColorTexture = baseColorMapDef;
  951. }
  952. if ( material.emissive ) {
  953. const emissive = material.emissive;
  954. const maxEmissiveComponent = Math.max( emissive.r, emissive.g, emissive.b );
  955. if ( maxEmissiveComponent > 0 ) {
  956. materialDef.emissiveFactor = material.emissive.toArray();
  957. }
  958. // emissiveTexture
  959. if ( material.emissiveMap ) {
  960. const emissiveMapDef = {
  961. index: this.processTexture( material.emissiveMap ),
  962. texCoord: material.emissiveMap.channel
  963. };
  964. this.applyTextureTransform( emissiveMapDef, material.emissiveMap );
  965. materialDef.emissiveTexture = emissiveMapDef;
  966. }
  967. }
  968. // normalTexture
  969. if ( material.normalMap ) {
  970. const normalMapDef = {
  971. index: this.processTexture( material.normalMap ),
  972. texCoord: material.normalMap.channel
  973. };
  974. if ( material.normalScale && material.normalScale.x !== 1 ) {
  975. // glTF normal scale is univariate. Ignore `y`, which may be flipped.
  976. // Context: https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  977. normalMapDef.scale = material.normalScale.x;
  978. }
  979. this.applyTextureTransform( normalMapDef, material.normalMap );
  980. materialDef.normalTexture = normalMapDef;
  981. }
  982. // occlusionTexture
  983. if ( material.aoMap ) {
  984. const occlusionMapDef = {
  985. index: this.processTexture( material.aoMap ),
  986. texCoord: material.aoMap.channel
  987. };
  988. if ( material.aoMapIntensity !== 1.0 ) {
  989. occlusionMapDef.strength = material.aoMapIntensity;
  990. }
  991. this.applyTextureTransform( occlusionMapDef, material.aoMap );
  992. materialDef.occlusionTexture = occlusionMapDef;
  993. }
  994. // alphaMode
  995. if ( material.transparent ) {
  996. materialDef.alphaMode = 'BLEND';
  997. } else {
  998. if ( material.alphaTest > 0.0 ) {
  999. materialDef.alphaMode = 'MASK';
  1000. materialDef.alphaCutoff = material.alphaTest;
  1001. }
  1002. }
  1003. // doubleSided
  1004. if ( material.side === DoubleSide ) materialDef.doubleSided = true;
  1005. if ( material.name !== '' ) materialDef.name = material.name;
  1006. this.serializeUserData( material, materialDef );
  1007. this._invokeAll( function ( ext ) {
  1008. ext.writeMaterial && ext.writeMaterial( material, materialDef );
  1009. } );
  1010. const index = json.materials.push( materialDef ) - 1;
  1011. cache.materials.set( material, index );
  1012. return index;
  1013. }
  1014. /**
  1015. * Process mesh
  1016. * @param {THREE.Mesh} mesh Mesh to process
  1017. * @return {Integer|null} Index of the processed mesh in the "meshes" array
  1018. */
  1019. processMesh( mesh ) {
  1020. const cache = this.cache;
  1021. const json = this.json;
  1022. const meshCacheKeyParts = [ mesh.geometry.uuid ];
  1023. if ( Array.isArray( mesh.material ) ) {
  1024. for ( let i = 0, l = mesh.material.length; i < l; i ++ ) {
  1025. meshCacheKeyParts.push( mesh.material[ i ].uuid );
  1026. }
  1027. } else {
  1028. meshCacheKeyParts.push( mesh.material.uuid );
  1029. }
  1030. const meshCacheKey = meshCacheKeyParts.join( ':' );
  1031. if ( cache.meshes.has( meshCacheKey ) ) return cache.meshes.get( meshCacheKey );
  1032. const geometry = mesh.geometry;
  1033. let mode;
  1034. // Use the correct mode
  1035. if ( mesh.isLineSegments ) {
  1036. mode = WEBGL_CONSTANTS.LINES;
  1037. } else if ( mesh.isLineLoop ) {
  1038. mode = WEBGL_CONSTANTS.LINE_LOOP;
  1039. } else if ( mesh.isLine ) {
  1040. mode = WEBGL_CONSTANTS.LINE_STRIP;
  1041. } else if ( mesh.isPoints ) {
  1042. mode = WEBGL_CONSTANTS.POINTS;
  1043. } else {
  1044. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
  1045. }
  1046. const meshDef = {};
  1047. const attributes = {};
  1048. const primitives = [];
  1049. const targets = [];
  1050. // Conversion between attributes names in threejs and gltf spec
  1051. const nameConversion = {
  1052. uv: 'TEXCOORD_0',
  1053. uv1: 'TEXCOORD_1',
  1054. color: 'COLOR_0',
  1055. skinWeight: 'WEIGHTS_0',
  1056. skinIndex: 'JOINTS_0'
  1057. };
  1058. const originalNormal = geometry.getAttribute( 'normal' );
  1059. if ( originalNormal !== undefined && ! this.isNormalizedNormalAttribute( originalNormal ) ) {
  1060. console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' );
  1061. geometry.setAttribute( 'normal', this.createNormalizedNormalAttribute( originalNormal ) );
  1062. }
  1063. // @QUESTION Detect if .vertexColors = true?
  1064. // For every attribute create an accessor
  1065. let modifiedAttribute = null;
  1066. for ( let attributeName in geometry.attributes ) {
  1067. // Ignore morph target attributes, which are exported later.
  1068. if ( attributeName.slice( 0, 5 ) === 'morph' ) continue;
  1069. const attribute = geometry.attributes[ attributeName ];
  1070. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
  1071. // Prefix all geometry attributes except the ones specifically
  1072. // listed in the spec; non-spec attributes are considered custom.
  1073. const validVertexAttributes =
  1074. /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;
  1075. if ( ! validVertexAttributes.test( attributeName ) ) attributeName = '_' + attributeName;
  1076. if ( cache.attributes.has( this.getUID( attribute ) ) ) {
  1077. attributes[ attributeName ] = cache.attributes.get( this.getUID( attribute ) );
  1078. continue;
  1079. }
  1080. // JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT.
  1081. modifiedAttribute = null;
  1082. const array = attribute.array;
  1083. if ( attributeName === 'JOINTS_0' &&
  1084. ! ( array instanceof Uint16Array ) &&
  1085. ! ( array instanceof Uint8Array ) ) {
  1086. console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' );
  1087. modifiedAttribute = new BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized );
  1088. }
  1089. const accessor = this.processAccessor( modifiedAttribute || attribute, geometry );
  1090. if ( accessor !== null ) {
  1091. if ( ! attributeName.startsWith( '_' ) ) {
  1092. this.detectMeshQuantization( attributeName, attribute );
  1093. }
  1094. attributes[ attributeName ] = accessor;
  1095. cache.attributes.set( this.getUID( attribute ), accessor );
  1096. }
  1097. }
  1098. if ( originalNormal !== undefined ) geometry.setAttribute( 'normal', originalNormal );
  1099. // Skip if no exportable attributes found
  1100. if ( Object.keys( attributes ).length === 0 ) return null;
  1101. // Morph targets
  1102. if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
  1103. const weights = [];
  1104. const targetNames = [];
  1105. const reverseDictionary = {};
  1106. if ( mesh.morphTargetDictionary !== undefined ) {
  1107. for ( const key in mesh.morphTargetDictionary ) {
  1108. reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;
  1109. }
  1110. }
  1111. for ( let i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
  1112. const target = {};
  1113. let warned = false;
  1114. for ( const attributeName in geometry.morphAttributes ) {
  1115. // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
  1116. // Three.js doesn't support TANGENT yet.
  1117. if ( attributeName !== 'position' && attributeName !== 'normal' ) {
  1118. if ( ! warned ) {
  1119. console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
  1120. warned = true;
  1121. }
  1122. continue;
  1123. }
  1124. const attribute = geometry.morphAttributes[ attributeName ][ i ];
  1125. const gltfAttributeName = attributeName.toUpperCase();
  1126. // Three.js morph attribute has absolute values while the one of glTF has relative values.
  1127. //
  1128. // glTF 2.0 Specification:
  1129. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets
  1130. const baseAttribute = geometry.attributes[ attributeName ];
  1131. if ( cache.attributes.has( this.getUID( attribute, true ) ) ) {
  1132. target[ gltfAttributeName ] = cache.attributes.get( this.getUID( attribute, true ) );
  1133. continue;
  1134. }
  1135. // Clones attribute not to override
  1136. const relativeAttribute = attribute.clone();
  1137. if ( ! geometry.morphTargetsRelative ) {
  1138. for ( let j = 0, jl = attribute.count; j < jl; j ++ ) {
  1139. for ( let a = 0; a < attribute.itemSize; a ++ ) {
  1140. if ( a === 0 ) relativeAttribute.setX( j, attribute.getX( j ) - baseAttribute.getX( j ) );
  1141. if ( a === 1 ) relativeAttribute.setY( j, attribute.getY( j ) - baseAttribute.getY( j ) );
  1142. if ( a === 2 ) relativeAttribute.setZ( j, attribute.getZ( j ) - baseAttribute.getZ( j ) );
  1143. if ( a === 3 ) relativeAttribute.setW( j, attribute.getW( j ) - baseAttribute.getW( j ) );
  1144. }
  1145. }
  1146. }
  1147. target[ gltfAttributeName ] = this.processAccessor( relativeAttribute, geometry );
  1148. cache.attributes.set( this.getUID( baseAttribute, true ), target[ gltfAttributeName ] );
  1149. }
  1150. targets.push( target );
  1151. weights.push( mesh.morphTargetInfluences[ i ] );
  1152. if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
  1153. }
  1154. meshDef.weights = weights;
  1155. if ( targetNames.length > 0 ) {
  1156. meshDef.extras = {};
  1157. meshDef.extras.targetNames = targetNames;
  1158. }
  1159. }
  1160. const isMultiMaterial = Array.isArray( mesh.material );
  1161. if ( isMultiMaterial && geometry.groups.length === 0 ) return null;
  1162. const materials = isMultiMaterial ? mesh.material : [ mesh.material ];
  1163. const groups = isMultiMaterial ? geometry.groups : [ { materialIndex: 0, start: undefined, count: undefined } ];
  1164. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  1165. const primitive = {
  1166. mode: mode,
  1167. attributes: attributes,
  1168. };
  1169. this.serializeUserData( geometry, primitive );
  1170. if ( targets.length > 0 ) primitive.targets = targets;
  1171. if ( geometry.index !== null ) {
  1172. let cacheKey = this.getUID( geometry.index );
  1173. if ( groups[ i ].start !== undefined || groups[ i ].count !== undefined ) {
  1174. cacheKey += ':' + groups[ i ].start + ':' + groups[ i ].count;
  1175. }
  1176. if ( cache.attributes.has( cacheKey ) ) {
  1177. primitive.indices = cache.attributes.get( cacheKey );
  1178. } else {
  1179. primitive.indices = this.processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
  1180. cache.attributes.set( cacheKey, primitive.indices );
  1181. }
  1182. if ( primitive.indices === null ) delete primitive.indices;
  1183. }
  1184. const material = this.processMaterial( materials[ groups[ i ].materialIndex ] );
  1185. if ( material !== null ) primitive.material = material;
  1186. primitives.push( primitive );
  1187. }
  1188. meshDef.primitives = primitives;
  1189. if ( ! json.meshes ) json.meshes = [];
  1190. this._invokeAll( function ( ext ) {
  1191. ext.writeMesh && ext.writeMesh( mesh, meshDef );
  1192. } );
  1193. const index = json.meshes.push( meshDef ) - 1;
  1194. cache.meshes.set( meshCacheKey, index );
  1195. return index;
  1196. }
  1197. /**
  1198. * If a vertex attribute with a
  1199. * [non-standard data type](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview)
  1200. * is used, it is checked whether it is a valid data type according to the
  1201. * [KHR_mesh_quantization](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_mesh_quantization/README.md)
  1202. * extension.
  1203. * In this case the extension is automatically added to the list of used extensions.
  1204. *
  1205. * @param {string} attributeName
  1206. * @param {THREE.BufferAttribute} attribute
  1207. */
  1208. detectMeshQuantization( attributeName, attribute ) {
  1209. if ( this.extensionsUsed[ KHR_MESH_QUANTIZATION ] ) return;
  1210. let attrType = undefined;
  1211. switch ( attribute.array.constructor ) {
  1212. case Int8Array:
  1213. attrType = 'byte';
  1214. break;
  1215. case Uint8Array:
  1216. attrType = 'unsigned byte';
  1217. break;
  1218. case Int16Array:
  1219. attrType = 'short';
  1220. break;
  1221. case Uint16Array:
  1222. attrType = 'unsigned short';
  1223. break;
  1224. default:
  1225. return;
  1226. }
  1227. if ( attribute.normalized ) attrType += ' normalized';
  1228. const attrNamePrefix = attributeName.split( '_', 1 )[ 0 ];
  1229. if ( KHR_mesh_quantization_ExtraAttrTypes[ attrNamePrefix ] && KHR_mesh_quantization_ExtraAttrTypes[ attrNamePrefix ].includes( attrType ) ) {
  1230. this.extensionsUsed[ KHR_MESH_QUANTIZATION ] = true;
  1231. this.extensionsRequired[ KHR_MESH_QUANTIZATION ] = true;
  1232. }
  1233. }
  1234. /**
  1235. * Process camera
  1236. * @param {THREE.Camera} camera Camera to process
  1237. * @return {Integer} Index of the processed mesh in the "camera" array
  1238. */
  1239. processCamera( camera ) {
  1240. const json = this.json;
  1241. if ( ! json.cameras ) json.cameras = [];
  1242. const isOrtho = camera.isOrthographicCamera;
  1243. const cameraDef = {
  1244. type: isOrtho ? 'orthographic' : 'perspective'
  1245. };
  1246. if ( isOrtho ) {
  1247. cameraDef.orthographic = {
  1248. xmag: camera.right * 2,
  1249. ymag: camera.top * 2,
  1250. zfar: camera.far <= 0 ? 0.001 : camera.far,
  1251. znear: camera.near < 0 ? 0 : camera.near
  1252. };
  1253. } else {
  1254. cameraDef.perspective = {
  1255. aspectRatio: camera.aspect,
  1256. yfov: MathUtils.degToRad( camera.fov ),
  1257. zfar: camera.far <= 0 ? 0.001 : camera.far,
  1258. znear: camera.near < 0 ? 0 : camera.near
  1259. };
  1260. }
  1261. // Question: Is saving "type" as name intentional?
  1262. if ( camera.name !== '' ) cameraDef.name = camera.type;
  1263. return json.cameras.push( cameraDef ) - 1;
  1264. }
  1265. /**
  1266. * Creates glTF animation entry from AnimationClip object.
  1267. *
  1268. * Status:
  1269. * - Only properties listed in PATH_PROPERTIES may be animated.
  1270. *
  1271. * @param {THREE.AnimationClip} clip
  1272. * @param {THREE.Object3D} root
  1273. * @return {number|null}
  1274. */
  1275. processAnimation( clip, root ) {
  1276. const json = this.json;
  1277. const nodeMap = this.nodeMap;
  1278. if ( ! json.animations ) json.animations = [];
  1279. clip = GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root );
  1280. const tracks = clip.tracks;
  1281. const channels = [];
  1282. const samplers = [];
  1283. for ( let i = 0; i < tracks.length; ++ i ) {
  1284. const track = tracks[ i ];
  1285. const trackBinding = PropertyBinding.parseTrackName( track.name );
  1286. let trackNode = PropertyBinding.findNode( root, trackBinding.nodeName );
  1287. const trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
  1288. if ( trackBinding.objectName === 'bones' ) {
  1289. if ( trackNode.isSkinnedMesh === true ) {
  1290. trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
  1291. } else {
  1292. trackNode = undefined;
  1293. }
  1294. }
  1295. if ( ! trackNode || ! trackProperty ) {
  1296. console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
  1297. return null;
  1298. }
  1299. const inputItemSize = 1;
  1300. let outputItemSize = track.values.length / track.times.length;
  1301. if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
  1302. outputItemSize /= trackNode.morphTargetInfluences.length;
  1303. }
  1304. let interpolation;
  1305. // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
  1306. // Detecting glTF cubic spline interpolant by checking factory method's special property
  1307. // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
  1308. // valid value from .getInterpolation().
  1309. if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
  1310. interpolation = 'CUBICSPLINE';
  1311. // itemSize of CUBICSPLINE keyframe is 9
  1312. // (VEC3 * 3: inTangent, splineVertex, and outTangent)
  1313. // but needs to be stored as VEC3 so dividing by 3 here.
  1314. outputItemSize /= 3;
  1315. } else if ( track.getInterpolation() === InterpolateDiscrete ) {
  1316. interpolation = 'STEP';
  1317. } else {
  1318. interpolation = 'LINEAR';
  1319. }
  1320. samplers.push( {
  1321. input: this.processAccessor( new BufferAttribute( track.times, inputItemSize ) ),
  1322. output: this.processAccessor( new BufferAttribute( track.values, outputItemSize ) ),
  1323. interpolation: interpolation
  1324. } );
  1325. channels.push( {
  1326. sampler: samplers.length - 1,
  1327. target: {
  1328. node: nodeMap.get( trackNode ),
  1329. path: trackProperty
  1330. }
  1331. } );
  1332. }
  1333. json.animations.push( {
  1334. name: clip.name || 'clip_' + json.animations.length,
  1335. samplers: samplers,
  1336. channels: channels
  1337. } );
  1338. return json.animations.length - 1;
  1339. }
  1340. /**
  1341. * @param {THREE.Object3D} object
  1342. * @return {number|null}
  1343. */
  1344. processSkin( object ) {
  1345. const json = this.json;
  1346. const nodeMap = this.nodeMap;
  1347. const node = json.nodes[ nodeMap.get( object ) ];
  1348. const skeleton = object.skeleton;
  1349. if ( skeleton === undefined ) return null;
  1350. const rootJoint = object.skeleton.bones[ 0 ];
  1351. if ( rootJoint === undefined ) return null;
  1352. const joints = [];
  1353. const inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
  1354. const temporaryBoneInverse = new Matrix4();
  1355. for ( let i = 0; i < skeleton.bones.length; ++ i ) {
  1356. joints.push( nodeMap.get( skeleton.bones[ i ] ) );
  1357. temporaryBoneInverse.copy( skeleton.boneInverses[ i ] );
  1358. temporaryBoneInverse.multiply( object.bindMatrix ).toArray( inverseBindMatrices, i * 16 );
  1359. }
  1360. if ( json.skins === undefined ) json.skins = [];
  1361. json.skins.push( {
  1362. inverseBindMatrices: this.processAccessor( new BufferAttribute( inverseBindMatrices, 16 ) ),
  1363. joints: joints,
  1364. skeleton: nodeMap.get( rootJoint )
  1365. } );
  1366. const skinIndex = node.skin = json.skins.length - 1;
  1367. return skinIndex;
  1368. }
  1369. /**
  1370. * Process Object3D node
  1371. * @param {THREE.Object3D} node Object3D to processNode
  1372. * @return {Integer} Index of the node in the nodes list
  1373. */
  1374. processNode( object ) {
  1375. const json = this.json;
  1376. const options = this.options;
  1377. const nodeMap = this.nodeMap;
  1378. if ( ! json.nodes ) json.nodes = [];
  1379. const nodeDef = {};
  1380. if ( options.trs ) {
  1381. const rotation = object.quaternion.toArray();
  1382. const position = object.position.toArray();
  1383. const scale = object.scale.toArray();
  1384. if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
  1385. nodeDef.rotation = rotation;
  1386. }
  1387. if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
  1388. nodeDef.translation = position;
  1389. }
  1390. if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
  1391. nodeDef.scale = scale;
  1392. }
  1393. } else {
  1394. if ( object.matrixAutoUpdate ) {
  1395. object.updateMatrix();
  1396. }
  1397. if ( isIdentityMatrix( object.matrix ) === false ) {
  1398. nodeDef.matrix = object.matrix.elements;
  1399. }
  1400. }
  1401. // We don't export empty strings name because it represents no-name in Three.js.
  1402. if ( object.name !== '' ) nodeDef.name = String( object.name );
  1403. this.serializeUserData( object, nodeDef );
  1404. if ( object.isMesh || object.isLine || object.isPoints ) {
  1405. const meshIndex = this.processMesh( object );
  1406. if ( meshIndex !== null ) nodeDef.mesh = meshIndex;
  1407. } else if ( object.isCamera ) {
  1408. nodeDef.camera = this.processCamera( object );
  1409. }
  1410. if ( object.isSkinnedMesh ) this.skins.push( object );
  1411. if ( object.children.length > 0 ) {
  1412. const children = [];
  1413. for ( let i = 0, l = object.children.length; i < l; i ++ ) {
  1414. const child = object.children[ i ];
  1415. if ( child.visible || options.onlyVisible === false ) {
  1416. const nodeIndex = this.processNode( child );
  1417. if ( nodeIndex !== null ) children.push( nodeIndex );
  1418. }
  1419. }
  1420. if ( children.length > 0 ) nodeDef.children = children;
  1421. }
  1422. this._invokeAll( function ( ext ) {
  1423. ext.writeNode && ext.writeNode( object, nodeDef );
  1424. } );
  1425. const nodeIndex = json.nodes.push( nodeDef ) - 1;
  1426. nodeMap.set( object, nodeIndex );
  1427. return nodeIndex;
  1428. }
  1429. /**
  1430. * Process Scene
  1431. * @param {Scene} node Scene to process
  1432. */
  1433. processScene( scene ) {
  1434. const json = this.json;
  1435. const options = this.options;
  1436. if ( ! json.scenes ) {
  1437. json.scenes = [];
  1438. json.scene = 0;
  1439. }
  1440. const sceneDef = {};
  1441. if ( scene.name !== '' ) sceneDef.name = scene.name;
  1442. json.scenes.push( sceneDef );
  1443. const nodes = [];
  1444. for ( let i = 0, l = scene.children.length; i < l; i ++ ) {
  1445. const child = scene.children[ i ];
  1446. if ( child.visible || options.onlyVisible === false ) {
  1447. const nodeIndex = this.processNode( child );
  1448. if ( nodeIndex !== null ) nodes.push( nodeIndex );
  1449. }
  1450. }
  1451. if ( nodes.length > 0 ) sceneDef.nodes = nodes;
  1452. this.serializeUserData( scene, sceneDef );
  1453. }
  1454. /**
  1455. * Creates a Scene to hold a list of objects and parse it
  1456. * @param {Array} objects List of objects to process
  1457. */
  1458. processObjects( objects ) {
  1459. const scene = new Scene();
  1460. scene.name = 'AuxScene';
  1461. for ( let i = 0; i < objects.length; i ++ ) {
  1462. // We push directly to children instead of calling `add` to prevent
  1463. // modify the .parent and break its original scene and hierarchy
  1464. scene.children.push( objects[ i ] );
  1465. }
  1466. this.processScene( scene );
  1467. }
  1468. /**
  1469. * @param {THREE.Object3D|Array<THREE.Object3D>} input
  1470. */
  1471. processInput( input ) {
  1472. const options = this.options;
  1473. input = input instanceof Array ? input : [ input ];
  1474. this._invokeAll( function ( ext ) {
  1475. ext.beforeParse && ext.beforeParse( input );
  1476. } );
  1477. const objectsWithoutScene = [];
  1478. for ( let i = 0; i < input.length; i ++ ) {
  1479. if ( input[ i ] instanceof Scene ) {
  1480. this.processScene( input[ i ] );
  1481. } else {
  1482. objectsWithoutScene.push( input[ i ] );
  1483. }
  1484. }
  1485. if ( objectsWithoutScene.length > 0 ) this.processObjects( objectsWithoutScene );
  1486. for ( let i = 0; i < this.skins.length; ++ i ) {
  1487. this.processSkin( this.skins[ i ] );
  1488. }
  1489. for ( let i = 0; i < options.animations.length; ++ i ) {
  1490. this.processAnimation( options.animations[ i ], input[ 0 ] );
  1491. }
  1492. this._invokeAll( function ( ext ) {
  1493. ext.afterParse && ext.afterParse( input );
  1494. } );
  1495. }
  1496. _invokeAll( func ) {
  1497. for ( let i = 0, il = this.plugins.length; i < il; i ++ ) {
  1498. func( this.plugins[ i ] );
  1499. }
  1500. }
  1501. }
  1502. /**
  1503. * Punctual Lights Extension
  1504. *
  1505. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  1506. */
  1507. class GLTFLightExtension {
  1508. constructor( writer ) {
  1509. this.writer = writer;
  1510. this.name = 'KHR_lights_punctual';
  1511. }
  1512. writeNode( light, nodeDef ) {
  1513. if ( ! light.isLight ) return;
  1514. if ( ! light.isDirectionalLight && ! light.isPointLight && ! light.isSpotLight ) {
  1515. console.warn( 'THREE.GLTFExporter: Only directional, point, and spot lights are supported.', light );
  1516. return;
  1517. }
  1518. const writer = this.writer;
  1519. const json = writer.json;
  1520. const extensionsUsed = writer.extensionsUsed;
  1521. const lightDef = {};
  1522. if ( light.name ) lightDef.name = light.name;
  1523. lightDef.color = light.color.toArray();
  1524. lightDef.intensity = light.intensity;
  1525. if ( light.isDirectionalLight ) {
  1526. lightDef.type = 'directional';
  1527. } else if ( light.isPointLight ) {
  1528. lightDef.type = 'point';
  1529. if ( light.distance > 0 ) lightDef.range = light.distance;
  1530. } else if ( light.isSpotLight ) {
  1531. lightDef.type = 'spot';
  1532. if ( light.distance > 0 ) lightDef.range = light.distance;
  1533. lightDef.spot = {};
  1534. lightDef.spot.innerConeAngle = ( light.penumbra - 1.0 ) * light.angle * - 1.0;
  1535. lightDef.spot.outerConeAngle = light.angle;
  1536. }
  1537. if ( light.decay !== undefined && light.decay !== 2 ) {
  1538. console.warn( 'THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, '
  1539. + 'and expects light.decay=2.' );
  1540. }
  1541. if ( light.target
  1542. && ( light.target.parent !== light
  1543. || light.target.position.x !== 0
  1544. || light.target.position.y !== 0
  1545. || light.target.position.z !== - 1 ) ) {
  1546. console.warn( 'THREE.GLTFExporter: Light direction may be lost. For best results, '
  1547. + 'make light.target a child of the light with position 0,0,-1.' );
  1548. }
  1549. if ( ! extensionsUsed[ this.name ] ) {
  1550. json.extensions = json.extensions || {};
  1551. json.extensions[ this.name ] = { lights: [] };
  1552. extensionsUsed[ this.name ] = true;
  1553. }
  1554. const lights = json.extensions[ this.name ].lights;
  1555. lights.push( lightDef );
  1556. nodeDef.extensions = nodeDef.extensions || {};
  1557. nodeDef.extensions[ this.name ] = { light: lights.length - 1 };
  1558. }
  1559. }
  1560. /**
  1561. * Unlit Materials Extension
  1562. *
  1563. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  1564. */
  1565. class GLTFMaterialsUnlitExtension {
  1566. constructor( writer ) {
  1567. this.writer = writer;
  1568. this.name = 'KHR_materials_unlit';
  1569. }
  1570. writeMaterial( material, materialDef ) {
  1571. if ( ! material.isMeshBasicMaterial ) return;
  1572. const writer = this.writer;
  1573. const extensionsUsed = writer.extensionsUsed;
  1574. materialDef.extensions = materialDef.extensions || {};
  1575. materialDef.extensions[ this.name ] = {};
  1576. extensionsUsed[ this.name ] = true;
  1577. materialDef.pbrMetallicRoughness.metallicFactor = 0.0;
  1578. materialDef.pbrMetallicRoughness.roughnessFactor = 0.9;
  1579. }
  1580. }
  1581. /**
  1582. * Clearcoat Materials Extension
  1583. *
  1584. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  1585. */
  1586. class GLTFMaterialsClearcoatExtension {
  1587. constructor( writer ) {
  1588. this.writer = writer;
  1589. this.name = 'KHR_materials_clearcoat';
  1590. }
  1591. writeMaterial( material, materialDef ) {
  1592. if ( ! material.isMeshPhysicalMaterial || material.clearcoat === 0 ) return;
  1593. const writer = this.writer;
  1594. const extensionsUsed = writer.extensionsUsed;
  1595. const extensionDef = {};
  1596. extensionDef.clearcoatFactor = material.clearcoat;
  1597. if ( material.clearcoatMap ) {
  1598. const clearcoatMapDef = {
  1599. index: writer.processTexture( material.clearcoatMap ),
  1600. texCoord: material.clearcoatMap.channel
  1601. };
  1602. writer.applyTextureTransform( clearcoatMapDef, material.clearcoatMap );
  1603. extensionDef.clearcoatTexture = clearcoatMapDef;
  1604. }
  1605. extensionDef.clearcoatRoughnessFactor = material.clearcoatRoughness;
  1606. if ( material.clearcoatRoughnessMap ) {
  1607. const clearcoatRoughnessMapDef = {
  1608. index: writer.processTexture( material.clearcoatRoughnessMap ),
  1609. texCoord: material.clearcoatRoughnessMap.channel
  1610. };
  1611. writer.applyTextureTransform( clearcoatRoughnessMapDef, material.clearcoatRoughnessMap );
  1612. extensionDef.clearcoatRoughnessTexture = clearcoatRoughnessMapDef;
  1613. }
  1614. if ( material.clearcoatNormalMap ) {
  1615. const clearcoatNormalMapDef = {
  1616. index: writer.processTexture( material.clearcoatNormalMap ),
  1617. texCoord: material.clearcoatNormalMap.channel
  1618. };
  1619. writer.applyTextureTransform( clearcoatNormalMapDef, material.clearcoatNormalMap );
  1620. extensionDef.clearcoatNormalTexture = clearcoatNormalMapDef;
  1621. }
  1622. materialDef.extensions = materialDef.extensions || {};
  1623. materialDef.extensions[ this.name ] = extensionDef;
  1624. extensionsUsed[ this.name ] = true;
  1625. }
  1626. }
  1627. /**
  1628. * Iridescence Materials Extension
  1629. *
  1630. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence
  1631. */
  1632. class GLTFMaterialsIridescenceExtension {
  1633. constructor( writer ) {
  1634. this.writer = writer;
  1635. this.name = 'KHR_materials_iridescence';
  1636. }
  1637. writeMaterial( material, materialDef ) {
  1638. if ( ! material.isMeshPhysicalMaterial || material.iridescence === 0 ) return;
  1639. const writer = this.writer;
  1640. const extensionsUsed = writer.extensionsUsed;
  1641. const extensionDef = {};
  1642. extensionDef.iridescenceFactor = material.iridescence;
  1643. if ( material.iridescenceMap ) {
  1644. const iridescenceMapDef = {
  1645. index: writer.processTexture( material.iridescenceMap ),
  1646. texCoord: material.iridescenceMap.channel
  1647. };
  1648. writer.applyTextureTransform( iridescenceMapDef, material.iridescenceMap );
  1649. extensionDef.iridescenceTexture = iridescenceMapDef;
  1650. }
  1651. extensionDef.iridescenceIor = material.iridescenceIOR;
  1652. extensionDef.iridescenceThicknessMinimum = material.iridescenceThicknessRange[ 0 ];
  1653. extensionDef.iridescenceThicknessMaximum = material.iridescenceThicknessRange[ 1 ];
  1654. if ( material.iridescenceThicknessMap ) {
  1655. const iridescenceThicknessMapDef = {
  1656. index: writer.processTexture( material.iridescenceThicknessMap ),
  1657. texCoord: material.iridescenceThicknessMap.channel
  1658. };
  1659. writer.applyTextureTransform( iridescenceThicknessMapDef, material.iridescenceThicknessMap );
  1660. extensionDef.iridescenceThicknessTexture = iridescenceThicknessMapDef;
  1661. }
  1662. materialDef.extensions = materialDef.extensions || {};
  1663. materialDef.extensions[ this.name ] = extensionDef;
  1664. extensionsUsed[ this.name ] = true;
  1665. }
  1666. }
  1667. /**
  1668. * Transmission Materials Extension
  1669. *
  1670. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  1671. */
  1672. class GLTFMaterialsTransmissionExtension {
  1673. constructor( writer ) {
  1674. this.writer = writer;
  1675. this.name = 'KHR_materials_transmission';
  1676. }
  1677. writeMaterial( material, materialDef ) {
  1678. if ( ! material.isMeshPhysicalMaterial || material.transmission === 0 ) return;
  1679. const writer = this.writer;
  1680. const extensionsUsed = writer.extensionsUsed;
  1681. const extensionDef = {};
  1682. extensionDef.transmissionFactor = material.transmission;
  1683. if ( material.transmissionMap ) {
  1684. const transmissionMapDef = {
  1685. index: writer.processTexture( material.transmissionMap ),
  1686. texCoord: material.transmissionMap.channel
  1687. };
  1688. writer.applyTextureTransform( transmissionMapDef, material.transmissionMap );
  1689. extensionDef.transmissionTexture = transmissionMapDef;
  1690. }
  1691. materialDef.extensions = materialDef.extensions || {};
  1692. materialDef.extensions[ this.name ] = extensionDef;
  1693. extensionsUsed[ this.name ] = true;
  1694. }
  1695. }
  1696. /**
  1697. * Materials Volume Extension
  1698. *
  1699. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume
  1700. */
  1701. class GLTFMaterialsVolumeExtension {
  1702. constructor( writer ) {
  1703. this.writer = writer;
  1704. this.name = 'KHR_materials_volume';
  1705. }
  1706. writeMaterial( material, materialDef ) {
  1707. if ( ! material.isMeshPhysicalMaterial || material.transmission === 0 ) return;
  1708. const writer = this.writer;
  1709. const extensionsUsed = writer.extensionsUsed;
  1710. const extensionDef = {};
  1711. extensionDef.thicknessFactor = material.thickness;
  1712. if ( material.thicknessMap ) {
  1713. const thicknessMapDef = {
  1714. index: writer.processTexture( material.thicknessMap ),
  1715. texCoord: material.thicknessMap.channel
  1716. };
  1717. writer.applyTextureTransform( thicknessMapDef, material.thicknessMap );
  1718. extensionDef.thicknessTexture = thicknessMapDef;
  1719. }
  1720. extensionDef.attenuationDistance = material.attenuationDistance;
  1721. extensionDef.attenuationColor = material.attenuationColor.toArray();
  1722. materialDef.extensions = materialDef.extensions || {};
  1723. materialDef.extensions[ this.name ] = extensionDef;
  1724. extensionsUsed[ this.name ] = true;
  1725. }
  1726. }
  1727. /**
  1728. * Materials ior Extension
  1729. *
  1730. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior
  1731. */
  1732. class GLTFMaterialsIorExtension {
  1733. constructor( writer ) {
  1734. this.writer = writer;
  1735. this.name = 'KHR_materials_ior';
  1736. }
  1737. writeMaterial( material, materialDef ) {
  1738. if ( ! material.isMeshPhysicalMaterial || material.ior === 1.5 ) return;
  1739. const writer = this.writer;
  1740. const extensionsUsed = writer.extensionsUsed;
  1741. const extensionDef = {};
  1742. extensionDef.ior = material.ior;
  1743. materialDef.extensions = materialDef.extensions || {};
  1744. materialDef.extensions[ this.name ] = extensionDef;
  1745. extensionsUsed[ this.name ] = true;
  1746. }
  1747. }
  1748. /**
  1749. * Materials specular Extension
  1750. *
  1751. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular
  1752. */
  1753. class GLTFMaterialsSpecularExtension {
  1754. constructor( writer ) {
  1755. this.writer = writer;
  1756. this.name = 'KHR_materials_specular';
  1757. }
  1758. writeMaterial( material, materialDef ) {
  1759. if ( ! material.isMeshPhysicalMaterial || ( material.specularIntensity === 1.0 &&
  1760. material.specularColor.equals( DEFAULT_SPECULAR_COLOR ) &&
  1761. ! material.specularIntensityMap && ! material.specularColorTexture ) ) return;
  1762. const writer = this.writer;
  1763. const extensionsUsed = writer.extensionsUsed;
  1764. const extensionDef = {};
  1765. if ( material.specularIntensityMap ) {
  1766. const specularIntensityMapDef = {
  1767. index: writer.processTexture( material.specularIntensityMap ),
  1768. texCoord: material.specularIntensityMap.channel
  1769. };
  1770. writer.applyTextureTransform( specularIntensityMapDef, material.specularIntensityMap );
  1771. extensionDef.specularTexture = specularIntensityMapDef;
  1772. }
  1773. if ( material.specularColorMap ) {
  1774. const specularColorMapDef = {
  1775. index: writer.processTexture( material.specularColorMap ),
  1776. texCoord: material.specularColorMap.channel
  1777. };
  1778. writer.applyTextureTransform( specularColorMapDef, material.specularColorMap );
  1779. extensionDef.specularColorTexture = specularColorMapDef;
  1780. }
  1781. extensionDef.specularFactor = material.specularIntensity;
  1782. extensionDef.specularColorFactor = material.specularColor.toArray();
  1783. materialDef.extensions = materialDef.extensions || {};
  1784. materialDef.extensions[ this.name ] = extensionDef;
  1785. extensionsUsed[ this.name ] = true;
  1786. }
  1787. }
  1788. /**
  1789. * Sheen Materials Extension
  1790. *
  1791. * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen
  1792. */
  1793. class GLTFMaterialsSheenExtension {
  1794. constructor( writer ) {
  1795. this.writer = writer;
  1796. this.name = 'KHR_materials_sheen';
  1797. }
  1798. writeMaterial( material, materialDef ) {
  1799. if ( ! material.isMeshPhysicalMaterial || material.sheen == 0.0 ) return;
  1800. const writer = this.writer;
  1801. const extensionsUsed = writer.extensionsUsed;
  1802. const extensionDef = {};
  1803. if ( material.sheenRoughnessMap ) {
  1804. const sheenRoughnessMapDef = {
  1805. index: writer.processTexture( material.sheenRoughnessMap ),
  1806. texCoord: material.sheenRoughnessMap.channel
  1807. };
  1808. writer.applyTextureTransform( sheenRoughnessMapDef, material.sheenRoughnessMap );
  1809. extensionDef.sheenRoughnessTexture = sheenRoughnessMapDef;
  1810. }
  1811. if ( material.sheenColorMap ) {
  1812. const sheenColorMapDef = {
  1813. index: writer.processTexture( material.sheenColorMap ),
  1814. texCoord: material.sheenColorMap.channel
  1815. };
  1816. writer.applyTextureTransform( sheenColorMapDef, material.sheenColorMap );
  1817. extensionDef.sheenColorTexture = sheenColorMapDef;
  1818. }
  1819. extensionDef.sheenRoughnessFactor = material.sheenRoughness;
  1820. extensionDef.sheenColorFactor = material.sheenColor.toArray();
  1821. materialDef.extensions = materialDef.extensions || {};
  1822. materialDef.extensions[ this.name ] = extensionDef;
  1823. extensionsUsed[ this.name ] = true;
  1824. }
  1825. }
  1826. /**
  1827. * Anisotropy Materials Extension
  1828. *
  1829. * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_anisotropy
  1830. */
  1831. class GLTFMaterialsAnisotropyExtension {
  1832. constructor( writer ) {
  1833. this.writer = writer;
  1834. this.name = 'KHR_materials_anisotropy';
  1835. }
  1836. writeMaterial( material, materialDef ) {
  1837. if ( ! material.isMeshPhysicalMaterial || material.anisotropy == 0.0 ) return;
  1838. const writer = this.writer;
  1839. const extensionsUsed = writer.extensionsUsed;
  1840. const extensionDef = {};
  1841. if ( material.anisotropyMap ) {
  1842. const anisotropyMapDef = { index: writer.processTexture( material.anisotropyMap ) };
  1843. writer.applyTextureTransform( anisotropyMapDef, material.anisotropyMap );
  1844. extensionDef.anisotropyTexture = anisotropyMapDef;
  1845. }
  1846. extensionDef.anisotropyStrength = material.anisotropy;
  1847. extensionDef.anisotropyRotation = material.anisotropyRotation;
  1848. materialDef.extensions = materialDef.extensions || {};
  1849. materialDef.extensions[ this.name ] = extensionDef;
  1850. extensionsUsed[ this.name ] = true;
  1851. }
  1852. }
  1853. /**
  1854. * Materials Emissive Strength Extension
  1855. *
  1856. * Specification: https://github.com/KhronosGroup/glTF/blob/5768b3ce0ef32bc39cdf1bef10b948586635ead3/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md
  1857. */
  1858. class GLTFMaterialsEmissiveStrengthExtension {
  1859. constructor( writer ) {
  1860. this.writer = writer;
  1861. this.name = 'KHR_materials_emissive_strength';
  1862. }
  1863. writeMaterial( material, materialDef ) {
  1864. if ( ! material.isMeshStandardMaterial || material.emissiveIntensity === 1.0 ) return;
  1865. const writer = this.writer;
  1866. const extensionsUsed = writer.extensionsUsed;
  1867. const extensionDef = {};
  1868. extensionDef.emissiveStrength = material.emissiveIntensity;
  1869. materialDef.extensions = materialDef.extensions || {};
  1870. materialDef.extensions[ this.name ] = extensionDef;
  1871. extensionsUsed[ this.name ] = true;
  1872. }
  1873. }
  1874. /**
  1875. * Static utility functions
  1876. */
  1877. GLTFExporter.Utils = {
  1878. insertKeyframe: function ( track, time ) {
  1879. const tolerance = 0.001; // 1ms
  1880. const valueSize = track.getValueSize();
  1881. const times = new track.TimeBufferType( track.times.length + 1 );
  1882. const values = new track.ValueBufferType( track.values.length + valueSize );
  1883. const interpolant = track.createInterpolant( new track.ValueBufferType( valueSize ) );
  1884. let index;
  1885. if ( track.times.length === 0 ) {
  1886. times[ 0 ] = time;
  1887. for ( let i = 0; i < valueSize; i ++ ) {
  1888. values[ i ] = 0;
  1889. }
  1890. index = 0;
  1891. } else if ( time < track.times[ 0 ] ) {
  1892. if ( Math.abs( track.times[ 0 ] - time ) < tolerance ) return 0;
  1893. times[ 0 ] = time;
  1894. times.set( track.times, 1 );
  1895. values.set( interpolant.evaluate( time ), 0 );
  1896. values.set( track.values, valueSize );
  1897. index = 0;
  1898. } else if ( time > track.times[ track.times.length - 1 ] ) {
  1899. if ( Math.abs( track.times[ track.times.length - 1 ] - time ) < tolerance ) {
  1900. return track.times.length - 1;
  1901. }
  1902. times[ times.length - 1 ] = time;
  1903. times.set( track.times, 0 );
  1904. values.set( track.values, 0 );
  1905. values.set( interpolant.evaluate( time ), track.values.length );
  1906. index = times.length - 1;
  1907. } else {
  1908. for ( let i = 0; i < track.times.length; i ++ ) {
  1909. if ( Math.abs( track.times[ i ] - time ) < tolerance ) return i;
  1910. if ( track.times[ i ] < time && track.times[ i + 1 ] > time ) {
  1911. times.set( track.times.slice( 0, i + 1 ), 0 );
  1912. times[ i + 1 ] = time;
  1913. times.set( track.times.slice( i + 1 ), i + 2 );
  1914. values.set( track.values.slice( 0, ( i + 1 ) * valueSize ), 0 );
  1915. values.set( interpolant.evaluate( time ), ( i + 1 ) * valueSize );
  1916. values.set( track.values.slice( ( i + 1 ) * valueSize ), ( i + 2 ) * valueSize );
  1917. index = i + 1;
  1918. break;
  1919. }
  1920. }
  1921. }
  1922. track.times = times;
  1923. track.values = values;
  1924. return index;
  1925. },
  1926. mergeMorphTargetTracks: function ( clip, root ) {
  1927. const tracks = [];
  1928. const mergedTracks = {};
  1929. const sourceTracks = clip.tracks;
  1930. for ( let i = 0; i < sourceTracks.length; ++ i ) {
  1931. let sourceTrack = sourceTracks[ i ];
  1932. const sourceTrackBinding = PropertyBinding.parseTrackName( sourceTrack.name );
  1933. const sourceTrackNode = PropertyBinding.findNode( root, sourceTrackBinding.nodeName );
  1934. if ( sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined ) {
  1935. // Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is.
  1936. tracks.push( sourceTrack );
  1937. continue;
  1938. }
  1939. if ( sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete
  1940. && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear ) {
  1941. if ( sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  1942. // This should never happen, because glTF morph target animations
  1943. // affect all targets already.
  1944. throw new Error( 'THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.' );
  1945. }
  1946. console.warn( 'THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.' );
  1947. sourceTrack = sourceTrack.clone();
  1948. sourceTrack.setInterpolation( InterpolateLinear );
  1949. }
  1950. const targetCount = sourceTrackNode.morphTargetInfluences.length;
  1951. const targetIndex = sourceTrackNode.morphTargetDictionary[ sourceTrackBinding.propertyIndex ];
  1952. if ( targetIndex === undefined ) {
  1953. throw new Error( 'THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex );
  1954. }
  1955. let mergedTrack;
  1956. // If this is the first time we've seen this object, create a new
  1957. // track to store merged keyframe data for each morph target.
  1958. if ( mergedTracks[ sourceTrackNode.uuid ] === undefined ) {
  1959. mergedTrack = sourceTrack.clone();
  1960. const values = new mergedTrack.ValueBufferType( targetCount * mergedTrack.times.length );
  1961. for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
  1962. values[ j * targetCount + targetIndex ] = mergedTrack.values[ j ];
  1963. }
  1964. // We need to take into consideration the intended target node
  1965. // of our original un-merged morphTarget animation.
  1966. mergedTrack.name = ( sourceTrackBinding.nodeName || '' ) + '.morphTargetInfluences';
  1967. mergedTrack.values = values;
  1968. mergedTracks[ sourceTrackNode.uuid ] = mergedTrack;
  1969. tracks.push( mergedTrack );
  1970. continue;
  1971. }
  1972. const sourceInterpolant = sourceTrack.createInterpolant( new sourceTrack.ValueBufferType( 1 ) );
  1973. mergedTrack = mergedTracks[ sourceTrackNode.uuid ];
  1974. // For every existing keyframe of the merged track, write a (possibly
  1975. // interpolated) value from the source track.
  1976. for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
  1977. mergedTrack.values[ j * targetCount + targetIndex ] = sourceInterpolant.evaluate( mergedTrack.times[ j ] );
  1978. }
  1979. // For every existing keyframe of the source track, write a (possibly
  1980. // new) keyframe to the merged track. Values from the previous loop may
  1981. // be written again, but keyframes are de-duplicated.
  1982. for ( let j = 0; j < sourceTrack.times.length; j ++ ) {
  1983. const keyframeIndex = this.insertKeyframe( mergedTrack, sourceTrack.times[ j ] );
  1984. mergedTrack.values[ keyframeIndex * targetCount + targetIndex ] = sourceTrack.values[ j ];
  1985. }
  1986. }
  1987. clip.tracks = tracks;
  1988. return clip;
  1989. }
  1990. };
  1991. export { GLTFExporter };