GLTFExporter.js 64 KB

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