GLTFExporter.js 84 KB

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