GLTFExporter.js 74 KB

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