GLTFExporter.js 62 KB

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