GLTFExporter.js 64 KB

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