GLTFExporter.js 63 KB

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