GLTFExporter.js 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389
  1. import {
  2. BufferAttribute,
  3. ClampToEdgeWrapping,
  4. Color,
  5. DoubleSide,
  6. InterpolateDiscrete,
  7. InterpolateLinear,
  8. NoColorSpace,
  9. LinearFilter,
  10. LinearMipmapLinearFilter,
  11. LinearMipmapNearestFilter,
  12. MathUtils,
  13. Matrix4,
  14. MirroredRepeatWrapping,
  15. NearestFilter,
  16. NearestMipmapLinearFilter,
  17. NearestMipmapNearestFilter,
  18. PropertyBinding,
  19. RGBAFormat,
  20. RepeatWrapping,
  21. Scene,
  22. Source,
  23. SRGBColorSpace,
  24. CompressedTexture,
  25. Vector3,
  26. Quaternion,
  27. REVISION
  28. } from 'three';
  29. import { decompress } from './../utils/TextureUtils.js';
  30. /**
  31. * The KHR_mesh_quantization extension allows these extra attribute component types
  32. *
  33. * @see https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_mesh_quantization/README.md#extending-mesh-attributes
  34. */
  35. const KHR_mesh_quantization_ExtraAttrTypes = {
  36. POSITION: [
  37. 'byte',
  38. 'byte normalized',
  39. 'unsigned byte',
  40. 'unsigned byte normalized',
  41. 'short',
  42. 'short normalized',
  43. 'unsigned short',
  44. 'unsigned short normalized',
  45. ],
  46. NORMAL: [
  47. 'byte normalized',
  48. 'short normalized',
  49. ],
  50. TANGENT: [
  51. 'byte normalized',
  52. 'short normalized',
  53. ],
  54. TEXCOORD: [
  55. 'byte',
  56. 'byte normalized',
  57. 'unsigned byte',
  58. 'short',
  59. 'short normalized',
  60. 'unsigned short',
  61. ],
  62. };
  63. class GLTFExporter {
  64. constructor() {
  65. this.pluginCallbacks = [];
  66. this.register( function ( writer ) {
  67. return new GLTFLightExtension( writer );
  68. } );
  69. this.register( function ( writer ) {
  70. return new GLTFMaterialsUnlitExtension( writer );
  71. } );
  72. this.register( function ( writer ) {
  73. return new GLTFMaterialsTransmissionExtension( writer );
  74. } );
  75. this.register( function ( writer ) {
  76. return new GLTFMaterialsVolumeExtension( writer );
  77. } );
  78. this.register( function ( writer ) {
  79. return new GLTFMaterialsIorExtension( writer );
  80. } );
  81. this.register( function ( writer ) {
  82. return new GLTFMaterialsSpecularExtension( writer );
  83. } );
  84. this.register( function ( writer ) {
  85. return new GLTFMaterialsClearcoatExtension( writer );
  86. } );
  87. this.register( function ( writer ) {
  88. return new GLTFMaterialsDispersionExtension( writer );
  89. } );
  90. this.register( function ( writer ) {
  91. return new GLTFMaterialsIridescenceExtension( writer );
  92. } );
  93. this.register( function ( writer ) {
  94. return new GLTFMaterialsSheenExtension( writer );
  95. } );
  96. this.register( function ( writer ) {
  97. return new GLTFMaterialsAnisotropyExtension( writer );
  98. } );
  99. this.register( function ( writer ) {
  100. return new GLTFMaterialsEmissiveStrengthExtension( writer );
  101. } );
  102. this.register( function ( writer ) {
  103. return new GLTFMaterialsBumpExtension( writer );
  104. } );
  105. this.register( function ( writer ) {
  106. return new GLTFMeshGpuInstancing( writer );
  107. } );
  108. }
  109. register( callback ) {
  110. if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
  111. this.pluginCallbacks.push( callback );
  112. }
  113. return this;
  114. }
  115. unregister( callback ) {
  116. if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
  117. this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
  118. }
  119. return this;
  120. }
  121. /**
  122. * Parse scenes and generate GLTF output
  123. * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes
  124. * @param {Function} onDone Callback on completed
  125. * @param {Function} onError Callback on errors
  126. * @param {Object} options options
  127. */
  128. parse( input, onDone, onError, options ) {
  129. const writer = new GLTFWriter();
  130. const plugins = [];
  131. for ( let i = 0, il = this.pluginCallbacks.length; i < il; i ++ ) {
  132. plugins.push( this.pluginCallbacks[ i ]( writer ) );
  133. }
  134. writer.setPlugins( plugins );
  135. writer.write( input, onDone, options ).catch( onError );
  136. }
  137. parseAsync( input, options ) {
  138. const scope = this;
  139. return new Promise( function ( resolve, reject ) {
  140. scope.parse( input, resolve, reject, options );
  141. } );
  142. }
  143. }
  144. //------------------------------------------------------------------------------
  145. // Constants
  146. //------------------------------------------------------------------------------
  147. const WEBGL_CONSTANTS = {
  148. POINTS: 0x0000,
  149. LINES: 0x0001,
  150. LINE_LOOP: 0x0002,
  151. LINE_STRIP: 0x0003,
  152. TRIANGLES: 0x0004,
  153. TRIANGLE_STRIP: 0x0005,
  154. TRIANGLE_FAN: 0x0006,
  155. BYTE: 0x1400,
  156. UNSIGNED_BYTE: 0x1401,
  157. SHORT: 0x1402,
  158. UNSIGNED_SHORT: 0x1403,
  159. INT: 0x1404,
  160. UNSIGNED_INT: 0x1405,
  161. FLOAT: 0x1406,
  162. ARRAY_BUFFER: 0x8892,
  163. ELEMENT_ARRAY_BUFFER: 0x8893,
  164. NEAREST: 0x2600,
  165. LINEAR: 0x2601,
  166. NEAREST_MIPMAP_NEAREST: 0x2700,
  167. LINEAR_MIPMAP_NEAREST: 0x2701,
  168. NEAREST_MIPMAP_LINEAR: 0x2702,
  169. LINEAR_MIPMAP_LINEAR: 0x2703,
  170. CLAMP_TO_EDGE: 33071,
  171. MIRRORED_REPEAT: 33648,
  172. REPEAT: 10497
  173. };
  174. const KHR_MESH_QUANTIZATION = 'KHR_mesh_quantization';
  175. const THREE_TO_WEBGL = {};
  176. THREE_TO_WEBGL[ NearestFilter ] = WEBGL_CONSTANTS.NEAREST;
  177. THREE_TO_WEBGL[ NearestMipmapNearestFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST;
  178. THREE_TO_WEBGL[ NearestMipmapLinearFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR;
  179. THREE_TO_WEBGL[ LinearFilter ] = WEBGL_CONSTANTS.LINEAR;
  180. THREE_TO_WEBGL[ LinearMipmapNearestFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST;
  181. THREE_TO_WEBGL[ LinearMipmapLinearFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR;
  182. THREE_TO_WEBGL[ ClampToEdgeWrapping ] = WEBGL_CONSTANTS.CLAMP_TO_EDGE;
  183. THREE_TO_WEBGL[ RepeatWrapping ] = WEBGL_CONSTANTS.REPEAT;
  184. THREE_TO_WEBGL[ MirroredRepeatWrapping ] = WEBGL_CONSTANTS.MIRRORED_REPEAT;
  185. const PATH_PROPERTIES = {
  186. scale: 'scale',
  187. position: 'translation',
  188. quaternion: 'rotation',
  189. morphTargetInfluences: 'weights'
  190. };
  191. const DEFAULT_SPECULAR_COLOR = new Color();
  192. // GLB constants
  193. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
  194. const GLB_HEADER_BYTES = 12;
  195. const GLB_HEADER_MAGIC = 0x46546C67;
  196. const GLB_VERSION = 2;
  197. const GLB_CHUNK_PREFIX_BYTES = 8;
  198. const GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
  199. const GLB_CHUNK_TYPE_BIN = 0x004E4942;
  200. //------------------------------------------------------------------------------
  201. // Utility functions
  202. //------------------------------------------------------------------------------
  203. /**
  204. * Compare two arrays
  205. * @param {Array} array1 Array 1 to compare
  206. * @param {Array} array2 Array 2 to compare
  207. * @return {Boolean} Returns true if both arrays are equal
  208. */
  209. function equalArray( array1, array2 ) {
  210. return ( array1.length === array2.length ) && array1.every( function ( element, index ) {
  211. return element === array2[ index ];
  212. } );
  213. }
  214. /**
  215. * Converts a string to an ArrayBuffer.
  216. * @param {string} text
  217. * @return {ArrayBuffer}
  218. */
  219. function stringToArrayBuffer( text ) {
  220. return new TextEncoder().encode( text ).buffer;
  221. }
  222. /**
  223. * Is identity matrix
  224. *
  225. * @param {Matrix4} matrix
  226. * @returns {Boolean} Returns true, if parameter is identity matrix
  227. */
  228. function isIdentityMatrix( matrix ) {
  229. return equalArray( matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] );
  230. }
  231. /**
  232. * Get the min and max vectors from the given attribute
  233. * @param {BufferAttribute} attribute Attribute to find the min/max in range from start to start + count
  234. * @param {Integer} start
  235. * @param {Integer} count
  236. * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
  237. */
  238. function getMinMax( attribute, start, count ) {
  239. const output = {
  240. min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
  241. max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
  242. };
  243. for ( let i = start; i < start + count; i ++ ) {
  244. for ( let a = 0; a < attribute.itemSize; a ++ ) {
  245. let value;
  246. if ( attribute.itemSize > 4 ) {
  247. // no support for interleaved data for itemSize > 4
  248. value = attribute.array[ i * attribute.itemSize + a ];
  249. } else {
  250. if ( a === 0 ) value = attribute.getX( i );
  251. else if ( a === 1 ) value = attribute.getY( i );
  252. else if ( a === 2 ) value = attribute.getZ( i );
  253. else if ( a === 3 ) value = attribute.getW( i );
  254. if ( attribute.normalized === true ) {
  255. value = MathUtils.normalize( value, attribute.array );
  256. }
  257. }
  258. output.min[ a ] = Math.min( output.min[ a ], value );
  259. output.max[ a ] = Math.max( output.max[ a ], value );
  260. }
  261. }
  262. return output;
  263. }
  264. /**
  265. * Get the required size + padding for a buffer, rounded to the next 4-byte boundary.
  266. * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
  267. *
  268. * @param {Integer} bufferSize The size the original buffer.
  269. * @returns {Integer} new buffer size with required padding.
  270. *
  271. */
  272. function getPaddedBufferSize( bufferSize ) {
  273. return Math.ceil( bufferSize / 4 ) * 4;
  274. }
  275. /**
  276. * Returns a buffer aligned to 4-byte boundary.
  277. *
  278. * @param {ArrayBuffer} arrayBuffer Buffer to pad
  279. * @param {Integer} paddingByte (Optional)
  280. * @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer
  281. */
  282. function getPaddedArrayBuffer( arrayBuffer, paddingByte = 0 ) {
  283. const paddedLength = getPaddedBufferSize( arrayBuffer.byteLength );
  284. if ( paddedLength !== arrayBuffer.byteLength ) {
  285. const array = new Uint8Array( paddedLength );
  286. array.set( new Uint8Array( arrayBuffer ) );
  287. if ( paddingByte !== 0 ) {
  288. for ( let i = arrayBuffer.byteLength; i < paddedLength; i ++ ) {
  289. array[ i ] = paddingByte;
  290. }
  291. }
  292. return array.buffer;
  293. }
  294. return arrayBuffer;
  295. }
  296. function getCanvas() {
  297. if ( typeof document === 'undefined' && typeof OffscreenCanvas !== 'undefined' ) {
  298. return new OffscreenCanvas( 1, 1 );
  299. }
  300. return document.createElement( 'canvas' );
  301. }
  302. function getToBlobPromise( canvas, mimeType ) {
  303. if ( canvas.toBlob !== undefined ) {
  304. return new Promise( ( resolve ) => canvas.toBlob( resolve, mimeType ) );
  305. }
  306. let quality;
  307. // Blink's implementation of convertToBlob seems to default to a quality level of 100%
  308. // Use the Blink default quality levels of toBlob instead so that file sizes are comparable.
  309. if ( mimeType === 'image/jpeg' ) {
  310. quality = 0.92;
  311. } else if ( mimeType === 'image/webp' ) {
  312. quality = 0.8;
  313. }
  314. return canvas.convertToBlob( {
  315. type: mimeType,
  316. quality: quality
  317. } );
  318. }
  319. /**
  320. * Writer
  321. */
  322. class GLTFWriter {
  323. constructor() {
  324. this.plugins = [];
  325. this.options = {};
  326. this.pending = [];
  327. this.buffers = [];
  328. this.byteOffset = 0;
  329. this.buffers = [];
  330. this.nodeMap = new Map();
  331. this.skins = [];
  332. this.extensionsUsed = {};
  333. this.extensionsRequired = {};
  334. this.uids = new Map();
  335. this.uid = 0;
  336. this.json = {
  337. asset: {
  338. version: '2.0',
  339. generator: 'THREE.GLTFExporter r' + REVISION
  340. }
  341. };
  342. this.cache = {
  343. meshes: new Map(),
  344. attributes: new Map(),
  345. attributesNormalized: new Map(),
  346. materials: new Map(),
  347. textures: new Map(),
  348. images: new Map()
  349. };
  350. }
  351. setPlugins( plugins ) {
  352. this.plugins = plugins;
  353. }
  354. /**
  355. * Parse scenes and generate GLTF output
  356. * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes
  357. * @param {Function} onDone Callback on completed
  358. * @param {Object} options options
  359. */
  360. async write( input, onDone, options = {} ) {
  361. this.options = Object.assign( {
  362. // default options
  363. binary: false,
  364. trs: false,
  365. onlyVisible: true,
  366. maxTextureSize: Infinity,
  367. animations: [],
  368. includeCustomExtensions: false
  369. }, options );
  370. if ( this.options.animations.length > 0 ) {
  371. // Only TRS properties, and not matrices, may be targeted by animation.
  372. this.options.trs = true;
  373. }
  374. this.processInput( input );
  375. await Promise.all( this.pending );
  376. const writer = this;
  377. const buffers = writer.buffers;
  378. const json = writer.json;
  379. options = writer.options;
  380. const extensionsUsed = writer.extensionsUsed;
  381. const extensionsRequired = writer.extensionsRequired;
  382. // Merge buffers.
  383. const blob = new Blob( buffers, { type: 'application/octet-stream' } );
  384. // Declare extensions.
  385. const extensionsUsedList = Object.keys( extensionsUsed );
  386. const extensionsRequiredList = Object.keys( extensionsRequired );
  387. if ( extensionsUsedList.length > 0 ) json.extensionsUsed = extensionsUsedList;
  388. if ( extensionsRequiredList.length > 0 ) json.extensionsRequired = extensionsRequiredList;
  389. // Update bytelength of the single buffer.
  390. if ( json.buffers && json.buffers.length > 0 ) json.buffers[ 0 ].byteLength = blob.size;
  391. if ( options.binary === true ) {
  392. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
  393. const reader = new FileReader();
  394. reader.readAsArrayBuffer( blob );
  395. reader.onloadend = function () {
  396. // Binary chunk.
  397. const binaryChunk = getPaddedArrayBuffer( reader.result );
  398. const binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  399. binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
  400. binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );
  401. // JSON chunk.
  402. const jsonChunk = getPaddedArrayBuffer( stringToArrayBuffer( JSON.stringify( json ) ), 0x20 );
  403. const jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
  404. jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
  405. jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );
  406. // GLB header.
  407. const header = new ArrayBuffer( GLB_HEADER_BYTES );
  408. const headerView = new DataView( header );
  409. headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
  410. headerView.setUint32( 4, GLB_VERSION, true );
  411. const totalByteLength = GLB_HEADER_BYTES
  412. + jsonChunkPrefix.byteLength + jsonChunk.byteLength
  413. + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
  414. headerView.setUint32( 8, totalByteLength, true );
  415. const glbBlob = new Blob( [
  416. header,
  417. jsonChunkPrefix,
  418. jsonChunk,
  419. binaryChunkPrefix,
  420. binaryChunk
  421. ], { type: 'application/octet-stream' } );
  422. const glbReader = new FileReader();
  423. glbReader.readAsArrayBuffer( glbBlob );
  424. glbReader.onloadend = function () {
  425. onDone( glbReader.result );
  426. };
  427. };
  428. } else {
  429. if ( json.buffers && json.buffers.length > 0 ) {
  430. const reader = new FileReader();
  431. reader.readAsDataURL( blob );
  432. reader.onloadend = function () {
  433. const base64data = reader.result;
  434. json.buffers[ 0 ].uri = base64data;
  435. onDone( json );
  436. };
  437. } else {
  438. onDone( json );
  439. }
  440. }
  441. }
  442. /**
  443. * Serializes a userData.
  444. *
  445. * @param {THREE.Object3D|THREE.Material} object
  446. * @param {Object} objectDef
  447. */
  448. serializeUserData( object, objectDef ) {
  449. if ( Object.keys( object.userData ).length === 0 ) return;
  450. const options = this.options;
  451. const extensionsUsed = this.extensionsUsed;
  452. try {
  453. const json = JSON.parse( JSON.stringify( object.userData ) );
  454. if ( options.includeCustomExtensions && json.gltfExtensions ) {
  455. if ( objectDef.extensions === undefined ) objectDef.extensions = {};
  456. for ( const extensionName in json.gltfExtensions ) {
  457. objectDef.extensions[ extensionName ] = json.gltfExtensions[ extensionName ];
  458. extensionsUsed[ extensionName ] = true;
  459. }
  460. delete json.gltfExtensions;
  461. }
  462. if ( Object.keys( json ).length > 0 ) objectDef.extras = json;
  463. } catch ( error ) {
  464. console.warn( 'THREE.GLTFExporter: userData of \'' + object.name + '\' ' +
  465. 'won\'t be serialized because of JSON.stringify error - ' + error.message );
  466. }
  467. }
  468. /**
  469. * Returns ids for buffer attributes.
  470. * @param {Object} object
  471. * @return {Integer}
  472. */
  473. getUID( attribute, isRelativeCopy = false ) {
  474. if ( this.uids.has( attribute ) === false ) {
  475. const uids = new Map();
  476. uids.set( true, this.uid ++ );
  477. uids.set( false, this.uid ++ );
  478. this.uids.set( attribute, uids );
  479. }
  480. const uids = this.uids.get( attribute );
  481. return uids.get( isRelativeCopy );
  482. }
  483. /**
  484. * Checks if normal attribute values are normalized.
  485. *
  486. * @param {BufferAttribute} normal
  487. * @returns {Boolean}
  488. */
  489. isNormalizedNormalAttribute( normal ) {
  490. const cache = this.cache;
  491. if ( cache.attributesNormalized.has( normal ) ) return false;
  492. const v = new Vector3();
  493. for ( let i = 0, il = normal.count; i < il; i ++ ) {
  494. // 0.0005 is from glTF-validator
  495. if ( Math.abs( v.fromBufferAttribute( normal, i ).length() - 1.0 ) > 0.0005 ) return false;
  496. }
  497. return true;
  498. }
  499. /**
  500. * Creates normalized normal buffer attribute.
  501. *
  502. * @param {BufferAttribute} normal
  503. * @returns {BufferAttribute}
  504. *
  505. */
  506. createNormalizedNormalAttribute( normal ) {
  507. const cache = this.cache;
  508. if ( cache.attributesNormalized.has( normal ) ) return cache.attributesNormalized.get( normal );
  509. const attribute = normal.clone();
  510. const v = new Vector3();
  511. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  512. v.fromBufferAttribute( attribute, i );
  513. if ( v.x === 0 && v.y === 0 && v.z === 0 ) {
  514. // if values can't be normalized set (1, 0, 0)
  515. v.setX( 1.0 );
  516. } else {
  517. v.normalize();
  518. }
  519. attribute.setXYZ( i, v.x, v.y, v.z );
  520. }
  521. cache.attributesNormalized.set( normal, attribute );
  522. return attribute;
  523. }
  524. /**
  525. * Applies a texture transform, if present, to the map definition. Requires
  526. * the KHR_texture_transform extension.
  527. *
  528. * @param {Object} mapDef
  529. * @param {THREE.Texture} texture
  530. */
  531. applyTextureTransform( mapDef, texture ) {
  532. let didTransform = false;
  533. const transformDef = {};
  534. if ( texture.offset.x !== 0 || texture.offset.y !== 0 ) {
  535. transformDef.offset = texture.offset.toArray();
  536. didTransform = true;
  537. }
  538. if ( texture.rotation !== 0 ) {
  539. transformDef.rotation = texture.rotation;
  540. didTransform = true;
  541. }
  542. if ( texture.repeat.x !== 1 || texture.repeat.y !== 1 ) {
  543. transformDef.scale = texture.repeat.toArray();
  544. didTransform = true;
  545. }
  546. if ( didTransform ) {
  547. mapDef.extensions = mapDef.extensions || {};
  548. mapDef.extensions[ 'KHR_texture_transform' ] = transformDef;
  549. this.extensionsUsed[ 'KHR_texture_transform' ] = true;
  550. }
  551. }
  552. buildMetalRoughTexture( metalnessMap, roughnessMap ) {
  553. if ( metalnessMap === roughnessMap ) return metalnessMap;
  554. function getEncodingConversion( map ) {
  555. if ( map.colorSpace === SRGBColorSpace ) {
  556. return function SRGBToLinear( c ) {
  557. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  558. };
  559. }
  560. return function LinearToLinear( c ) {
  561. return c;
  562. };
  563. }
  564. console.warn( 'THREE.GLTFExporter: Merged metalnessMap and roughnessMap textures.' );
  565. if ( metalnessMap instanceof CompressedTexture ) {
  566. metalnessMap = decompress( metalnessMap );
  567. }
  568. if ( roughnessMap instanceof CompressedTexture ) {
  569. roughnessMap = decompress( roughnessMap );
  570. }
  571. const metalness = metalnessMap ? metalnessMap.image : null;
  572. const roughness = roughnessMap ? roughnessMap.image : null;
  573. const width = Math.max( metalness ? metalness.width : 0, roughness ? roughness.width : 0 );
  574. const height = Math.max( metalness ? metalness.height : 0, roughness ? roughness.height : 0 );
  575. const canvas = getCanvas();
  576. canvas.width = width;
  577. canvas.height = height;
  578. const context = canvas.getContext( '2d', {
  579. willReadFrequently: true,
  580. } );
  581. context.fillStyle = '#00ffff';
  582. context.fillRect( 0, 0, width, height );
  583. const composite = context.getImageData( 0, 0, width, height );
  584. if ( metalness ) {
  585. context.drawImage( metalness, 0, 0, width, height );
  586. const convert = getEncodingConversion( metalnessMap );
  587. const data = context.getImageData( 0, 0, width, height ).data;
  588. for ( let i = 2; i < data.length; i += 4 ) {
  589. composite.data[ i ] = convert( data[ i ] / 256 ) * 256;
  590. }
  591. }
  592. if ( roughness ) {
  593. context.drawImage( roughness, 0, 0, width, height );
  594. const convert = getEncodingConversion( roughnessMap );
  595. const data = context.getImageData( 0, 0, width, height ).data;
  596. for ( let i = 1; i < data.length; i += 4 ) {
  597. composite.data[ i ] = convert( data[ i ] / 256 ) * 256;
  598. }
  599. }
  600. context.putImageData( composite, 0, 0 );
  601. //
  602. const reference = metalnessMap || roughnessMap;
  603. const texture = reference.clone();
  604. texture.source = new Source( canvas );
  605. texture.colorSpace = NoColorSpace;
  606. texture.channel = ( metalnessMap || roughnessMap ).channel;
  607. if ( metalnessMap && roughnessMap && metalnessMap.channel !== roughnessMap.channel ) {
  608. console.warn( 'THREE.GLTFExporter: UV channels for metalnessMap and roughnessMap textures must match.' );
  609. }
  610. return texture;
  611. }
  612. /**
  613. * Process a buffer to append to the default one.
  614. * @param {ArrayBuffer} buffer
  615. * @return {Integer}
  616. */
  617. processBuffer( buffer ) {
  618. const json = this.json;
  619. const buffers = this.buffers;
  620. if ( ! json.buffers ) json.buffers = [ { byteLength: 0 } ];
  621. // All buffers are merged before export.
  622. buffers.push( buffer );
  623. return 0;
  624. }
  625. /**
  626. * Process and generate a BufferView
  627. * @param {BufferAttribute} attribute
  628. * @param {number} componentType
  629. * @param {number} start
  630. * @param {number} count
  631. * @param {number} target (Optional) Target usage of the BufferView
  632. * @return {Object}
  633. */
  634. processBufferView( attribute, componentType, start, count, target ) {
  635. const json = this.json;
  636. if ( ! json.bufferViews ) json.bufferViews = [];
  637. // Create a new dataview and dump the attribute's array into it
  638. let componentSize;
  639. switch ( componentType ) {
  640. case WEBGL_CONSTANTS.BYTE:
  641. case WEBGL_CONSTANTS.UNSIGNED_BYTE:
  642. componentSize = 1;
  643. break;
  644. case WEBGL_CONSTANTS.SHORT:
  645. case WEBGL_CONSTANTS.UNSIGNED_SHORT:
  646. componentSize = 2;
  647. break;
  648. default:
  649. componentSize = 4;
  650. }
  651. let byteStride = attribute.itemSize * componentSize;
  652. if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
  653. // Each element of a vertex attribute MUST be aligned to 4-byte boundaries
  654. // inside a bufferView
  655. byteStride = Math.ceil( byteStride / 4 ) * 4;
  656. }
  657. const byteLength = getPaddedBufferSize( count * byteStride );
  658. const dataView = new DataView( new ArrayBuffer( byteLength ) );
  659. let offset = 0;
  660. for ( let i = start; i < start + count; i ++ ) {
  661. for ( let a = 0; a < attribute.itemSize; a ++ ) {
  662. let value;
  663. if ( attribute.itemSize > 4 ) {
  664. // no support for interleaved data for itemSize > 4
  665. value = attribute.array[ i * attribute.itemSize + a ];
  666. } else {
  667. if ( a === 0 ) value = attribute.getX( i );
  668. else if ( a === 1 ) value = attribute.getY( i );
  669. else if ( a === 2 ) value = attribute.getZ( i );
  670. else if ( a === 3 ) value = attribute.getW( i );
  671. if ( attribute.normalized === true ) {
  672. value = MathUtils.normalize( value, attribute.array );
  673. }
  674. }
  675. if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
  676. dataView.setFloat32( offset, value, true );
  677. } else if ( componentType === WEBGL_CONSTANTS.INT ) {
  678. dataView.setInt32( offset, value, true );
  679. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
  680. dataView.setUint32( offset, value, true );
  681. } else if ( componentType === WEBGL_CONSTANTS.SHORT ) {
  682. dataView.setInt16( offset, value, true );
  683. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  684. dataView.setUint16( offset, value, true );
  685. } else if ( componentType === WEBGL_CONSTANTS.BYTE ) {
  686. dataView.setInt8( offset, value );
  687. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
  688. dataView.setUint8( offset, value );
  689. }
  690. offset += componentSize;
  691. }
  692. if ( ( offset % byteStride ) !== 0 ) {
  693. offset += byteStride - ( offset % byteStride );
  694. }
  695. }
  696. const bufferViewDef = {
  697. buffer: this.processBuffer( dataView.buffer ),
  698. byteOffset: this.byteOffset,
  699. byteLength: byteLength
  700. };
  701. if ( target !== undefined ) bufferViewDef.target = target;
  702. if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
  703. // Only define byteStride for vertex attributes.
  704. bufferViewDef.byteStride = byteStride;
  705. }
  706. this.byteOffset += byteLength;
  707. json.bufferViews.push( bufferViewDef );
  708. // @TODO Merge bufferViews where possible.
  709. const output = {
  710. id: json.bufferViews.length - 1,
  711. byteLength: 0
  712. };
  713. return output;
  714. }
  715. /**
  716. * Process and generate a BufferView from an image Blob.
  717. * @param {Blob} blob
  718. * @return {Promise<Integer>}
  719. */
  720. processBufferViewImage( blob ) {
  721. const writer = this;
  722. const json = writer.json;
  723. if ( ! json.bufferViews ) json.bufferViews = [];
  724. return new Promise( function ( resolve ) {
  725. const reader = new FileReader();
  726. reader.readAsArrayBuffer( blob );
  727. reader.onloadend = function () {
  728. const buffer = getPaddedArrayBuffer( reader.result );
  729. const bufferViewDef = {
  730. buffer: writer.processBuffer( buffer ),
  731. byteOffset: writer.byteOffset,
  732. byteLength: buffer.byteLength
  733. };
  734. writer.byteOffset += buffer.byteLength;
  735. resolve( json.bufferViews.push( bufferViewDef ) - 1 );
  736. };
  737. } );
  738. }
  739. /**
  740. * Process attribute to generate an accessor
  741. * @param {BufferAttribute} attribute Attribute to process
  742. * @param {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range
  743. * @param {Integer} start (Optional)
  744. * @param {Integer} count (Optional)
  745. * @return {Integer|null} Index of the processed accessor on the "accessors" array
  746. */
  747. processAccessor( attribute, geometry, start, count ) {
  748. const json = this.json;
  749. const types = {
  750. 1: 'SCALAR',
  751. 2: 'VEC2',
  752. 3: 'VEC3',
  753. 4: 'VEC4',
  754. 9: 'MAT3',
  755. 16: 'MAT4'
  756. };
  757. let componentType;
  758. // Detect the component type of the attribute array
  759. if ( attribute.array.constructor === Float32Array ) {
  760. componentType = WEBGL_CONSTANTS.FLOAT;
  761. } else if ( attribute.array.constructor === Int32Array ) {
  762. componentType = WEBGL_CONSTANTS.INT;
  763. } else if ( attribute.array.constructor === Uint32Array ) {
  764. componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
  765. } else if ( attribute.array.constructor === Int16Array ) {
  766. componentType = WEBGL_CONSTANTS.SHORT;
  767. } else if ( attribute.array.constructor === Uint16Array ) {
  768. componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
  769. } else if ( attribute.array.constructor === Int8Array ) {
  770. componentType = WEBGL_CONSTANTS.BYTE;
  771. } else if ( attribute.array.constructor === Uint8Array ) {
  772. componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE;
  773. } else {
  774. throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type: ' + attribute.array.constructor.name );
  775. }
  776. if ( start === undefined ) start = 0;
  777. if ( count === undefined || count === Infinity ) count = attribute.count;
  778. // Skip creating an accessor if the attribute doesn't have data to export
  779. if ( count === 0 ) return null;
  780. const minMax = getMinMax( attribute, start, count );
  781. let bufferViewTarget;
  782. // If geometry isn't provided, don't infer the target usage of the bufferView. For
  783. // animation samplers, target must not be set.
  784. if ( geometry !== undefined ) {
  785. bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER;
  786. }
  787. const bufferView = this.processBufferView( attribute, componentType, start, count, bufferViewTarget );
  788. const accessorDef = {
  789. bufferView: bufferView.id,
  790. byteOffset: bufferView.byteOffset,
  791. componentType: componentType,
  792. count: count,
  793. max: minMax.max,
  794. min: minMax.min,
  795. type: types[ attribute.itemSize ]
  796. };
  797. if ( attribute.normalized === true ) accessorDef.normalized = true;
  798. if ( ! json.accessors ) json.accessors = [];
  799. return json.accessors.push( accessorDef ) - 1;
  800. }
  801. /**
  802. * Process image
  803. * @param {Image} image to process
  804. * @param {Integer} format of the image (RGBAFormat)
  805. * @param {Boolean} flipY before writing out the image
  806. * @param {String} mimeType export format
  807. * @return {Integer} Index of the processed texture in the "images" array
  808. */
  809. processImage( image, format, flipY, mimeType = 'image/png' ) {
  810. if ( image !== null ) {
  811. const writer = this;
  812. const cache = writer.cache;
  813. const json = writer.json;
  814. const options = writer.options;
  815. const pending = writer.pending;
  816. if ( ! cache.images.has( image ) ) cache.images.set( image, {} );
  817. const cachedImages = cache.images.get( image );
  818. const key = mimeType + ':flipY/' + flipY.toString();
  819. if ( cachedImages[ key ] !== undefined ) return cachedImages[ key ];
  820. if ( ! json.images ) json.images = [];
  821. const imageDef = { mimeType: mimeType };
  822. const canvas = getCanvas();
  823. canvas.width = Math.min( image.width, options.maxTextureSize );
  824. canvas.height = Math.min( image.height, options.maxTextureSize );
  825. const ctx = canvas.getContext( '2d', {
  826. willReadFrequently: true,
  827. } );
  828. if ( flipY === true ) {
  829. ctx.translate( 0, canvas.height );
  830. ctx.scale( 1, - 1 );
  831. }
  832. if ( image.data !== undefined ) { // THREE.DataTexture
  833. if ( format !== RGBAFormat ) {
  834. console.error( 'GLTFExporter: Only RGBAFormat is supported.', format );
  835. }
  836. if ( image.width > options.maxTextureSize || image.height > options.maxTextureSize ) {
  837. console.warn( 'GLTFExporter: Image size is bigger than maxTextureSize', image );
  838. }
  839. const data = new Uint8ClampedArray( image.height * image.width * 4 );
  840. for ( let i = 0; i < data.length; i += 4 ) {
  841. data[ i + 0 ] = image.data[ i + 0 ];
  842. data[ i + 1 ] = image.data[ i + 1 ];
  843. data[ i + 2 ] = image.data[ i + 2 ];
  844. data[ i + 3 ] = image.data[ i + 3 ];
  845. }
  846. ctx.putImageData( new ImageData( data, image.width, image.height ), 0, 0 );
  847. } else {
  848. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  849. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  850. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  851. ( typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas ) ) {
  852. ctx.drawImage( image, 0, 0, canvas.width, canvas.height );
  853. } else {
  854. throw new Error( 'THREE.GLTFExporter: Invalid image type. Use HTMLImageElement, HTMLCanvasElement, ImageBitmap or OffscreenCanvas.' );
  855. }
  856. }
  857. if ( options.binary === true ) {
  858. pending.push(
  859. getToBlobPromise( canvas, mimeType )
  860. .then( blob => writer.processBufferViewImage( blob ) )
  861. .then( bufferViewIndex => {
  862. imageDef.bufferView = bufferViewIndex;
  863. } )
  864. );
  865. } else {
  866. if ( canvas.toDataURL !== undefined ) {
  867. imageDef.uri = canvas.toDataURL( mimeType );
  868. } else {
  869. pending.push(
  870. getToBlobPromise( canvas, mimeType )
  871. .then( blob => new FileReader().readAsDataURL( blob ) )
  872. .then( dataURL => {
  873. imageDef.uri = dataURL;
  874. } )
  875. );
  876. }
  877. }
  878. const index = json.images.push( imageDef ) - 1;
  879. cachedImages[ key ] = index;
  880. return index;
  881. } else {
  882. throw new Error( 'THREE.GLTFExporter: No valid image data found. Unable to process texture.' );
  883. }
  884. }
  885. /**
  886. * Process sampler
  887. * @param {Texture} map Texture to process
  888. * @return {Integer} Index of the processed texture in the "samplers" array
  889. */
  890. processSampler( map ) {
  891. const json = this.json;
  892. if ( ! json.samplers ) json.samplers = [];
  893. const samplerDef = {
  894. magFilter: THREE_TO_WEBGL[ map.magFilter ],
  895. minFilter: THREE_TO_WEBGL[ map.minFilter ],
  896. wrapS: THREE_TO_WEBGL[ map.wrapS ],
  897. wrapT: THREE_TO_WEBGL[ map.wrapT ]
  898. };
  899. return json.samplers.push( samplerDef ) - 1;
  900. }
  901. /**
  902. * Process texture
  903. * @param {Texture} map Map to process
  904. * @return {Integer} Index of the processed texture in the "textures" array
  905. */
  906. processTexture( map ) {
  907. const writer = this;
  908. const options = writer.options;
  909. const cache = this.cache;
  910. const json = this.json;
  911. if ( cache.textures.has( map ) ) return cache.textures.get( map );
  912. if ( ! json.textures ) json.textures = [];
  913. // make non-readable textures (e.g. CompressedTexture) readable by blitting them into a new texture
  914. if ( map instanceof CompressedTexture ) {
  915. map = decompress( map, options.maxTextureSize );
  916. }
  917. let mimeType = map.userData.mimeType;
  918. if ( mimeType === 'image/webp' ) mimeType = 'image/png';
  919. const textureDef = {
  920. sampler: this.processSampler( map ),
  921. source: this.processImage( map.image, map.format, map.flipY, mimeType )
  922. };
  923. if ( map.name ) textureDef.name = map.name;
  924. this._invokeAll( function ( ext ) {
  925. ext.writeTexture && ext.writeTexture( map, textureDef );
  926. } );
  927. const index = json.textures.push( textureDef ) - 1;
  928. cache.textures.set( map, index );
  929. return index;
  930. }
  931. /**
  932. * Process material
  933. * @param {THREE.Material} material Material to process
  934. * @return {Integer|null} Index of the processed material in the "materials" array
  935. */
  936. processMaterial( material ) {
  937. const cache = this.cache;
  938. const json = this.json;
  939. if ( cache.materials.has( material ) ) return cache.materials.get( material );
  940. if ( material.isShaderMaterial ) {
  941. console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
  942. return null;
  943. }
  944. if ( ! json.materials ) json.materials = [];
  945. // @QUESTION Should we avoid including any attribute that has the default value?
  946. const materialDef = { pbrMetallicRoughness: {} };
  947. if ( material.isMeshStandardMaterial !== true && material.isMeshBasicMaterial !== true ) {
  948. console.warn( 'GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.' );
  949. }
  950. // pbrMetallicRoughness.baseColorFactor
  951. const color = material.color.toArray().concat( [ material.opacity ] );
  952. if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
  953. materialDef.pbrMetallicRoughness.baseColorFactor = color;
  954. }
  955. if ( material.isMeshStandardMaterial ) {
  956. materialDef.pbrMetallicRoughness.metallicFactor = material.metalness;
  957. materialDef.pbrMetallicRoughness.roughnessFactor = material.roughness;
  958. } else {
  959. materialDef.pbrMetallicRoughness.metallicFactor = 0.5;
  960. materialDef.pbrMetallicRoughness.roughnessFactor = 0.5;
  961. }
  962. // pbrMetallicRoughness.metallicRoughnessTexture
  963. if ( material.metalnessMap || material.roughnessMap ) {
  964. const metalRoughTexture = this.buildMetalRoughTexture( material.metalnessMap, material.roughnessMap );
  965. const metalRoughMapDef = {
  966. index: this.processTexture( metalRoughTexture ),
  967. channel: metalRoughTexture.channel
  968. };
  969. this.applyTextureTransform( metalRoughMapDef, metalRoughTexture );
  970. materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
  971. }
  972. // pbrMetallicRoughness.baseColorTexture
  973. if ( material.map ) {
  974. const baseColorMapDef = {
  975. index: this.processTexture( material.map ),
  976. texCoord: material.map.channel
  977. };
  978. this.applyTextureTransform( baseColorMapDef, material.map );
  979. materialDef.pbrMetallicRoughness.baseColorTexture = baseColorMapDef;
  980. }
  981. if ( material.emissive ) {
  982. const emissive = material.emissive;
  983. const maxEmissiveComponent = Math.max( emissive.r, emissive.g, emissive.b );
  984. if ( maxEmissiveComponent > 0 ) {
  985. materialDef.emissiveFactor = material.emissive.toArray();
  986. }
  987. // emissiveTexture
  988. if ( material.emissiveMap ) {
  989. const emissiveMapDef = {
  990. index: this.processTexture( material.emissiveMap ),
  991. texCoord: material.emissiveMap.channel
  992. };
  993. this.applyTextureTransform( emissiveMapDef, material.emissiveMap );
  994. materialDef.emissiveTexture = emissiveMapDef;
  995. }
  996. }
  997. // normalTexture
  998. if ( material.normalMap ) {
  999. const normalMapDef = {
  1000. index: this.processTexture( material.normalMap ),
  1001. texCoord: material.normalMap.channel
  1002. };
  1003. if ( material.normalScale && material.normalScale.x !== 1 ) {
  1004. // glTF normal scale is univariate. Ignore `y`, which may be flipped.
  1005. // Context: https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  1006. normalMapDef.scale = material.normalScale.x;
  1007. }
  1008. this.applyTextureTransform( normalMapDef, material.normalMap );
  1009. materialDef.normalTexture = normalMapDef;
  1010. }
  1011. // occlusionTexture
  1012. if ( material.aoMap ) {
  1013. const occlusionMapDef = {
  1014. index: this.processTexture( material.aoMap ),
  1015. texCoord: material.aoMap.channel
  1016. };
  1017. if ( material.aoMapIntensity !== 1.0 ) {
  1018. occlusionMapDef.strength = material.aoMapIntensity;
  1019. }
  1020. this.applyTextureTransform( occlusionMapDef, material.aoMap );
  1021. materialDef.occlusionTexture = occlusionMapDef;
  1022. }
  1023. // alphaMode
  1024. if ( material.transparent ) {
  1025. materialDef.alphaMode = 'BLEND';
  1026. } else {
  1027. if ( material.alphaTest > 0.0 ) {
  1028. materialDef.alphaMode = 'MASK';
  1029. materialDef.alphaCutoff = material.alphaTest;
  1030. }
  1031. }
  1032. // doubleSided
  1033. if ( material.side === DoubleSide ) materialDef.doubleSided = true;
  1034. if ( material.name !== '' ) materialDef.name = material.name;
  1035. this.serializeUserData( material, materialDef );
  1036. this._invokeAll( function ( ext ) {
  1037. ext.writeMaterial && ext.writeMaterial( material, materialDef );
  1038. } );
  1039. const index = json.materials.push( materialDef ) - 1;
  1040. cache.materials.set( material, index );
  1041. return index;
  1042. }
  1043. /**
  1044. * Process mesh
  1045. * @param {THREE.Mesh} mesh Mesh to process
  1046. * @return {Integer|null} Index of the processed mesh in the "meshes" array
  1047. */
  1048. processMesh( mesh ) {
  1049. const cache = this.cache;
  1050. const json = this.json;
  1051. const meshCacheKeyParts = [ mesh.geometry.uuid ];
  1052. if ( Array.isArray( mesh.material ) ) {
  1053. for ( let i = 0, l = mesh.material.length; i < l; i ++ ) {
  1054. meshCacheKeyParts.push( mesh.material[ i ].uuid );
  1055. }
  1056. } else {
  1057. meshCacheKeyParts.push( mesh.material.uuid );
  1058. }
  1059. const meshCacheKey = meshCacheKeyParts.join( ':' );
  1060. if ( cache.meshes.has( meshCacheKey ) ) return cache.meshes.get( meshCacheKey );
  1061. const geometry = mesh.geometry;
  1062. let mode;
  1063. // Use the correct mode
  1064. if ( mesh.isLineSegments ) {
  1065. mode = WEBGL_CONSTANTS.LINES;
  1066. } else if ( mesh.isLineLoop ) {
  1067. mode = WEBGL_CONSTANTS.LINE_LOOP;
  1068. } else if ( mesh.isLine ) {
  1069. mode = WEBGL_CONSTANTS.LINE_STRIP;
  1070. } else if ( mesh.isPoints ) {
  1071. mode = WEBGL_CONSTANTS.POINTS;
  1072. } else {
  1073. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
  1074. }
  1075. const meshDef = {};
  1076. const attributes = {};
  1077. const primitives = [];
  1078. const targets = [];
  1079. // Conversion between attributes names in threejs and gltf spec
  1080. const nameConversion = {
  1081. uv: 'TEXCOORD_0',
  1082. uv1: 'TEXCOORD_1',
  1083. uv2: 'TEXCOORD_2',
  1084. uv3: 'TEXCOORD_3',
  1085. color: 'COLOR_0',
  1086. skinWeight: 'WEIGHTS_0',
  1087. skinIndex: 'JOINTS_0'
  1088. };
  1089. const originalNormal = geometry.getAttribute( 'normal' );
  1090. if ( originalNormal !== undefined && ! this.isNormalizedNormalAttribute( originalNormal ) ) {
  1091. console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' );
  1092. geometry.setAttribute( 'normal', this.createNormalizedNormalAttribute( originalNormal ) );
  1093. }
  1094. // @QUESTION Detect if .vertexColors = true?
  1095. // For every attribute create an accessor
  1096. let modifiedAttribute = null;
  1097. for ( let attributeName in geometry.attributes ) {
  1098. // Ignore morph target attributes, which are exported later.
  1099. if ( attributeName.slice( 0, 5 ) === 'morph' ) continue;
  1100. const attribute = geometry.attributes[ attributeName ];
  1101. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
  1102. // Prefix all geometry attributes except the ones specifically
  1103. // listed in the spec; non-spec attributes are considered custom.
  1104. const validVertexAttributes =
  1105. /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;
  1106. if ( ! validVertexAttributes.test( attributeName ) ) attributeName = '_' + attributeName;
  1107. if ( cache.attributes.has( this.getUID( attribute ) ) ) {
  1108. attributes[ attributeName ] = cache.attributes.get( this.getUID( attribute ) );
  1109. continue;
  1110. }
  1111. // JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT.
  1112. modifiedAttribute = null;
  1113. const array = attribute.array;
  1114. if ( attributeName === 'JOINTS_0' &&
  1115. ! ( array instanceof Uint16Array ) &&
  1116. ! ( array instanceof Uint8Array ) ) {
  1117. console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' );
  1118. modifiedAttribute = new BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized );
  1119. }
  1120. const accessor = this.processAccessor( modifiedAttribute || attribute, geometry );
  1121. if ( accessor !== null ) {
  1122. if ( ! attributeName.startsWith( '_' ) ) {
  1123. this.detectMeshQuantization( attributeName, attribute );
  1124. }
  1125. attributes[ attributeName ] = accessor;
  1126. cache.attributes.set( this.getUID( attribute ), accessor );
  1127. }
  1128. }
  1129. if ( originalNormal !== undefined ) geometry.setAttribute( 'normal', originalNormal );
  1130. // Skip if no exportable attributes found
  1131. if ( Object.keys( attributes ).length === 0 ) return null;
  1132. // Morph targets
  1133. if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
  1134. const weights = [];
  1135. const targetNames = [];
  1136. const reverseDictionary = {};
  1137. if ( mesh.morphTargetDictionary !== undefined ) {
  1138. for ( const key in mesh.morphTargetDictionary ) {
  1139. reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;
  1140. }
  1141. }
  1142. for ( let i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
  1143. const target = {};
  1144. let warned = false;
  1145. for ( const attributeName in geometry.morphAttributes ) {
  1146. // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
  1147. // Three.js doesn't support TANGENT yet.
  1148. if ( attributeName !== 'position' && attributeName !== 'normal' ) {
  1149. if ( ! warned ) {
  1150. console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
  1151. warned = true;
  1152. }
  1153. continue;
  1154. }
  1155. const attribute = geometry.morphAttributes[ attributeName ][ i ];
  1156. const gltfAttributeName = attributeName.toUpperCase();
  1157. // Three.js morph attribute has absolute values while the one of glTF has relative values.
  1158. //
  1159. // glTF 2.0 Specification:
  1160. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets
  1161. const baseAttribute = geometry.attributes[ attributeName ];
  1162. if ( cache.attributes.has( this.getUID( attribute, true ) ) ) {
  1163. target[ gltfAttributeName ] = cache.attributes.get( this.getUID( attribute, true ) );
  1164. continue;
  1165. }
  1166. // Clones attribute not to override
  1167. const relativeAttribute = attribute.clone();
  1168. if ( ! geometry.morphTargetsRelative ) {
  1169. for ( let j = 0, jl = attribute.count; j < jl; j ++ ) {
  1170. for ( let a = 0; a < attribute.itemSize; a ++ ) {
  1171. if ( a === 0 ) relativeAttribute.setX( j, attribute.getX( j ) - baseAttribute.getX( j ) );
  1172. if ( a === 1 ) relativeAttribute.setY( j, attribute.getY( j ) - baseAttribute.getY( j ) );
  1173. if ( a === 2 ) relativeAttribute.setZ( j, attribute.getZ( j ) - baseAttribute.getZ( j ) );
  1174. if ( a === 3 ) relativeAttribute.setW( j, attribute.getW( j ) - baseAttribute.getW( j ) );
  1175. }
  1176. }
  1177. }
  1178. target[ gltfAttributeName ] = this.processAccessor( relativeAttribute, geometry );
  1179. cache.attributes.set( this.getUID( baseAttribute, true ), target[ gltfAttributeName ] );
  1180. }
  1181. targets.push( target );
  1182. weights.push( mesh.morphTargetInfluences[ i ] );
  1183. if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
  1184. }
  1185. meshDef.weights = weights;
  1186. if ( targetNames.length > 0 ) {
  1187. meshDef.extras = {};
  1188. meshDef.extras.targetNames = targetNames;
  1189. }
  1190. }
  1191. const isMultiMaterial = Array.isArray( mesh.material );
  1192. if ( isMultiMaterial && geometry.groups.length === 0 ) return null;
  1193. let didForceIndices = false;
  1194. if ( isMultiMaterial && geometry.index === null ) {
  1195. const indices = [];
  1196. for ( let i = 0, il = geometry.attributes.position.count; i < il; i ++ ) {
  1197. indices[ i ] = i;
  1198. }
  1199. geometry.setIndex( indices );
  1200. didForceIndices = true;
  1201. }
  1202. const materials = isMultiMaterial ? mesh.material : [ mesh.material ];
  1203. const groups = isMultiMaterial ? geometry.groups : [ { materialIndex: 0, start: undefined, count: undefined } ];
  1204. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  1205. const primitive = {
  1206. mode: mode,
  1207. attributes: attributes,
  1208. };
  1209. this.serializeUserData( geometry, primitive );
  1210. if ( targets.length > 0 ) primitive.targets = targets;
  1211. if ( geometry.index !== null ) {
  1212. let cacheKey = this.getUID( geometry.index );
  1213. if ( groups[ i ].start !== undefined || groups[ i ].count !== undefined ) {
  1214. cacheKey += ':' + groups[ i ].start + ':' + groups[ i ].count;
  1215. }
  1216. if ( cache.attributes.has( cacheKey ) ) {
  1217. primitive.indices = cache.attributes.get( cacheKey );
  1218. } else {
  1219. primitive.indices = this.processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
  1220. cache.attributes.set( cacheKey, primitive.indices );
  1221. }
  1222. if ( primitive.indices === null ) delete primitive.indices;
  1223. }
  1224. const material = this.processMaterial( materials[ groups[ i ].materialIndex ] );
  1225. if ( material !== null ) primitive.material = material;
  1226. primitives.push( primitive );
  1227. }
  1228. if ( didForceIndices === true ) {
  1229. geometry.setIndex( null );
  1230. }
  1231. meshDef.primitives = primitives;
  1232. if ( ! json.meshes ) json.meshes = [];
  1233. this._invokeAll( function ( ext ) {
  1234. ext.writeMesh && ext.writeMesh( mesh, meshDef );
  1235. } );
  1236. const index = json.meshes.push( meshDef ) - 1;
  1237. cache.meshes.set( meshCacheKey, index );
  1238. return index;
  1239. }
  1240. /**
  1241. * If a vertex attribute with a
  1242. * [non-standard data type](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview)
  1243. * is used, it is checked whether it is a valid data type according to the
  1244. * [KHR_mesh_quantization](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_mesh_quantization/README.md)
  1245. * extension.
  1246. * In this case the extension is automatically added to the list of used extensions.
  1247. *
  1248. * @param {string} attributeName
  1249. * @param {THREE.BufferAttribute} attribute
  1250. */
  1251. detectMeshQuantization( attributeName, attribute ) {
  1252. if ( this.extensionsUsed[ KHR_MESH_QUANTIZATION ] ) return;
  1253. let attrType = undefined;
  1254. switch ( attribute.array.constructor ) {
  1255. case Int8Array:
  1256. attrType = 'byte';
  1257. break;
  1258. case Uint8Array:
  1259. attrType = 'unsigned byte';
  1260. break;
  1261. case Int16Array:
  1262. attrType = 'short';
  1263. break;
  1264. case Uint16Array:
  1265. attrType = 'unsigned short';
  1266. break;
  1267. default:
  1268. return;
  1269. }
  1270. if ( attribute.normalized ) attrType += ' normalized';
  1271. const attrNamePrefix = attributeName.split( '_', 1 )[ 0 ];
  1272. if ( KHR_mesh_quantization_ExtraAttrTypes[ attrNamePrefix ] && KHR_mesh_quantization_ExtraAttrTypes[ attrNamePrefix ].includes( attrType ) ) {
  1273. this.extensionsUsed[ KHR_MESH_QUANTIZATION ] = true;
  1274. this.extensionsRequired[ KHR_MESH_QUANTIZATION ] = true;
  1275. }
  1276. }
  1277. /**
  1278. * Process camera
  1279. * @param {THREE.Camera} camera Camera to process
  1280. * @return {Integer} Index of the processed mesh in the "camera" array
  1281. */
  1282. processCamera( camera ) {
  1283. const json = this.json;
  1284. if ( ! json.cameras ) json.cameras = [];
  1285. const isOrtho = camera.isOrthographicCamera;
  1286. const cameraDef = {
  1287. type: isOrtho ? 'orthographic' : 'perspective'
  1288. };
  1289. if ( isOrtho ) {
  1290. cameraDef.orthographic = {
  1291. xmag: camera.right * 2,
  1292. ymag: camera.top * 2,
  1293. zfar: camera.far <= 0 ? 0.001 : camera.far,
  1294. znear: camera.near < 0 ? 0 : camera.near
  1295. };
  1296. } else {
  1297. cameraDef.perspective = {
  1298. aspectRatio: camera.aspect,
  1299. yfov: MathUtils.degToRad( camera.fov ),
  1300. zfar: camera.far <= 0 ? 0.001 : camera.far,
  1301. znear: camera.near < 0 ? 0 : camera.near
  1302. };
  1303. }
  1304. // Question: Is saving "type" as name intentional?
  1305. if ( camera.name !== '' ) cameraDef.name = camera.type;
  1306. return json.cameras.push( cameraDef ) - 1;
  1307. }
  1308. /**
  1309. * Creates glTF animation entry from AnimationClip object.
  1310. *
  1311. * Status:
  1312. * - Only properties listed in PATH_PROPERTIES may be animated.
  1313. *
  1314. * @param {THREE.AnimationClip} clip
  1315. * @param {THREE.Object3D} root
  1316. * @return {number|null}
  1317. */
  1318. processAnimation( clip, root ) {
  1319. const json = this.json;
  1320. const nodeMap = this.nodeMap;
  1321. if ( ! json.animations ) json.animations = [];
  1322. clip = GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root );
  1323. const tracks = clip.tracks;
  1324. const channels = [];
  1325. const samplers = [];
  1326. for ( let i = 0; i < tracks.length; ++ i ) {
  1327. const track = tracks[ i ];
  1328. const trackBinding = PropertyBinding.parseTrackName( track.name );
  1329. let trackNode = PropertyBinding.findNode( root, trackBinding.nodeName );
  1330. const trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
  1331. if ( trackBinding.objectName === 'bones' ) {
  1332. if ( trackNode.isSkinnedMesh === true ) {
  1333. trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
  1334. } else {
  1335. trackNode = undefined;
  1336. }
  1337. }
  1338. if ( ! trackNode || ! trackProperty ) {
  1339. console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
  1340. continue;
  1341. }
  1342. const inputItemSize = 1;
  1343. let outputItemSize = track.values.length / track.times.length;
  1344. if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
  1345. outputItemSize /= trackNode.morphTargetInfluences.length;
  1346. }
  1347. let interpolation;
  1348. // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
  1349. // Detecting glTF cubic spline interpolant by checking factory method's special property
  1350. // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
  1351. // valid value from .getInterpolation().
  1352. if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
  1353. interpolation = 'CUBICSPLINE';
  1354. // itemSize of CUBICSPLINE keyframe is 9
  1355. // (VEC3 * 3: inTangent, splineVertex, and outTangent)
  1356. // but needs to be stored as VEC3 so dividing by 3 here.
  1357. outputItemSize /= 3;
  1358. } else if ( track.getInterpolation() === InterpolateDiscrete ) {
  1359. interpolation = 'STEP';
  1360. } else {
  1361. interpolation = 'LINEAR';
  1362. }
  1363. samplers.push( {
  1364. input: this.processAccessor( new BufferAttribute( track.times, inputItemSize ) ),
  1365. output: this.processAccessor( new BufferAttribute( track.values, outputItemSize ) ),
  1366. interpolation: interpolation
  1367. } );
  1368. channels.push( {
  1369. sampler: samplers.length - 1,
  1370. target: {
  1371. node: nodeMap.get( trackNode ),
  1372. path: trackProperty
  1373. }
  1374. } );
  1375. }
  1376. json.animations.push( {
  1377. name: clip.name || 'clip_' + json.animations.length,
  1378. samplers: samplers,
  1379. channels: channels
  1380. } );
  1381. return json.animations.length - 1;
  1382. }
  1383. /**
  1384. * @param {THREE.Object3D} object
  1385. * @return {number|null}
  1386. */
  1387. processSkin( object ) {
  1388. const json = this.json;
  1389. const nodeMap = this.nodeMap;
  1390. const node = json.nodes[ nodeMap.get( object ) ];
  1391. const skeleton = object.skeleton;
  1392. if ( skeleton === undefined ) return null;
  1393. const rootJoint = object.skeleton.bones[ 0 ];
  1394. if ( rootJoint === undefined ) return null;
  1395. const joints = [];
  1396. const inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
  1397. const temporaryBoneInverse = new Matrix4();
  1398. for ( let i = 0; i < skeleton.bones.length; ++ i ) {
  1399. joints.push( nodeMap.get( skeleton.bones[ i ] ) );
  1400. temporaryBoneInverse.copy( skeleton.boneInverses[ i ] );
  1401. temporaryBoneInverse.multiply( object.bindMatrix ).toArray( inverseBindMatrices, i * 16 );
  1402. }
  1403. if ( json.skins === undefined ) json.skins = [];
  1404. json.skins.push( {
  1405. inverseBindMatrices: this.processAccessor( new BufferAttribute( inverseBindMatrices, 16 ) ),
  1406. joints: joints,
  1407. skeleton: nodeMap.get( rootJoint )
  1408. } );
  1409. const skinIndex = node.skin = json.skins.length - 1;
  1410. return skinIndex;
  1411. }
  1412. /**
  1413. * Process Object3D node
  1414. * @param {THREE.Object3D} node Object3D to processNode
  1415. * @return {Integer} Index of the node in the nodes list
  1416. */
  1417. processNode( object ) {
  1418. const json = this.json;
  1419. const options = this.options;
  1420. const nodeMap = this.nodeMap;
  1421. if ( ! json.nodes ) json.nodes = [];
  1422. const nodeDef = {};
  1423. if ( options.trs ) {
  1424. const rotation = object.quaternion.toArray();
  1425. const position = object.position.toArray();
  1426. const scale = object.scale.toArray();
  1427. if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
  1428. nodeDef.rotation = rotation;
  1429. }
  1430. if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
  1431. nodeDef.translation = position;
  1432. }
  1433. if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
  1434. nodeDef.scale = scale;
  1435. }
  1436. } else {
  1437. if ( object.matrixAutoUpdate ) {
  1438. object.updateMatrix();
  1439. }
  1440. if ( isIdentityMatrix( object.matrix ) === false ) {
  1441. nodeDef.matrix = object.matrix.elements;
  1442. }
  1443. }
  1444. // We don't export empty strings name because it represents no-name in Three.js.
  1445. if ( object.name !== '' ) nodeDef.name = String( object.name );
  1446. this.serializeUserData( object, nodeDef );
  1447. if ( object.isMesh || object.isLine || object.isPoints ) {
  1448. const meshIndex = this.processMesh( object );
  1449. if ( meshIndex !== null ) nodeDef.mesh = meshIndex;
  1450. } else if ( object.isCamera ) {
  1451. nodeDef.camera = this.processCamera( object );
  1452. }
  1453. if ( object.isSkinnedMesh ) this.skins.push( object );
  1454. if ( object.children.length > 0 ) {
  1455. const children = [];
  1456. for ( let i = 0, l = object.children.length; i < l; i ++ ) {
  1457. const child = object.children[ i ];
  1458. if ( child.visible || options.onlyVisible === false ) {
  1459. const nodeIndex = this.processNode( child );
  1460. if ( nodeIndex !== null ) children.push( nodeIndex );
  1461. }
  1462. }
  1463. if ( children.length > 0 ) nodeDef.children = children;
  1464. }
  1465. this._invokeAll( function ( ext ) {
  1466. ext.writeNode && ext.writeNode( object, nodeDef );
  1467. } );
  1468. const nodeIndex = json.nodes.push( nodeDef ) - 1;
  1469. nodeMap.set( object, nodeIndex );
  1470. return nodeIndex;
  1471. }
  1472. /**
  1473. * Process Scene
  1474. * @param {Scene} node Scene to process
  1475. */
  1476. processScene( scene ) {
  1477. const json = this.json;
  1478. const options = this.options;
  1479. if ( ! json.scenes ) {
  1480. json.scenes = [];
  1481. json.scene = 0;
  1482. }
  1483. const sceneDef = {};
  1484. if ( scene.name !== '' ) sceneDef.name = scene.name;
  1485. json.scenes.push( sceneDef );
  1486. const nodes = [];
  1487. for ( let i = 0, l = scene.children.length; i < l; i ++ ) {
  1488. const child = scene.children[ i ];
  1489. if ( child.visible || options.onlyVisible === false ) {
  1490. const nodeIndex = this.processNode( child );
  1491. if ( nodeIndex !== null ) nodes.push( nodeIndex );
  1492. }
  1493. }
  1494. if ( nodes.length > 0 ) sceneDef.nodes = nodes;
  1495. this.serializeUserData( scene, sceneDef );
  1496. }
  1497. /**
  1498. * Creates a Scene to hold a list of objects and parse it
  1499. * @param {Array} objects List of objects to process
  1500. */
  1501. processObjects( objects ) {
  1502. const scene = new Scene();
  1503. scene.name = 'AuxScene';
  1504. for ( let i = 0; i < objects.length; i ++ ) {
  1505. // We push directly to children instead of calling `add` to prevent
  1506. // modify the .parent and break its original scene and hierarchy
  1507. scene.children.push( objects[ i ] );
  1508. }
  1509. this.processScene( scene );
  1510. }
  1511. /**
  1512. * @param {THREE.Object3D|Array<THREE.Object3D>} input
  1513. */
  1514. processInput( input ) {
  1515. const options = this.options;
  1516. input = input instanceof Array ? input : [ input ];
  1517. this._invokeAll( function ( ext ) {
  1518. ext.beforeParse && ext.beforeParse( input );
  1519. } );
  1520. const objectsWithoutScene = [];
  1521. for ( let i = 0; i < input.length; i ++ ) {
  1522. if ( input[ i ] instanceof Scene ) {
  1523. this.processScene( input[ i ] );
  1524. } else {
  1525. objectsWithoutScene.push( input[ i ] );
  1526. }
  1527. }
  1528. if ( objectsWithoutScene.length > 0 ) this.processObjects( objectsWithoutScene );
  1529. for ( let i = 0; i < this.skins.length; ++ i ) {
  1530. this.processSkin( this.skins[ i ] );
  1531. }
  1532. for ( let i = 0; i < options.animations.length; ++ i ) {
  1533. this.processAnimation( options.animations[ i ], input[ 0 ] );
  1534. }
  1535. this._invokeAll( function ( ext ) {
  1536. ext.afterParse && ext.afterParse( input );
  1537. } );
  1538. }
  1539. _invokeAll( func ) {
  1540. for ( let i = 0, il = this.plugins.length; i < il; i ++ ) {
  1541. func( this.plugins[ i ] );
  1542. }
  1543. }
  1544. }
  1545. /**
  1546. * Punctual Lights Extension
  1547. *
  1548. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  1549. */
  1550. class GLTFLightExtension {
  1551. constructor( writer ) {
  1552. this.writer = writer;
  1553. this.name = 'KHR_lights_punctual';
  1554. }
  1555. writeNode( light, nodeDef ) {
  1556. if ( ! light.isLight ) return;
  1557. if ( ! light.isDirectionalLight && ! light.isPointLight && ! light.isSpotLight ) {
  1558. console.warn( 'THREE.GLTFExporter: Only directional, point, and spot lights are supported.', light );
  1559. return;
  1560. }
  1561. const writer = this.writer;
  1562. const json = writer.json;
  1563. const extensionsUsed = writer.extensionsUsed;
  1564. const lightDef = {};
  1565. if ( light.name ) lightDef.name = light.name;
  1566. lightDef.color = light.color.toArray();
  1567. lightDef.intensity = light.intensity;
  1568. if ( light.isDirectionalLight ) {
  1569. lightDef.type = 'directional';
  1570. } else if ( light.isPointLight ) {
  1571. lightDef.type = 'point';
  1572. if ( light.distance > 0 ) lightDef.range = light.distance;
  1573. } else if ( light.isSpotLight ) {
  1574. lightDef.type = 'spot';
  1575. if ( light.distance > 0 ) lightDef.range = light.distance;
  1576. lightDef.spot = {};
  1577. lightDef.spot.innerConeAngle = ( 1.0 - light.penumbra ) * light.angle;
  1578. lightDef.spot.outerConeAngle = light.angle;
  1579. }
  1580. if ( light.decay !== undefined && light.decay !== 2 ) {
  1581. console.warn( 'THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, '
  1582. + 'and expects light.decay=2.' );
  1583. }
  1584. if ( light.target
  1585. && ( light.target.parent !== light
  1586. || light.target.position.x !== 0
  1587. || light.target.position.y !== 0
  1588. || light.target.position.z !== - 1 ) ) {
  1589. console.warn( 'THREE.GLTFExporter: Light direction may be lost. For best results, '
  1590. + 'make light.target a child of the light with position 0,0,-1.' );
  1591. }
  1592. if ( ! extensionsUsed[ this.name ] ) {
  1593. json.extensions = json.extensions || {};
  1594. json.extensions[ this.name ] = { lights: [] };
  1595. extensionsUsed[ this.name ] = true;
  1596. }
  1597. const lights = json.extensions[ this.name ].lights;
  1598. lights.push( lightDef );
  1599. nodeDef.extensions = nodeDef.extensions || {};
  1600. nodeDef.extensions[ this.name ] = { light: lights.length - 1 };
  1601. }
  1602. }
  1603. /**
  1604. * Unlit Materials Extension
  1605. *
  1606. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  1607. */
  1608. class GLTFMaterialsUnlitExtension {
  1609. constructor( writer ) {
  1610. this.writer = writer;
  1611. this.name = 'KHR_materials_unlit';
  1612. }
  1613. writeMaterial( material, materialDef ) {
  1614. if ( ! material.isMeshBasicMaterial ) return;
  1615. const writer = this.writer;
  1616. const extensionsUsed = writer.extensionsUsed;
  1617. materialDef.extensions = materialDef.extensions || {};
  1618. materialDef.extensions[ this.name ] = {};
  1619. extensionsUsed[ this.name ] = true;
  1620. materialDef.pbrMetallicRoughness.metallicFactor = 0.0;
  1621. materialDef.pbrMetallicRoughness.roughnessFactor = 0.9;
  1622. }
  1623. }
  1624. /**
  1625. * Clearcoat Materials Extension
  1626. *
  1627. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  1628. */
  1629. class GLTFMaterialsClearcoatExtension {
  1630. constructor( writer ) {
  1631. this.writer = writer;
  1632. this.name = 'KHR_materials_clearcoat';
  1633. }
  1634. writeMaterial( material, materialDef ) {
  1635. if ( ! material.isMeshPhysicalMaterial || material.clearcoat === 0 ) return;
  1636. const writer = this.writer;
  1637. const extensionsUsed = writer.extensionsUsed;
  1638. const extensionDef = {};
  1639. extensionDef.clearcoatFactor = material.clearcoat;
  1640. if ( material.clearcoatMap ) {
  1641. const clearcoatMapDef = {
  1642. index: writer.processTexture( material.clearcoatMap ),
  1643. texCoord: material.clearcoatMap.channel
  1644. };
  1645. writer.applyTextureTransform( clearcoatMapDef, material.clearcoatMap );
  1646. extensionDef.clearcoatTexture = clearcoatMapDef;
  1647. }
  1648. extensionDef.clearcoatRoughnessFactor = material.clearcoatRoughness;
  1649. if ( material.clearcoatRoughnessMap ) {
  1650. const clearcoatRoughnessMapDef = {
  1651. index: writer.processTexture( material.clearcoatRoughnessMap ),
  1652. texCoord: material.clearcoatRoughnessMap.channel
  1653. };
  1654. writer.applyTextureTransform( clearcoatRoughnessMapDef, material.clearcoatRoughnessMap );
  1655. extensionDef.clearcoatRoughnessTexture = clearcoatRoughnessMapDef;
  1656. }
  1657. if ( material.clearcoatNormalMap ) {
  1658. const clearcoatNormalMapDef = {
  1659. index: writer.processTexture( material.clearcoatNormalMap ),
  1660. texCoord: material.clearcoatNormalMap.channel
  1661. };
  1662. if ( material.clearcoatNormalScale.x !== 1 ) clearcoatNormalMapDef.scale = material.clearcoatNormalScale.x;
  1663. writer.applyTextureTransform( clearcoatNormalMapDef, material.clearcoatNormalMap );
  1664. extensionDef.clearcoatNormalTexture = clearcoatNormalMapDef;
  1665. }
  1666. materialDef.extensions = materialDef.extensions || {};
  1667. materialDef.extensions[ this.name ] = extensionDef;
  1668. extensionsUsed[ this.name ] = true;
  1669. }
  1670. }
  1671. /**
  1672. * Materials dispersion Extension
  1673. *
  1674. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_dispersion
  1675. */
  1676. class GLTFMaterialsDispersionExtension {
  1677. constructor( writer ) {
  1678. this.writer = writer;
  1679. this.name = 'KHR_materials_dispersion';
  1680. }
  1681. writeMaterial( material, materialDef ) {
  1682. if ( ! material.isMeshPhysicalMaterial || material.dispersion === 0 ) return;
  1683. const writer = this.writer;
  1684. const extensionsUsed = writer.extensionsUsed;
  1685. const extensionDef = {};
  1686. extensionDef.dispersion = material.dispersion;
  1687. materialDef.extensions = materialDef.extensions || {};
  1688. materialDef.extensions[ this.name ] = extensionDef;
  1689. extensionsUsed[ this.name ] = true;
  1690. }
  1691. }
  1692. /**
  1693. * Iridescence Materials Extension
  1694. *
  1695. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence
  1696. */
  1697. class GLTFMaterialsIridescenceExtension {
  1698. constructor( writer ) {
  1699. this.writer = writer;
  1700. this.name = 'KHR_materials_iridescence';
  1701. }
  1702. writeMaterial( material, materialDef ) {
  1703. if ( ! material.isMeshPhysicalMaterial || material.iridescence === 0 ) return;
  1704. const writer = this.writer;
  1705. const extensionsUsed = writer.extensionsUsed;
  1706. const extensionDef = {};
  1707. extensionDef.iridescenceFactor = material.iridescence;
  1708. if ( material.iridescenceMap ) {
  1709. const iridescenceMapDef = {
  1710. index: writer.processTexture( material.iridescenceMap ),
  1711. texCoord: material.iridescenceMap.channel
  1712. };
  1713. writer.applyTextureTransform( iridescenceMapDef, material.iridescenceMap );
  1714. extensionDef.iridescenceTexture = iridescenceMapDef;
  1715. }
  1716. extensionDef.iridescenceIor = material.iridescenceIOR;
  1717. extensionDef.iridescenceThicknessMinimum = material.iridescenceThicknessRange[ 0 ];
  1718. extensionDef.iridescenceThicknessMaximum = material.iridescenceThicknessRange[ 1 ];
  1719. if ( material.iridescenceThicknessMap ) {
  1720. const iridescenceThicknessMapDef = {
  1721. index: writer.processTexture( material.iridescenceThicknessMap ),
  1722. texCoord: material.iridescenceThicknessMap.channel
  1723. };
  1724. writer.applyTextureTransform( iridescenceThicknessMapDef, material.iridescenceThicknessMap );
  1725. extensionDef.iridescenceThicknessTexture = iridescenceThicknessMapDef;
  1726. }
  1727. materialDef.extensions = materialDef.extensions || {};
  1728. materialDef.extensions[ this.name ] = extensionDef;
  1729. extensionsUsed[ this.name ] = true;
  1730. }
  1731. }
  1732. /**
  1733. * Transmission Materials Extension
  1734. *
  1735. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  1736. */
  1737. class GLTFMaterialsTransmissionExtension {
  1738. constructor( writer ) {
  1739. this.writer = writer;
  1740. this.name = 'KHR_materials_transmission';
  1741. }
  1742. writeMaterial( material, materialDef ) {
  1743. if ( ! material.isMeshPhysicalMaterial || material.transmission === 0 ) return;
  1744. const writer = this.writer;
  1745. const extensionsUsed = writer.extensionsUsed;
  1746. const extensionDef = {};
  1747. extensionDef.transmissionFactor = material.transmission;
  1748. if ( material.transmissionMap ) {
  1749. const transmissionMapDef = {
  1750. index: writer.processTexture( material.transmissionMap ),
  1751. texCoord: material.transmissionMap.channel
  1752. };
  1753. writer.applyTextureTransform( transmissionMapDef, material.transmissionMap );
  1754. extensionDef.transmissionTexture = transmissionMapDef;
  1755. }
  1756. materialDef.extensions = materialDef.extensions || {};
  1757. materialDef.extensions[ this.name ] = extensionDef;
  1758. extensionsUsed[ this.name ] = true;
  1759. }
  1760. }
  1761. /**
  1762. * Materials Volume Extension
  1763. *
  1764. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume
  1765. */
  1766. class GLTFMaterialsVolumeExtension {
  1767. constructor( writer ) {
  1768. this.writer = writer;
  1769. this.name = 'KHR_materials_volume';
  1770. }
  1771. writeMaterial( material, materialDef ) {
  1772. if ( ! material.isMeshPhysicalMaterial || material.transmission === 0 ) return;
  1773. const writer = this.writer;
  1774. const extensionsUsed = writer.extensionsUsed;
  1775. const extensionDef = {};
  1776. extensionDef.thicknessFactor = material.thickness;
  1777. if ( material.thicknessMap ) {
  1778. const thicknessMapDef = {
  1779. index: writer.processTexture( material.thicknessMap ),
  1780. texCoord: material.thicknessMap.channel
  1781. };
  1782. writer.applyTextureTransform( thicknessMapDef, material.thicknessMap );
  1783. extensionDef.thicknessTexture = thicknessMapDef;
  1784. }
  1785. if ( material.attenuationDistance !== Infinity ) {
  1786. extensionDef.attenuationDistance = material.attenuationDistance;
  1787. }
  1788. extensionDef.attenuationColor = material.attenuationColor.toArray();
  1789. materialDef.extensions = materialDef.extensions || {};
  1790. materialDef.extensions[ this.name ] = extensionDef;
  1791. extensionsUsed[ this.name ] = true;
  1792. }
  1793. }
  1794. /**
  1795. * Materials ior Extension
  1796. *
  1797. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior
  1798. */
  1799. class GLTFMaterialsIorExtension {
  1800. constructor( writer ) {
  1801. this.writer = writer;
  1802. this.name = 'KHR_materials_ior';
  1803. }
  1804. writeMaterial( material, materialDef ) {
  1805. if ( ! material.isMeshPhysicalMaterial || material.ior === 1.5 ) return;
  1806. const writer = this.writer;
  1807. const extensionsUsed = writer.extensionsUsed;
  1808. const extensionDef = {};
  1809. extensionDef.ior = material.ior;
  1810. materialDef.extensions = materialDef.extensions || {};
  1811. materialDef.extensions[ this.name ] = extensionDef;
  1812. extensionsUsed[ this.name ] = true;
  1813. }
  1814. }
  1815. /**
  1816. * Materials specular Extension
  1817. *
  1818. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular
  1819. */
  1820. class GLTFMaterialsSpecularExtension {
  1821. constructor( writer ) {
  1822. this.writer = writer;
  1823. this.name = 'KHR_materials_specular';
  1824. }
  1825. writeMaterial( material, materialDef ) {
  1826. if ( ! material.isMeshPhysicalMaterial || ( material.specularIntensity === 1.0 &&
  1827. material.specularColor.equals( DEFAULT_SPECULAR_COLOR ) &&
  1828. ! material.specularIntensityMap && ! material.specularColorMap ) ) return;
  1829. const writer = this.writer;
  1830. const extensionsUsed = writer.extensionsUsed;
  1831. const extensionDef = {};
  1832. if ( material.specularIntensityMap ) {
  1833. const specularIntensityMapDef = {
  1834. index: writer.processTexture( material.specularIntensityMap ),
  1835. texCoord: material.specularIntensityMap.channel
  1836. };
  1837. writer.applyTextureTransform( specularIntensityMapDef, material.specularIntensityMap );
  1838. extensionDef.specularTexture = specularIntensityMapDef;
  1839. }
  1840. if ( material.specularColorMap ) {
  1841. const specularColorMapDef = {
  1842. index: writer.processTexture( material.specularColorMap ),
  1843. texCoord: material.specularColorMap.channel
  1844. };
  1845. writer.applyTextureTransform( specularColorMapDef, material.specularColorMap );
  1846. extensionDef.specularColorTexture = specularColorMapDef;
  1847. }
  1848. extensionDef.specularFactor = material.specularIntensity;
  1849. extensionDef.specularColorFactor = material.specularColor.toArray();
  1850. materialDef.extensions = materialDef.extensions || {};
  1851. materialDef.extensions[ this.name ] = extensionDef;
  1852. extensionsUsed[ this.name ] = true;
  1853. }
  1854. }
  1855. /**
  1856. * Sheen Materials Extension
  1857. *
  1858. * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen
  1859. */
  1860. class GLTFMaterialsSheenExtension {
  1861. constructor( writer ) {
  1862. this.writer = writer;
  1863. this.name = 'KHR_materials_sheen';
  1864. }
  1865. writeMaterial( material, materialDef ) {
  1866. if ( ! material.isMeshPhysicalMaterial || material.sheen == 0.0 ) return;
  1867. const writer = this.writer;
  1868. const extensionsUsed = writer.extensionsUsed;
  1869. const extensionDef = {};
  1870. if ( material.sheenRoughnessMap ) {
  1871. const sheenRoughnessMapDef = {
  1872. index: writer.processTexture( material.sheenRoughnessMap ),
  1873. texCoord: material.sheenRoughnessMap.channel
  1874. };
  1875. writer.applyTextureTransform( sheenRoughnessMapDef, material.sheenRoughnessMap );
  1876. extensionDef.sheenRoughnessTexture = sheenRoughnessMapDef;
  1877. }
  1878. if ( material.sheenColorMap ) {
  1879. const sheenColorMapDef = {
  1880. index: writer.processTexture( material.sheenColorMap ),
  1881. texCoord: material.sheenColorMap.channel
  1882. };
  1883. writer.applyTextureTransform( sheenColorMapDef, material.sheenColorMap );
  1884. extensionDef.sheenColorTexture = sheenColorMapDef;
  1885. }
  1886. extensionDef.sheenRoughnessFactor = material.sheenRoughness;
  1887. extensionDef.sheenColorFactor = material.sheenColor.toArray();
  1888. materialDef.extensions = materialDef.extensions || {};
  1889. materialDef.extensions[ this.name ] = extensionDef;
  1890. extensionsUsed[ this.name ] = true;
  1891. }
  1892. }
  1893. /**
  1894. * Anisotropy Materials Extension
  1895. *
  1896. * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_anisotropy
  1897. */
  1898. class GLTFMaterialsAnisotropyExtension {
  1899. constructor( writer ) {
  1900. this.writer = writer;
  1901. this.name = 'KHR_materials_anisotropy';
  1902. }
  1903. writeMaterial( material, materialDef ) {
  1904. if ( ! material.isMeshPhysicalMaterial || material.anisotropy == 0.0 ) return;
  1905. const writer = this.writer;
  1906. const extensionsUsed = writer.extensionsUsed;
  1907. const extensionDef = {};
  1908. if ( material.anisotropyMap ) {
  1909. const anisotropyMapDef = { index: writer.processTexture( material.anisotropyMap ) };
  1910. writer.applyTextureTransform( anisotropyMapDef, material.anisotropyMap );
  1911. extensionDef.anisotropyTexture = anisotropyMapDef;
  1912. }
  1913. extensionDef.anisotropyStrength = material.anisotropy;
  1914. extensionDef.anisotropyRotation = material.anisotropyRotation;
  1915. materialDef.extensions = materialDef.extensions || {};
  1916. materialDef.extensions[ this.name ] = extensionDef;
  1917. extensionsUsed[ this.name ] = true;
  1918. }
  1919. }
  1920. /**
  1921. * Materials Emissive Strength Extension
  1922. *
  1923. * Specification: https://github.com/KhronosGroup/glTF/blob/5768b3ce0ef32bc39cdf1bef10b948586635ead3/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md
  1924. */
  1925. class GLTFMaterialsEmissiveStrengthExtension {
  1926. constructor( writer ) {
  1927. this.writer = writer;
  1928. this.name = 'KHR_materials_emissive_strength';
  1929. }
  1930. writeMaterial( material, materialDef ) {
  1931. if ( ! material.isMeshStandardMaterial || material.emissiveIntensity === 1.0 ) return;
  1932. const writer = this.writer;
  1933. const extensionsUsed = writer.extensionsUsed;
  1934. const extensionDef = {};
  1935. extensionDef.emissiveStrength = material.emissiveIntensity;
  1936. materialDef.extensions = materialDef.extensions || {};
  1937. materialDef.extensions[ this.name ] = extensionDef;
  1938. extensionsUsed[ this.name ] = true;
  1939. }
  1940. }
  1941. /**
  1942. * Materials bump Extension
  1943. *
  1944. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/EXT_materials_bump
  1945. */
  1946. class GLTFMaterialsBumpExtension {
  1947. constructor( writer ) {
  1948. this.writer = writer;
  1949. this.name = 'EXT_materials_bump';
  1950. }
  1951. writeMaterial( material, materialDef ) {
  1952. if ( ! material.isMeshStandardMaterial || (
  1953. material.bumpScale === 1 &&
  1954. ! material.bumpMap ) ) return;
  1955. const writer = this.writer;
  1956. const extensionsUsed = writer.extensionsUsed;
  1957. const extensionDef = {};
  1958. if ( material.bumpMap ) {
  1959. const bumpMapDef = {
  1960. index: writer.processTexture( material.bumpMap ),
  1961. texCoord: material.bumpMap.channel
  1962. };
  1963. writer.applyTextureTransform( bumpMapDef, material.bumpMap );
  1964. extensionDef.bumpTexture = bumpMapDef;
  1965. }
  1966. extensionDef.bumpFactor = material.bumpScale;
  1967. materialDef.extensions = materialDef.extensions || {};
  1968. materialDef.extensions[ this.name ] = extensionDef;
  1969. extensionsUsed[ this.name ] = true;
  1970. }
  1971. }
  1972. /**
  1973. * GPU Instancing Extension
  1974. *
  1975. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_mesh_gpu_instancing
  1976. */
  1977. class GLTFMeshGpuInstancing {
  1978. constructor( writer ) {
  1979. this.writer = writer;
  1980. this.name = 'EXT_mesh_gpu_instancing';
  1981. }
  1982. writeNode( object, nodeDef ) {
  1983. if ( ! object.isInstancedMesh ) return;
  1984. const writer = this.writer;
  1985. const mesh = object;
  1986. const translationAttr = new Float32Array( mesh.count * 3 );
  1987. const rotationAttr = new Float32Array( mesh.count * 4 );
  1988. const scaleAttr = new Float32Array( mesh.count * 3 );
  1989. const matrix = new Matrix4();
  1990. const position = new Vector3();
  1991. const quaternion = new Quaternion();
  1992. const scale = new Vector3();
  1993. for ( let i = 0; i < mesh.count; i ++ ) {
  1994. mesh.getMatrixAt( i, matrix );
  1995. matrix.decompose( position, quaternion, scale );
  1996. position.toArray( translationAttr, i * 3 );
  1997. quaternion.toArray( rotationAttr, i * 4 );
  1998. scale.toArray( scaleAttr, i * 3 );
  1999. }
  2000. const attributes = {
  2001. TRANSLATION: writer.processAccessor( new BufferAttribute( translationAttr, 3 ) ),
  2002. ROTATION: writer.processAccessor( new BufferAttribute( rotationAttr, 4 ) ),
  2003. SCALE: writer.processAccessor( new BufferAttribute( scaleAttr, 3 ) ),
  2004. };
  2005. if ( mesh.instanceColor )
  2006. attributes._COLOR_0 = writer.processAccessor( mesh.instanceColor );
  2007. nodeDef.extensions = nodeDef.extensions || {};
  2008. nodeDef.extensions[ this.name ] = { attributes };
  2009. writer.extensionsUsed[ this.name ] = true;
  2010. writer.extensionsRequired[ this.name ] = true;
  2011. }
  2012. }
  2013. /**
  2014. * Static utility functions
  2015. */
  2016. GLTFExporter.Utils = {
  2017. insertKeyframe: function ( track, time ) {
  2018. const tolerance = 0.001; // 1ms
  2019. const valueSize = track.getValueSize();
  2020. const times = new track.TimeBufferType( track.times.length + 1 );
  2021. const values = new track.ValueBufferType( track.values.length + valueSize );
  2022. const interpolant = track.createInterpolant( new track.ValueBufferType( valueSize ) );
  2023. let index;
  2024. if ( track.times.length === 0 ) {
  2025. times[ 0 ] = time;
  2026. for ( let i = 0; i < valueSize; i ++ ) {
  2027. values[ i ] = 0;
  2028. }
  2029. index = 0;
  2030. } else if ( time < track.times[ 0 ] ) {
  2031. if ( Math.abs( track.times[ 0 ] - time ) < tolerance ) return 0;
  2032. times[ 0 ] = time;
  2033. times.set( track.times, 1 );
  2034. values.set( interpolant.evaluate( time ), 0 );
  2035. values.set( track.values, valueSize );
  2036. index = 0;
  2037. } else if ( time > track.times[ track.times.length - 1 ] ) {
  2038. if ( Math.abs( track.times[ track.times.length - 1 ] - time ) < tolerance ) {
  2039. return track.times.length - 1;
  2040. }
  2041. times[ times.length - 1 ] = time;
  2042. times.set( track.times, 0 );
  2043. values.set( track.values, 0 );
  2044. values.set( interpolant.evaluate( time ), track.values.length );
  2045. index = times.length - 1;
  2046. } else {
  2047. for ( let i = 0; i < track.times.length; i ++ ) {
  2048. if ( Math.abs( track.times[ i ] - time ) < tolerance ) return i;
  2049. if ( track.times[ i ] < time && track.times[ i + 1 ] > time ) {
  2050. times.set( track.times.slice( 0, i + 1 ), 0 );
  2051. times[ i + 1 ] = time;
  2052. times.set( track.times.slice( i + 1 ), i + 2 );
  2053. values.set( track.values.slice( 0, ( i + 1 ) * valueSize ), 0 );
  2054. values.set( interpolant.evaluate( time ), ( i + 1 ) * valueSize );
  2055. values.set( track.values.slice( ( i + 1 ) * valueSize ), ( i + 2 ) * valueSize );
  2056. index = i + 1;
  2057. break;
  2058. }
  2059. }
  2060. }
  2061. track.times = times;
  2062. track.values = values;
  2063. return index;
  2064. },
  2065. mergeMorphTargetTracks: function ( clip, root ) {
  2066. const tracks = [];
  2067. const mergedTracks = {};
  2068. const sourceTracks = clip.tracks;
  2069. for ( let i = 0; i < sourceTracks.length; ++ i ) {
  2070. let sourceTrack = sourceTracks[ i ];
  2071. const sourceTrackBinding = PropertyBinding.parseTrackName( sourceTrack.name );
  2072. const sourceTrackNode = PropertyBinding.findNode( root, sourceTrackBinding.nodeName );
  2073. if ( sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined ) {
  2074. // Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is.
  2075. tracks.push( sourceTrack );
  2076. continue;
  2077. }
  2078. if ( sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete
  2079. && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear ) {
  2080. if ( sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  2081. // This should never happen, because glTF morph target animations
  2082. // affect all targets already.
  2083. throw new Error( 'THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.' );
  2084. }
  2085. console.warn( 'THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.' );
  2086. sourceTrack = sourceTrack.clone();
  2087. sourceTrack.setInterpolation( InterpolateLinear );
  2088. }
  2089. const targetCount = sourceTrackNode.morphTargetInfluences.length;
  2090. const targetIndex = sourceTrackNode.morphTargetDictionary[ sourceTrackBinding.propertyIndex ];
  2091. if ( targetIndex === undefined ) {
  2092. throw new Error( 'THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex );
  2093. }
  2094. let mergedTrack;
  2095. // If this is the first time we've seen this object, create a new
  2096. // track to store merged keyframe data for each morph target.
  2097. if ( mergedTracks[ sourceTrackNode.uuid ] === undefined ) {
  2098. mergedTrack = sourceTrack.clone();
  2099. const values = new mergedTrack.ValueBufferType( targetCount * mergedTrack.times.length );
  2100. for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
  2101. values[ j * targetCount + targetIndex ] = mergedTrack.values[ j ];
  2102. }
  2103. // We need to take into consideration the intended target node
  2104. // of our original un-merged morphTarget animation.
  2105. mergedTrack.name = ( sourceTrackBinding.nodeName || '' ) + '.morphTargetInfluences';
  2106. mergedTrack.values = values;
  2107. mergedTracks[ sourceTrackNode.uuid ] = mergedTrack;
  2108. tracks.push( mergedTrack );
  2109. continue;
  2110. }
  2111. const sourceInterpolant = sourceTrack.createInterpolant( new sourceTrack.ValueBufferType( 1 ) );
  2112. mergedTrack = mergedTracks[ sourceTrackNode.uuid ];
  2113. // For every existing keyframe of the merged track, write a (possibly
  2114. // interpolated) value from the source track.
  2115. for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
  2116. mergedTrack.values[ j * targetCount + targetIndex ] = sourceInterpolant.evaluate( mergedTrack.times[ j ] );
  2117. }
  2118. // For every existing keyframe of the source track, write a (possibly
  2119. // new) keyframe to the merged track. Values from the previous loop may
  2120. // be written again, but keyframes are de-duplicated.
  2121. for ( let j = 0; j < sourceTrack.times.length; j ++ ) {
  2122. const keyframeIndex = this.insertKeyframe( mergedTrack, sourceTrack.times[ j ] );
  2123. mergedTrack.values[ keyframeIndex * targetCount + targetIndex ] = sourceTrack.values[ j ];
  2124. }
  2125. }
  2126. clip.tracks = tracks;
  2127. return clip;
  2128. }
  2129. };
  2130. export { GLTFExporter };