GLTFExporter.js 84 KB

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