GLTFExporter.js 57 KB

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