GLTFExporter.js 63 KB

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