GLTFExporter.js 58 KB

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