GLTFExporter.js 71 KB

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