GLTFExporter.js 63 KB

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