GLTFExporter.js 63 KB

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