GLTFExporter.js 63 KB

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