GLTFExporter.js 84 KB

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