GLTFExporter.js 78 KB

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