GLTFExporter.js 63 KB

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