GLTFExporter.js 63 KB

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