GLTFExporter.js 65 KB

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