GLTFExporter.js 76 KB

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