2
0

GLTFExporter.js 62 KB

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