GLTFExporter.js 64 KB

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