GLTFExporter.js 64 KB

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