GLTFExporter.js 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380
  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. context.fillStyle = '#00ffff';
  580. context.fillRect( 0, 0, width, height );
  581. const composite = context.getImageData( 0, 0, width, height );
  582. if ( metalness ) {
  583. context.drawImage( metalness, 0, 0, width, height );
  584. const convert = getEncodingConversion( metalnessMap );
  585. const data = context.getImageData( 0, 0, width, height ).data;
  586. for ( let i = 2; i < data.length; i += 4 ) {
  587. composite.data[ i ] = convert( data[ i ] / 256 ) * 256;
  588. }
  589. }
  590. if ( roughness ) {
  591. context.drawImage( roughness, 0, 0, width, height );
  592. const convert = getEncodingConversion( roughnessMap );
  593. const data = context.getImageData( 0, 0, width, height ).data;
  594. for ( let i = 1; i < data.length; i += 4 ) {
  595. composite.data[ i ] = convert( data[ i ] / 256 ) * 256;
  596. }
  597. }
  598. context.putImageData( composite, 0, 0 );
  599. //
  600. const reference = metalnessMap || roughnessMap;
  601. const texture = reference.clone();
  602. texture.source = new Source( canvas );
  603. texture.colorSpace = NoColorSpace;
  604. texture.channel = ( metalnessMap || roughnessMap ).channel;
  605. if ( metalnessMap && roughnessMap && metalnessMap.channel !== roughnessMap.channel ) {
  606. console.warn( 'THREE.GLTFExporter: UV channels for metalnessMap and roughnessMap textures must match.' );
  607. }
  608. return texture;
  609. }
  610. /**
  611. * Process a buffer to append to the default one.
  612. * @param {ArrayBuffer} buffer
  613. * @return {Integer}
  614. */
  615. processBuffer( buffer ) {
  616. const json = this.json;
  617. const buffers = this.buffers;
  618. if ( ! json.buffers ) json.buffers = [ { byteLength: 0 } ];
  619. // All buffers are merged before export.
  620. buffers.push( buffer );
  621. return 0;
  622. }
  623. /**
  624. * Process and generate a BufferView
  625. * @param {BufferAttribute} attribute
  626. * @param {number} componentType
  627. * @param {number} start
  628. * @param {number} count
  629. * @param {number} target (Optional) Target usage of the BufferView
  630. * @return {Object}
  631. */
  632. processBufferView( attribute, componentType, start, count, target ) {
  633. const json = this.json;
  634. if ( ! json.bufferViews ) json.bufferViews = [];
  635. // Create a new dataview and dump the attribute's array into it
  636. let componentSize;
  637. switch ( componentType ) {
  638. case WEBGL_CONSTANTS.BYTE:
  639. case WEBGL_CONSTANTS.UNSIGNED_BYTE:
  640. componentSize = 1;
  641. break;
  642. case WEBGL_CONSTANTS.SHORT:
  643. case WEBGL_CONSTANTS.UNSIGNED_SHORT:
  644. componentSize = 2;
  645. break;
  646. default:
  647. componentSize = 4;
  648. }
  649. let byteStride = attribute.itemSize * componentSize;
  650. if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
  651. // Each element of a vertex attribute MUST be aligned to 4-byte boundaries
  652. // inside a bufferView
  653. byteStride = Math.ceil( byteStride / 4 ) * 4;
  654. }
  655. const byteLength = getPaddedBufferSize( count * byteStride );
  656. const dataView = new DataView( new ArrayBuffer( byteLength ) );
  657. let offset = 0;
  658. for ( let i = start; i < start + count; i ++ ) {
  659. for ( let a = 0; a < attribute.itemSize; a ++ ) {
  660. let value;
  661. if ( attribute.itemSize > 4 ) {
  662. // no support for interleaved data for itemSize > 4
  663. value = attribute.array[ i * attribute.itemSize + a ];
  664. } else {
  665. if ( a === 0 ) value = attribute.getX( i );
  666. else if ( a === 1 ) value = attribute.getY( i );
  667. else if ( a === 2 ) value = attribute.getZ( i );
  668. else if ( a === 3 ) value = attribute.getW( i );
  669. if ( attribute.normalized === true ) {
  670. value = MathUtils.normalize( value, attribute.array );
  671. }
  672. }
  673. if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
  674. dataView.setFloat32( offset, value, true );
  675. } else if ( componentType === WEBGL_CONSTANTS.INT ) {
  676. dataView.setInt32( offset, value, true );
  677. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
  678. dataView.setUint32( offset, value, true );
  679. } else if ( componentType === WEBGL_CONSTANTS.SHORT ) {
  680. dataView.setInt16( offset, value, true );
  681. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
  682. dataView.setUint16( offset, value, true );
  683. } else if ( componentType === WEBGL_CONSTANTS.BYTE ) {
  684. dataView.setInt8( offset, value );
  685. } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
  686. dataView.setUint8( offset, value );
  687. }
  688. offset += componentSize;
  689. }
  690. if ( ( offset % byteStride ) !== 0 ) {
  691. offset += byteStride - ( offset % byteStride );
  692. }
  693. }
  694. const bufferViewDef = {
  695. buffer: this.processBuffer( dataView.buffer ),
  696. byteOffset: this.byteOffset,
  697. byteLength: byteLength
  698. };
  699. if ( target !== undefined ) bufferViewDef.target = target;
  700. if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
  701. // Only define byteStride for vertex attributes.
  702. bufferViewDef.byteStride = byteStride;
  703. }
  704. this.byteOffset += byteLength;
  705. json.bufferViews.push( bufferViewDef );
  706. // @TODO Merge bufferViews where possible.
  707. const output = {
  708. id: json.bufferViews.length - 1,
  709. byteLength: 0
  710. };
  711. return output;
  712. }
  713. /**
  714. * Process and generate a BufferView from an image Blob.
  715. * @param {Blob} blob
  716. * @return {Promise<Integer>}
  717. */
  718. processBufferViewImage( blob ) {
  719. const writer = this;
  720. const json = writer.json;
  721. if ( ! json.bufferViews ) json.bufferViews = [];
  722. return new Promise( function ( resolve ) {
  723. const reader = new FileReader();
  724. reader.readAsArrayBuffer( blob );
  725. reader.onloadend = function () {
  726. const buffer = getPaddedArrayBuffer( reader.result );
  727. const bufferViewDef = {
  728. buffer: writer.processBuffer( buffer ),
  729. byteOffset: writer.byteOffset,
  730. byteLength: buffer.byteLength
  731. };
  732. writer.byteOffset += buffer.byteLength;
  733. resolve( json.bufferViews.push( bufferViewDef ) - 1 );
  734. };
  735. } );
  736. }
  737. /**
  738. * Process attribute to generate an accessor
  739. * @param {BufferAttribute} attribute Attribute to process
  740. * @param {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range
  741. * @param {Integer} start (Optional)
  742. * @param {Integer} count (Optional)
  743. * @return {Integer|null} Index of the processed accessor on the "accessors" array
  744. */
  745. processAccessor( attribute, geometry, start, count ) {
  746. const json = this.json;
  747. const types = {
  748. 1: 'SCALAR',
  749. 2: 'VEC2',
  750. 3: 'VEC3',
  751. 4: 'VEC4',
  752. 9: 'MAT3',
  753. 16: 'MAT4'
  754. };
  755. let componentType;
  756. // Detect the component type of the attribute array
  757. if ( attribute.array.constructor === Float32Array ) {
  758. componentType = WEBGL_CONSTANTS.FLOAT;
  759. } else if ( attribute.array.constructor === Int32Array ) {
  760. componentType = WEBGL_CONSTANTS.INT;
  761. } else if ( attribute.array.constructor === Uint32Array ) {
  762. componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
  763. } else if ( attribute.array.constructor === Int16Array ) {
  764. componentType = WEBGL_CONSTANTS.SHORT;
  765. } else if ( attribute.array.constructor === Uint16Array ) {
  766. componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
  767. } else if ( attribute.array.constructor === Int8Array ) {
  768. componentType = WEBGL_CONSTANTS.BYTE;
  769. } else if ( attribute.array.constructor === Uint8Array ) {
  770. componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE;
  771. } else {
  772. throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type: ' + attribute.array.constructor.name );
  773. }
  774. if ( start === undefined ) start = 0;
  775. if ( count === undefined || count === Infinity ) count = attribute.count;
  776. // Skip creating an accessor if the attribute doesn't have data to export
  777. if ( count === 0 ) return null;
  778. const minMax = getMinMax( attribute, start, count );
  779. let bufferViewTarget;
  780. // If geometry isn't provided, don't infer the target usage of the bufferView. For
  781. // animation samplers, target must not be set.
  782. if ( geometry !== undefined ) {
  783. bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER;
  784. }
  785. const bufferView = this.processBufferView( attribute, componentType, start, count, bufferViewTarget );
  786. const accessorDef = {
  787. bufferView: bufferView.id,
  788. byteOffset: bufferView.byteOffset,
  789. componentType: componentType,
  790. count: count,
  791. max: minMax.max,
  792. min: minMax.min,
  793. type: types[ attribute.itemSize ]
  794. };
  795. if ( attribute.normalized === true ) accessorDef.normalized = true;
  796. if ( ! json.accessors ) json.accessors = [];
  797. return json.accessors.push( accessorDef ) - 1;
  798. }
  799. /**
  800. * Process image
  801. * @param {Image} image to process
  802. * @param {Integer} format of the image (RGBAFormat)
  803. * @param {Boolean} flipY before writing out the image
  804. * @param {String} mimeType export format
  805. * @return {Integer} Index of the processed texture in the "images" array
  806. */
  807. processImage( image, format, flipY, mimeType = 'image/png' ) {
  808. if ( image !== null ) {
  809. const writer = this;
  810. const cache = writer.cache;
  811. const json = writer.json;
  812. const options = writer.options;
  813. const pending = writer.pending;
  814. if ( ! cache.images.has( image ) ) cache.images.set( image, {} );
  815. const cachedImages = cache.images.get( image );
  816. const key = mimeType + ':flipY/' + flipY.toString();
  817. if ( cachedImages[ key ] !== undefined ) return cachedImages[ key ];
  818. if ( ! json.images ) json.images = [];
  819. const imageDef = { mimeType: mimeType };
  820. const canvas = getCanvas();
  821. canvas.width = Math.min( image.width, options.maxTextureSize );
  822. canvas.height = Math.min( image.height, options.maxTextureSize );
  823. const ctx = canvas.getContext( '2d' );
  824. if ( flipY === true ) {
  825. ctx.translate( 0, canvas.height );
  826. ctx.scale( 1, - 1 );
  827. }
  828. if ( image.data !== undefined ) { // THREE.DataTexture
  829. if ( format !== RGBAFormat ) {
  830. console.error( 'GLTFExporter: Only RGBAFormat is supported.', format );
  831. }
  832. if ( image.width > options.maxTextureSize || image.height > options.maxTextureSize ) {
  833. console.warn( 'GLTFExporter: Image size is bigger than maxTextureSize', image );
  834. }
  835. const data = new Uint8ClampedArray( image.height * image.width * 4 );
  836. for ( let i = 0; i < data.length; i += 4 ) {
  837. data[ i + 0 ] = image.data[ i + 0 ];
  838. data[ i + 1 ] = image.data[ i + 1 ];
  839. data[ i + 2 ] = image.data[ i + 2 ];
  840. data[ i + 3 ] = image.data[ i + 3 ];
  841. }
  842. ctx.putImageData( new ImageData( data, image.width, image.height ), 0, 0 );
  843. } else {
  844. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  845. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  846. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  847. ( typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas ) ) {
  848. ctx.drawImage( image, 0, 0, canvas.width, canvas.height );
  849. } else {
  850. throw new Error( 'THREE.GLTFExporter: Invalid image type. Use HTMLImageElement, HTMLCanvasElement, ImageBitmap or OffscreenCanvas.' );
  851. }
  852. }
  853. if ( options.binary === true ) {
  854. pending.push(
  855. getToBlobPromise( canvas, mimeType )
  856. .then( blob => writer.processBufferViewImage( blob ) )
  857. .then( bufferViewIndex => {
  858. imageDef.bufferView = bufferViewIndex;
  859. } )
  860. );
  861. } else {
  862. if ( canvas.toDataURL !== undefined ) {
  863. imageDef.uri = canvas.toDataURL( mimeType );
  864. } else {
  865. pending.push(
  866. getToBlobPromise( canvas, mimeType )
  867. .then( blob => new FileReader().readAsDataURL( blob ) )
  868. .then( dataURL => {
  869. imageDef.uri = dataURL;
  870. } )
  871. );
  872. }
  873. }
  874. const index = json.images.push( imageDef ) - 1;
  875. cachedImages[ key ] = index;
  876. return index;
  877. } else {
  878. throw new Error( 'THREE.GLTFExporter: No valid image data found. Unable to process texture.' );
  879. }
  880. }
  881. /**
  882. * Process sampler
  883. * @param {Texture} map Texture to process
  884. * @return {Integer} Index of the processed texture in the "samplers" array
  885. */
  886. processSampler( map ) {
  887. const json = this.json;
  888. if ( ! json.samplers ) json.samplers = [];
  889. const samplerDef = {
  890. magFilter: THREE_TO_WEBGL[ map.magFilter ],
  891. minFilter: THREE_TO_WEBGL[ map.minFilter ],
  892. wrapS: THREE_TO_WEBGL[ map.wrapS ],
  893. wrapT: THREE_TO_WEBGL[ map.wrapT ]
  894. };
  895. return json.samplers.push( samplerDef ) - 1;
  896. }
  897. /**
  898. * Process texture
  899. * @param {Texture} map Map to process
  900. * @return {Integer} Index of the processed texture in the "textures" array
  901. */
  902. processTexture( map ) {
  903. const writer = this;
  904. const options = writer.options;
  905. const cache = this.cache;
  906. const json = this.json;
  907. if ( cache.textures.has( map ) ) return cache.textures.get( map );
  908. if ( ! json.textures ) json.textures = [];
  909. // make non-readable textures (e.g. CompressedTexture) readable by blitting them into a new texture
  910. if ( map instanceof CompressedTexture ) {
  911. map = decompress( map, options.maxTextureSize );
  912. }
  913. let mimeType = map.userData.mimeType;
  914. if ( mimeType === 'image/webp' ) mimeType = 'image/png';
  915. const textureDef = {
  916. sampler: this.processSampler( map ),
  917. source: this.processImage( map.image, map.format, map.flipY, mimeType )
  918. };
  919. if ( map.name ) textureDef.name = map.name;
  920. this._invokeAll( function ( ext ) {
  921. ext.writeTexture && ext.writeTexture( map, textureDef );
  922. } );
  923. const index = json.textures.push( textureDef ) - 1;
  924. cache.textures.set( map, index );
  925. return index;
  926. }
  927. /**
  928. * Process material
  929. * @param {THREE.Material} material Material to process
  930. * @return {Integer|null} Index of the processed material in the "materials" array
  931. */
  932. processMaterial( material ) {
  933. const cache = this.cache;
  934. const json = this.json;
  935. if ( cache.materials.has( material ) ) return cache.materials.get( material );
  936. if ( material.isShaderMaterial ) {
  937. console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
  938. return null;
  939. }
  940. if ( ! json.materials ) json.materials = [];
  941. // @QUESTION Should we avoid including any attribute that has the default value?
  942. const materialDef = { pbrMetallicRoughness: {} };
  943. if ( material.isMeshStandardMaterial !== true && material.isMeshBasicMaterial !== true ) {
  944. console.warn( 'GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.' );
  945. }
  946. // pbrMetallicRoughness.baseColorFactor
  947. const color = material.color.toArray().concat( [ material.opacity ] );
  948. if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
  949. materialDef.pbrMetallicRoughness.baseColorFactor = color;
  950. }
  951. if ( material.isMeshStandardMaterial ) {
  952. materialDef.pbrMetallicRoughness.metallicFactor = material.metalness;
  953. materialDef.pbrMetallicRoughness.roughnessFactor = material.roughness;
  954. } else {
  955. materialDef.pbrMetallicRoughness.metallicFactor = 0.5;
  956. materialDef.pbrMetallicRoughness.roughnessFactor = 0.5;
  957. }
  958. // pbrMetallicRoughness.metallicRoughnessTexture
  959. if ( material.metalnessMap || material.roughnessMap ) {
  960. const metalRoughTexture = this.buildMetalRoughTexture( material.metalnessMap, material.roughnessMap );
  961. const metalRoughMapDef = {
  962. index: this.processTexture( metalRoughTexture ),
  963. channel: metalRoughTexture.channel
  964. };
  965. this.applyTextureTransform( metalRoughMapDef, metalRoughTexture );
  966. materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
  967. }
  968. // pbrMetallicRoughness.baseColorTexture
  969. if ( material.map ) {
  970. const baseColorMapDef = {
  971. index: this.processTexture( material.map ),
  972. texCoord: material.map.channel
  973. };
  974. this.applyTextureTransform( baseColorMapDef, material.map );
  975. materialDef.pbrMetallicRoughness.baseColorTexture = baseColorMapDef;
  976. }
  977. if ( material.emissive ) {
  978. const emissive = material.emissive;
  979. const maxEmissiveComponent = Math.max( emissive.r, emissive.g, emissive.b );
  980. if ( maxEmissiveComponent > 0 ) {
  981. materialDef.emissiveFactor = material.emissive.toArray();
  982. }
  983. // emissiveTexture
  984. if ( material.emissiveMap ) {
  985. const emissiveMapDef = {
  986. index: this.processTexture( material.emissiveMap ),
  987. texCoord: material.emissiveMap.channel
  988. };
  989. this.applyTextureTransform( emissiveMapDef, material.emissiveMap );
  990. materialDef.emissiveTexture = emissiveMapDef;
  991. }
  992. }
  993. // normalTexture
  994. if ( material.normalMap ) {
  995. const normalMapDef = {
  996. index: this.processTexture( material.normalMap ),
  997. texCoord: material.normalMap.channel
  998. };
  999. if ( material.normalScale && material.normalScale.x !== 1 ) {
  1000. // glTF normal scale is univariate. Ignore `y`, which may be flipped.
  1001. // Context: https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  1002. normalMapDef.scale = material.normalScale.x;
  1003. }
  1004. this.applyTextureTransform( normalMapDef, material.normalMap );
  1005. materialDef.normalTexture = normalMapDef;
  1006. }
  1007. // occlusionTexture
  1008. if ( material.aoMap ) {
  1009. const occlusionMapDef = {
  1010. index: this.processTexture( material.aoMap ),
  1011. texCoord: material.aoMap.channel
  1012. };
  1013. if ( material.aoMapIntensity !== 1.0 ) {
  1014. occlusionMapDef.strength = material.aoMapIntensity;
  1015. }
  1016. this.applyTextureTransform( occlusionMapDef, material.aoMap );
  1017. materialDef.occlusionTexture = occlusionMapDef;
  1018. }
  1019. // alphaMode
  1020. if ( material.transparent ) {
  1021. materialDef.alphaMode = 'BLEND';
  1022. } else {
  1023. if ( material.alphaTest > 0.0 ) {
  1024. materialDef.alphaMode = 'MASK';
  1025. materialDef.alphaCutoff = material.alphaTest;
  1026. }
  1027. }
  1028. // doubleSided
  1029. if ( material.side === DoubleSide ) materialDef.doubleSided = true;
  1030. if ( material.name !== '' ) materialDef.name = material.name;
  1031. this.serializeUserData( material, materialDef );
  1032. this._invokeAll( function ( ext ) {
  1033. ext.writeMaterial && ext.writeMaterial( material, materialDef );
  1034. } );
  1035. const index = json.materials.push( materialDef ) - 1;
  1036. cache.materials.set( material, index );
  1037. return index;
  1038. }
  1039. /**
  1040. * Process mesh
  1041. * @param {THREE.Mesh} mesh Mesh to process
  1042. * @return {Integer|null} Index of the processed mesh in the "meshes" array
  1043. */
  1044. processMesh( mesh ) {
  1045. const cache = this.cache;
  1046. const json = this.json;
  1047. const meshCacheKeyParts = [ mesh.geometry.uuid ];
  1048. if ( Array.isArray( mesh.material ) ) {
  1049. for ( let i = 0, l = mesh.material.length; i < l; i ++ ) {
  1050. meshCacheKeyParts.push( mesh.material[ i ].uuid );
  1051. }
  1052. } else {
  1053. meshCacheKeyParts.push( mesh.material.uuid );
  1054. }
  1055. const meshCacheKey = meshCacheKeyParts.join( ':' );
  1056. if ( cache.meshes.has( meshCacheKey ) ) return cache.meshes.get( meshCacheKey );
  1057. const geometry = mesh.geometry;
  1058. let mode;
  1059. // Use the correct mode
  1060. if ( mesh.isLineSegments ) {
  1061. mode = WEBGL_CONSTANTS.LINES;
  1062. } else if ( mesh.isLineLoop ) {
  1063. mode = WEBGL_CONSTANTS.LINE_LOOP;
  1064. } else if ( mesh.isLine ) {
  1065. mode = WEBGL_CONSTANTS.LINE_STRIP;
  1066. } else if ( mesh.isPoints ) {
  1067. mode = WEBGL_CONSTANTS.POINTS;
  1068. } else {
  1069. mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
  1070. }
  1071. const meshDef = {};
  1072. const attributes = {};
  1073. const primitives = [];
  1074. const targets = [];
  1075. // Conversion between attributes names in threejs and gltf spec
  1076. const nameConversion = {
  1077. uv: 'TEXCOORD_0',
  1078. uv1: 'TEXCOORD_1',
  1079. uv2: 'TEXCOORD_2',
  1080. uv3: 'TEXCOORD_3',
  1081. color: 'COLOR_0',
  1082. skinWeight: 'WEIGHTS_0',
  1083. skinIndex: 'JOINTS_0'
  1084. };
  1085. const originalNormal = geometry.getAttribute( 'normal' );
  1086. if ( originalNormal !== undefined && ! this.isNormalizedNormalAttribute( originalNormal ) ) {
  1087. console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' );
  1088. geometry.setAttribute( 'normal', this.createNormalizedNormalAttribute( originalNormal ) );
  1089. }
  1090. // @QUESTION Detect if .vertexColors = true?
  1091. // For every attribute create an accessor
  1092. let modifiedAttribute = null;
  1093. for ( let attributeName in geometry.attributes ) {
  1094. // Ignore morph target attributes, which are exported later.
  1095. if ( attributeName.slice( 0, 5 ) === 'morph' ) continue;
  1096. const attribute = geometry.attributes[ attributeName ];
  1097. attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
  1098. // Prefix all geometry attributes except the ones specifically
  1099. // listed in the spec; non-spec attributes are considered custom.
  1100. const validVertexAttributes =
  1101. /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;
  1102. if ( ! validVertexAttributes.test( attributeName ) ) attributeName = '_' + attributeName;
  1103. if ( cache.attributes.has( this.getUID( attribute ) ) ) {
  1104. attributes[ attributeName ] = cache.attributes.get( this.getUID( attribute ) );
  1105. continue;
  1106. }
  1107. // JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT.
  1108. modifiedAttribute = null;
  1109. const array = attribute.array;
  1110. if ( attributeName === 'JOINTS_0' &&
  1111. ! ( array instanceof Uint16Array ) &&
  1112. ! ( array instanceof Uint8Array ) ) {
  1113. console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' );
  1114. modifiedAttribute = new BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized );
  1115. }
  1116. const accessor = this.processAccessor( modifiedAttribute || attribute, geometry );
  1117. if ( accessor !== null ) {
  1118. if ( ! attributeName.startsWith( '_' ) ) {
  1119. this.detectMeshQuantization( attributeName, attribute );
  1120. }
  1121. attributes[ attributeName ] = accessor;
  1122. cache.attributes.set( this.getUID( attribute ), accessor );
  1123. }
  1124. }
  1125. if ( originalNormal !== undefined ) geometry.setAttribute( 'normal', originalNormal );
  1126. // Skip if no exportable attributes found
  1127. if ( Object.keys( attributes ).length === 0 ) return null;
  1128. // Morph targets
  1129. if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
  1130. const weights = [];
  1131. const targetNames = [];
  1132. const reverseDictionary = {};
  1133. if ( mesh.morphTargetDictionary !== undefined ) {
  1134. for ( const key in mesh.morphTargetDictionary ) {
  1135. reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;
  1136. }
  1137. }
  1138. for ( let i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
  1139. const target = {};
  1140. let warned = false;
  1141. for ( const attributeName in geometry.morphAttributes ) {
  1142. // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
  1143. // Three.js doesn't support TANGENT yet.
  1144. if ( attributeName !== 'position' && attributeName !== 'normal' ) {
  1145. if ( ! warned ) {
  1146. console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
  1147. warned = true;
  1148. }
  1149. continue;
  1150. }
  1151. const attribute = geometry.morphAttributes[ attributeName ][ i ];
  1152. const gltfAttributeName = attributeName.toUpperCase();
  1153. // Three.js morph attribute has absolute values while the one of glTF has relative values.
  1154. //
  1155. // glTF 2.0 Specification:
  1156. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets
  1157. const baseAttribute = geometry.attributes[ attributeName ];
  1158. if ( cache.attributes.has( this.getUID( attribute, true ) ) ) {
  1159. target[ gltfAttributeName ] = cache.attributes.get( this.getUID( attribute, true ) );
  1160. continue;
  1161. }
  1162. // Clones attribute not to override
  1163. const relativeAttribute = attribute.clone();
  1164. if ( ! geometry.morphTargetsRelative ) {
  1165. for ( let j = 0, jl = attribute.count; j < jl; j ++ ) {
  1166. for ( let a = 0; a < attribute.itemSize; a ++ ) {
  1167. if ( a === 0 ) relativeAttribute.setX( j, attribute.getX( j ) - baseAttribute.getX( j ) );
  1168. if ( a === 1 ) relativeAttribute.setY( j, attribute.getY( j ) - baseAttribute.getY( j ) );
  1169. if ( a === 2 ) relativeAttribute.setZ( j, attribute.getZ( j ) - baseAttribute.getZ( j ) );
  1170. if ( a === 3 ) relativeAttribute.setW( j, attribute.getW( j ) - baseAttribute.getW( j ) );
  1171. }
  1172. }
  1173. }
  1174. target[ gltfAttributeName ] = this.processAccessor( relativeAttribute, geometry );
  1175. cache.attributes.set( this.getUID( baseAttribute, true ), target[ gltfAttributeName ] );
  1176. }
  1177. targets.push( target );
  1178. weights.push( mesh.morphTargetInfluences[ i ] );
  1179. if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
  1180. }
  1181. meshDef.weights = weights;
  1182. if ( targetNames.length > 0 ) {
  1183. meshDef.extras = {};
  1184. meshDef.extras.targetNames = targetNames;
  1185. }
  1186. }
  1187. const isMultiMaterial = Array.isArray( mesh.material );
  1188. if ( isMultiMaterial && geometry.groups.length === 0 ) return null;
  1189. let didForceIndices = false;
  1190. if ( isMultiMaterial && geometry.index === null ) {
  1191. const indices = [];
  1192. for ( let i = 0, il = geometry.attributes.position.count; i < il; i ++ ) {
  1193. indices[ i ] = i;
  1194. }
  1195. geometry.setIndex( indices );
  1196. didForceIndices = true;
  1197. }
  1198. const materials = isMultiMaterial ? mesh.material : [ mesh.material ];
  1199. const groups = isMultiMaterial ? geometry.groups : [ { materialIndex: 0, start: undefined, count: undefined } ];
  1200. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  1201. const primitive = {
  1202. mode: mode,
  1203. attributes: attributes,
  1204. };
  1205. this.serializeUserData( geometry, primitive );
  1206. if ( targets.length > 0 ) primitive.targets = targets;
  1207. if ( geometry.index !== null ) {
  1208. let cacheKey = this.getUID( geometry.index );
  1209. if ( groups[ i ].start !== undefined || groups[ i ].count !== undefined ) {
  1210. cacheKey += ':' + groups[ i ].start + ':' + groups[ i ].count;
  1211. }
  1212. if ( cache.attributes.has( cacheKey ) ) {
  1213. primitive.indices = cache.attributes.get( cacheKey );
  1214. } else {
  1215. primitive.indices = this.processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
  1216. cache.attributes.set( cacheKey, primitive.indices );
  1217. }
  1218. if ( primitive.indices === null ) delete primitive.indices;
  1219. }
  1220. const material = this.processMaterial( materials[ groups[ i ].materialIndex ] );
  1221. if ( material !== null ) primitive.material = material;
  1222. primitives.push( primitive );
  1223. }
  1224. if ( didForceIndices === true ) {
  1225. geometry.setIndex( null );
  1226. }
  1227. meshDef.primitives = primitives;
  1228. if ( ! json.meshes ) json.meshes = [];
  1229. this._invokeAll( function ( ext ) {
  1230. ext.writeMesh && ext.writeMesh( mesh, meshDef );
  1231. } );
  1232. const index = json.meshes.push( meshDef ) - 1;
  1233. cache.meshes.set( meshCacheKey, index );
  1234. return index;
  1235. }
  1236. /**
  1237. * If a vertex attribute with a
  1238. * [non-standard data type](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview)
  1239. * is used, it is checked whether it is a valid data type according to the
  1240. * [KHR_mesh_quantization](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_mesh_quantization/README.md)
  1241. * extension.
  1242. * In this case the extension is automatically added to the list of used extensions.
  1243. *
  1244. * @param {string} attributeName
  1245. * @param {THREE.BufferAttribute} attribute
  1246. */
  1247. detectMeshQuantization( attributeName, attribute ) {
  1248. if ( this.extensionsUsed[ KHR_MESH_QUANTIZATION ] ) return;
  1249. let attrType = undefined;
  1250. switch ( attribute.array.constructor ) {
  1251. case Int8Array:
  1252. attrType = 'byte';
  1253. break;
  1254. case Uint8Array:
  1255. attrType = 'unsigned byte';
  1256. break;
  1257. case Int16Array:
  1258. attrType = 'short';
  1259. break;
  1260. case Uint16Array:
  1261. attrType = 'unsigned short';
  1262. break;
  1263. default:
  1264. return;
  1265. }
  1266. if ( attribute.normalized ) attrType += ' normalized';
  1267. const attrNamePrefix = attributeName.split( '_', 1 )[ 0 ];
  1268. if ( KHR_mesh_quantization_ExtraAttrTypes[ attrNamePrefix ] && KHR_mesh_quantization_ExtraAttrTypes[ attrNamePrefix ].includes( attrType ) ) {
  1269. this.extensionsUsed[ KHR_MESH_QUANTIZATION ] = true;
  1270. this.extensionsRequired[ KHR_MESH_QUANTIZATION ] = true;
  1271. }
  1272. }
  1273. /**
  1274. * Process camera
  1275. * @param {THREE.Camera} camera Camera to process
  1276. * @return {Integer} Index of the processed mesh in the "camera" array
  1277. */
  1278. processCamera( camera ) {
  1279. const json = this.json;
  1280. if ( ! json.cameras ) json.cameras = [];
  1281. const isOrtho = camera.isOrthographicCamera;
  1282. const cameraDef = {
  1283. type: isOrtho ? 'orthographic' : 'perspective'
  1284. };
  1285. if ( isOrtho ) {
  1286. cameraDef.orthographic = {
  1287. xmag: camera.right * 2,
  1288. ymag: camera.top * 2,
  1289. zfar: camera.far <= 0 ? 0.001 : camera.far,
  1290. znear: camera.near < 0 ? 0 : camera.near
  1291. };
  1292. } else {
  1293. cameraDef.perspective = {
  1294. aspectRatio: camera.aspect,
  1295. yfov: MathUtils.degToRad( camera.fov ),
  1296. zfar: camera.far <= 0 ? 0.001 : camera.far,
  1297. znear: camera.near < 0 ? 0 : camera.near
  1298. };
  1299. }
  1300. // Question: Is saving "type" as name intentional?
  1301. if ( camera.name !== '' ) cameraDef.name = camera.type;
  1302. return json.cameras.push( cameraDef ) - 1;
  1303. }
  1304. /**
  1305. * Creates glTF animation entry from AnimationClip object.
  1306. *
  1307. * Status:
  1308. * - Only properties listed in PATH_PROPERTIES may be animated.
  1309. *
  1310. * @param {THREE.AnimationClip} clip
  1311. * @param {THREE.Object3D} root
  1312. * @return {number|null}
  1313. */
  1314. processAnimation( clip, root ) {
  1315. const json = this.json;
  1316. const nodeMap = this.nodeMap;
  1317. if ( ! json.animations ) json.animations = [];
  1318. clip = GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root );
  1319. const tracks = clip.tracks;
  1320. const channels = [];
  1321. const samplers = [];
  1322. for ( let i = 0; i < tracks.length; ++ i ) {
  1323. const track = tracks[ i ];
  1324. const trackBinding = PropertyBinding.parseTrackName( track.name );
  1325. let trackNode = PropertyBinding.findNode( root, trackBinding.nodeName );
  1326. const trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
  1327. if ( trackBinding.objectName === 'bones' ) {
  1328. if ( trackNode.isSkinnedMesh === true ) {
  1329. trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
  1330. } else {
  1331. trackNode = undefined;
  1332. }
  1333. }
  1334. if ( ! trackNode || ! trackProperty ) {
  1335. console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
  1336. return null;
  1337. }
  1338. const inputItemSize = 1;
  1339. let outputItemSize = track.values.length / track.times.length;
  1340. if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
  1341. outputItemSize /= trackNode.morphTargetInfluences.length;
  1342. }
  1343. let interpolation;
  1344. // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
  1345. // Detecting glTF cubic spline interpolant by checking factory method's special property
  1346. // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
  1347. // valid value from .getInterpolation().
  1348. if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
  1349. interpolation = 'CUBICSPLINE';
  1350. // itemSize of CUBICSPLINE keyframe is 9
  1351. // (VEC3 * 3: inTangent, splineVertex, and outTangent)
  1352. // but needs to be stored as VEC3 so dividing by 3 here.
  1353. outputItemSize /= 3;
  1354. } else if ( track.getInterpolation() === InterpolateDiscrete ) {
  1355. interpolation = 'STEP';
  1356. } else {
  1357. interpolation = 'LINEAR';
  1358. }
  1359. samplers.push( {
  1360. input: this.processAccessor( new BufferAttribute( track.times, inputItemSize ) ),
  1361. output: this.processAccessor( new BufferAttribute( track.values, outputItemSize ) ),
  1362. interpolation: interpolation
  1363. } );
  1364. channels.push( {
  1365. sampler: samplers.length - 1,
  1366. target: {
  1367. node: nodeMap.get( trackNode ),
  1368. path: trackProperty
  1369. }
  1370. } );
  1371. }
  1372. json.animations.push( {
  1373. name: clip.name || 'clip_' + json.animations.length,
  1374. samplers: samplers,
  1375. channels: channels
  1376. } );
  1377. return json.animations.length - 1;
  1378. }
  1379. /**
  1380. * @param {THREE.Object3D} object
  1381. * @return {number|null}
  1382. */
  1383. processSkin( object ) {
  1384. const json = this.json;
  1385. const nodeMap = this.nodeMap;
  1386. const node = json.nodes[ nodeMap.get( object ) ];
  1387. const skeleton = object.skeleton;
  1388. if ( skeleton === undefined ) return null;
  1389. const rootJoint = object.skeleton.bones[ 0 ];
  1390. if ( rootJoint === undefined ) return null;
  1391. const joints = [];
  1392. const inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
  1393. const temporaryBoneInverse = new Matrix4();
  1394. for ( let i = 0; i < skeleton.bones.length; ++ i ) {
  1395. joints.push( nodeMap.get( skeleton.bones[ i ] ) );
  1396. temporaryBoneInverse.copy( skeleton.boneInverses[ i ] );
  1397. temporaryBoneInverse.multiply( object.bindMatrix ).toArray( inverseBindMatrices, i * 16 );
  1398. }
  1399. if ( json.skins === undefined ) json.skins = [];
  1400. json.skins.push( {
  1401. inverseBindMatrices: this.processAccessor( new BufferAttribute( inverseBindMatrices, 16 ) ),
  1402. joints: joints,
  1403. skeleton: nodeMap.get( rootJoint )
  1404. } );
  1405. const skinIndex = node.skin = json.skins.length - 1;
  1406. return skinIndex;
  1407. }
  1408. /**
  1409. * Process Object3D node
  1410. * @param {THREE.Object3D} node Object3D to processNode
  1411. * @return {Integer} Index of the node in the nodes list
  1412. */
  1413. processNode( object ) {
  1414. const json = this.json;
  1415. const options = this.options;
  1416. const nodeMap = this.nodeMap;
  1417. if ( ! json.nodes ) json.nodes = [];
  1418. const nodeDef = {};
  1419. if ( options.trs ) {
  1420. const rotation = object.quaternion.toArray();
  1421. const position = object.position.toArray();
  1422. const scale = object.scale.toArray();
  1423. if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
  1424. nodeDef.rotation = rotation;
  1425. }
  1426. if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
  1427. nodeDef.translation = position;
  1428. }
  1429. if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
  1430. nodeDef.scale = scale;
  1431. }
  1432. } else {
  1433. if ( object.matrixAutoUpdate ) {
  1434. object.updateMatrix();
  1435. }
  1436. if ( isIdentityMatrix( object.matrix ) === false ) {
  1437. nodeDef.matrix = object.matrix.elements;
  1438. }
  1439. }
  1440. // We don't export empty strings name because it represents no-name in Three.js.
  1441. if ( object.name !== '' ) nodeDef.name = String( object.name );
  1442. this.serializeUserData( object, nodeDef );
  1443. if ( object.isMesh || object.isLine || object.isPoints ) {
  1444. const meshIndex = this.processMesh( object );
  1445. if ( meshIndex !== null ) nodeDef.mesh = meshIndex;
  1446. } else if ( object.isCamera ) {
  1447. nodeDef.camera = this.processCamera( object );
  1448. }
  1449. if ( object.isSkinnedMesh ) this.skins.push( object );
  1450. if ( object.children.length > 0 ) {
  1451. const children = [];
  1452. for ( let i = 0, l = object.children.length; i < l; i ++ ) {
  1453. const child = object.children[ i ];
  1454. if ( child.visible || options.onlyVisible === false ) {
  1455. const nodeIndex = this.processNode( child );
  1456. if ( nodeIndex !== null ) children.push( nodeIndex );
  1457. }
  1458. }
  1459. if ( children.length > 0 ) nodeDef.children = children;
  1460. }
  1461. this._invokeAll( function ( ext ) {
  1462. ext.writeNode && ext.writeNode( object, nodeDef );
  1463. } );
  1464. const nodeIndex = json.nodes.push( nodeDef ) - 1;
  1465. nodeMap.set( object, nodeIndex );
  1466. return nodeIndex;
  1467. }
  1468. /**
  1469. * Process Scene
  1470. * @param {Scene} node Scene to process
  1471. */
  1472. processScene( scene ) {
  1473. const json = this.json;
  1474. const options = this.options;
  1475. if ( ! json.scenes ) {
  1476. json.scenes = [];
  1477. json.scene = 0;
  1478. }
  1479. const sceneDef = {};
  1480. if ( scene.name !== '' ) sceneDef.name = scene.name;
  1481. json.scenes.push( sceneDef );
  1482. const nodes = [];
  1483. for ( let i = 0, l = scene.children.length; i < l; i ++ ) {
  1484. const child = scene.children[ i ];
  1485. if ( child.visible || options.onlyVisible === false ) {
  1486. const nodeIndex = this.processNode( child );
  1487. if ( nodeIndex !== null ) nodes.push( nodeIndex );
  1488. }
  1489. }
  1490. if ( nodes.length > 0 ) sceneDef.nodes = nodes;
  1491. this.serializeUserData( scene, sceneDef );
  1492. }
  1493. /**
  1494. * Creates a Scene to hold a list of objects and parse it
  1495. * @param {Array} objects List of objects to process
  1496. */
  1497. processObjects( objects ) {
  1498. const scene = new Scene();
  1499. scene.name = 'AuxScene';
  1500. for ( let i = 0; i < objects.length; i ++ ) {
  1501. // We push directly to children instead of calling `add` to prevent
  1502. // modify the .parent and break its original scene and hierarchy
  1503. scene.children.push( objects[ i ] );
  1504. }
  1505. this.processScene( scene );
  1506. }
  1507. /**
  1508. * @param {THREE.Object3D|Array<THREE.Object3D>} input
  1509. */
  1510. processInput( input ) {
  1511. const options = this.options;
  1512. input = input instanceof Array ? input : [ input ];
  1513. this._invokeAll( function ( ext ) {
  1514. ext.beforeParse && ext.beforeParse( input );
  1515. } );
  1516. const objectsWithoutScene = [];
  1517. for ( let i = 0; i < input.length; i ++ ) {
  1518. if ( input[ i ] instanceof Scene ) {
  1519. this.processScene( input[ i ] );
  1520. } else {
  1521. objectsWithoutScene.push( input[ i ] );
  1522. }
  1523. }
  1524. if ( objectsWithoutScene.length > 0 ) this.processObjects( objectsWithoutScene );
  1525. for ( let i = 0; i < this.skins.length; ++ i ) {
  1526. this.processSkin( this.skins[ i ] );
  1527. }
  1528. for ( let i = 0; i < options.animations.length; ++ i ) {
  1529. this.processAnimation( options.animations[ i ], input[ 0 ] );
  1530. }
  1531. this._invokeAll( function ( ext ) {
  1532. ext.afterParse && ext.afterParse( input );
  1533. } );
  1534. }
  1535. _invokeAll( func ) {
  1536. for ( let i = 0, il = this.plugins.length; i < il; i ++ ) {
  1537. func( this.plugins[ i ] );
  1538. }
  1539. }
  1540. }
  1541. /**
  1542. * Punctual Lights Extension
  1543. *
  1544. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  1545. */
  1546. class GLTFLightExtension {
  1547. constructor( writer ) {
  1548. this.writer = writer;
  1549. this.name = 'KHR_lights_punctual';
  1550. }
  1551. writeNode( light, nodeDef ) {
  1552. if ( ! light.isLight ) return;
  1553. if ( ! light.isDirectionalLight && ! light.isPointLight && ! light.isSpotLight ) {
  1554. console.warn( 'THREE.GLTFExporter: Only directional, point, and spot lights are supported.', light );
  1555. return;
  1556. }
  1557. const writer = this.writer;
  1558. const json = writer.json;
  1559. const extensionsUsed = writer.extensionsUsed;
  1560. const lightDef = {};
  1561. if ( light.name ) lightDef.name = light.name;
  1562. lightDef.color = light.color.toArray();
  1563. lightDef.intensity = light.intensity;
  1564. if ( light.isDirectionalLight ) {
  1565. lightDef.type = 'directional';
  1566. } else if ( light.isPointLight ) {
  1567. lightDef.type = 'point';
  1568. if ( light.distance > 0 ) lightDef.range = light.distance;
  1569. } else if ( light.isSpotLight ) {
  1570. lightDef.type = 'spot';
  1571. if ( light.distance > 0 ) lightDef.range = light.distance;
  1572. lightDef.spot = {};
  1573. lightDef.spot.innerConeAngle = ( 1.0 - light.penumbra ) * light.angle;
  1574. lightDef.spot.outerConeAngle = light.angle;
  1575. }
  1576. if ( light.decay !== undefined && light.decay !== 2 ) {
  1577. console.warn( 'THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, '
  1578. + 'and expects light.decay=2.' );
  1579. }
  1580. if ( light.target
  1581. && ( light.target.parent !== light
  1582. || light.target.position.x !== 0
  1583. || light.target.position.y !== 0
  1584. || light.target.position.z !== - 1 ) ) {
  1585. console.warn( 'THREE.GLTFExporter: Light direction may be lost. For best results, '
  1586. + 'make light.target a child of the light with position 0,0,-1.' );
  1587. }
  1588. if ( ! extensionsUsed[ this.name ] ) {
  1589. json.extensions = json.extensions || {};
  1590. json.extensions[ this.name ] = { lights: [] };
  1591. extensionsUsed[ this.name ] = true;
  1592. }
  1593. const lights = json.extensions[ this.name ].lights;
  1594. lights.push( lightDef );
  1595. nodeDef.extensions = nodeDef.extensions || {};
  1596. nodeDef.extensions[ this.name ] = { light: lights.length - 1 };
  1597. }
  1598. }
  1599. /**
  1600. * Unlit Materials Extension
  1601. *
  1602. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  1603. */
  1604. class GLTFMaterialsUnlitExtension {
  1605. constructor( writer ) {
  1606. this.writer = writer;
  1607. this.name = 'KHR_materials_unlit';
  1608. }
  1609. writeMaterial( material, materialDef ) {
  1610. if ( ! material.isMeshBasicMaterial ) return;
  1611. const writer = this.writer;
  1612. const extensionsUsed = writer.extensionsUsed;
  1613. materialDef.extensions = materialDef.extensions || {};
  1614. materialDef.extensions[ this.name ] = {};
  1615. extensionsUsed[ this.name ] = true;
  1616. materialDef.pbrMetallicRoughness.metallicFactor = 0.0;
  1617. materialDef.pbrMetallicRoughness.roughnessFactor = 0.9;
  1618. }
  1619. }
  1620. /**
  1621. * Clearcoat Materials Extension
  1622. *
  1623. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  1624. */
  1625. class GLTFMaterialsClearcoatExtension {
  1626. constructor( writer ) {
  1627. this.writer = writer;
  1628. this.name = 'KHR_materials_clearcoat';
  1629. }
  1630. writeMaterial( material, materialDef ) {
  1631. if ( ! material.isMeshPhysicalMaterial || material.clearcoat === 0 ) return;
  1632. const writer = this.writer;
  1633. const extensionsUsed = writer.extensionsUsed;
  1634. const extensionDef = {};
  1635. extensionDef.clearcoatFactor = material.clearcoat;
  1636. if ( material.clearcoatMap ) {
  1637. const clearcoatMapDef = {
  1638. index: writer.processTexture( material.clearcoatMap ),
  1639. texCoord: material.clearcoatMap.channel
  1640. };
  1641. writer.applyTextureTransform( clearcoatMapDef, material.clearcoatMap );
  1642. extensionDef.clearcoatTexture = clearcoatMapDef;
  1643. }
  1644. extensionDef.clearcoatRoughnessFactor = material.clearcoatRoughness;
  1645. if ( material.clearcoatRoughnessMap ) {
  1646. const clearcoatRoughnessMapDef = {
  1647. index: writer.processTexture( material.clearcoatRoughnessMap ),
  1648. texCoord: material.clearcoatRoughnessMap.channel
  1649. };
  1650. writer.applyTextureTransform( clearcoatRoughnessMapDef, material.clearcoatRoughnessMap );
  1651. extensionDef.clearcoatRoughnessTexture = clearcoatRoughnessMapDef;
  1652. }
  1653. if ( material.clearcoatNormalMap ) {
  1654. const clearcoatNormalMapDef = {
  1655. index: writer.processTexture( material.clearcoatNormalMap ),
  1656. texCoord: material.clearcoatNormalMap.channel
  1657. };
  1658. if ( material.clearcoatNormalScale.x !== 1 ) clearcoatNormalMapDef.scale = material.clearcoatNormalScale.x;
  1659. writer.applyTextureTransform( clearcoatNormalMapDef, material.clearcoatNormalMap );
  1660. extensionDef.clearcoatNormalTexture = clearcoatNormalMapDef;
  1661. }
  1662. materialDef.extensions = materialDef.extensions || {};
  1663. materialDef.extensions[ this.name ] = extensionDef;
  1664. extensionsUsed[ this.name ] = true;
  1665. }
  1666. }
  1667. /**
  1668. * Materials dispersion Extension
  1669. *
  1670. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_dispersion
  1671. */
  1672. class GLTFMaterialsDispersionExtension {
  1673. constructor( writer ) {
  1674. this.writer = writer;
  1675. this.name = 'KHR_materials_dispersion';
  1676. }
  1677. writeMaterial( material, materialDef ) {
  1678. if ( ! material.isMeshPhysicalMaterial || material.dispersion === 0 ) return;
  1679. const writer = this.writer;
  1680. const extensionsUsed = writer.extensionsUsed;
  1681. const extensionDef = {};
  1682. extensionDef.dispersion = material.dispersion;
  1683. materialDef.extensions = materialDef.extensions || {};
  1684. materialDef.extensions[ this.name ] = extensionDef;
  1685. extensionsUsed[ this.name ] = true;
  1686. }
  1687. }
  1688. /**
  1689. * Iridescence Materials Extension
  1690. *
  1691. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence
  1692. */
  1693. class GLTFMaterialsIridescenceExtension {
  1694. constructor( writer ) {
  1695. this.writer = writer;
  1696. this.name = 'KHR_materials_iridescence';
  1697. }
  1698. writeMaterial( material, materialDef ) {
  1699. if ( ! material.isMeshPhysicalMaterial || material.iridescence === 0 ) return;
  1700. const writer = this.writer;
  1701. const extensionsUsed = writer.extensionsUsed;
  1702. const extensionDef = {};
  1703. extensionDef.iridescenceFactor = material.iridescence;
  1704. if ( material.iridescenceMap ) {
  1705. const iridescenceMapDef = {
  1706. index: writer.processTexture( material.iridescenceMap ),
  1707. texCoord: material.iridescenceMap.channel
  1708. };
  1709. writer.applyTextureTransform( iridescenceMapDef, material.iridescenceMap );
  1710. extensionDef.iridescenceTexture = iridescenceMapDef;
  1711. }
  1712. extensionDef.iridescenceIor = material.iridescenceIOR;
  1713. extensionDef.iridescenceThicknessMinimum = material.iridescenceThicknessRange[ 0 ];
  1714. extensionDef.iridescenceThicknessMaximum = material.iridescenceThicknessRange[ 1 ];
  1715. if ( material.iridescenceThicknessMap ) {
  1716. const iridescenceThicknessMapDef = {
  1717. index: writer.processTexture( material.iridescenceThicknessMap ),
  1718. texCoord: material.iridescenceThicknessMap.channel
  1719. };
  1720. writer.applyTextureTransform( iridescenceThicknessMapDef, material.iridescenceThicknessMap );
  1721. extensionDef.iridescenceThicknessTexture = iridescenceThicknessMapDef;
  1722. }
  1723. materialDef.extensions = materialDef.extensions || {};
  1724. materialDef.extensions[ this.name ] = extensionDef;
  1725. extensionsUsed[ this.name ] = true;
  1726. }
  1727. }
  1728. /**
  1729. * Transmission Materials Extension
  1730. *
  1731. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  1732. */
  1733. class GLTFMaterialsTransmissionExtension {
  1734. constructor( writer ) {
  1735. this.writer = writer;
  1736. this.name = 'KHR_materials_transmission';
  1737. }
  1738. writeMaterial( material, materialDef ) {
  1739. if ( ! material.isMeshPhysicalMaterial || material.transmission === 0 ) return;
  1740. const writer = this.writer;
  1741. const extensionsUsed = writer.extensionsUsed;
  1742. const extensionDef = {};
  1743. extensionDef.transmissionFactor = material.transmission;
  1744. if ( material.transmissionMap ) {
  1745. const transmissionMapDef = {
  1746. index: writer.processTexture( material.transmissionMap ),
  1747. texCoord: material.transmissionMap.channel
  1748. };
  1749. writer.applyTextureTransform( transmissionMapDef, material.transmissionMap );
  1750. extensionDef.transmissionTexture = transmissionMapDef;
  1751. }
  1752. materialDef.extensions = materialDef.extensions || {};
  1753. materialDef.extensions[ this.name ] = extensionDef;
  1754. extensionsUsed[ this.name ] = true;
  1755. }
  1756. }
  1757. /**
  1758. * Materials Volume Extension
  1759. *
  1760. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume
  1761. */
  1762. class GLTFMaterialsVolumeExtension {
  1763. constructor( writer ) {
  1764. this.writer = writer;
  1765. this.name = 'KHR_materials_volume';
  1766. }
  1767. writeMaterial( material, materialDef ) {
  1768. if ( ! material.isMeshPhysicalMaterial || material.transmission === 0 ) return;
  1769. const writer = this.writer;
  1770. const extensionsUsed = writer.extensionsUsed;
  1771. const extensionDef = {};
  1772. extensionDef.thicknessFactor = material.thickness;
  1773. if ( material.thicknessMap ) {
  1774. const thicknessMapDef = {
  1775. index: writer.processTexture( material.thicknessMap ),
  1776. texCoord: material.thicknessMap.channel
  1777. };
  1778. writer.applyTextureTransform( thicknessMapDef, material.thicknessMap );
  1779. extensionDef.thicknessTexture = thicknessMapDef;
  1780. }
  1781. extensionDef.attenuationDistance = material.attenuationDistance;
  1782. extensionDef.attenuationColor = material.attenuationColor.toArray();
  1783. materialDef.extensions = materialDef.extensions || {};
  1784. materialDef.extensions[ this.name ] = extensionDef;
  1785. extensionsUsed[ this.name ] = true;
  1786. }
  1787. }
  1788. /**
  1789. * Materials ior Extension
  1790. *
  1791. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior
  1792. */
  1793. class GLTFMaterialsIorExtension {
  1794. constructor( writer ) {
  1795. this.writer = writer;
  1796. this.name = 'KHR_materials_ior';
  1797. }
  1798. writeMaterial( material, materialDef ) {
  1799. if ( ! material.isMeshPhysicalMaterial || material.ior === 1.5 ) return;
  1800. const writer = this.writer;
  1801. const extensionsUsed = writer.extensionsUsed;
  1802. const extensionDef = {};
  1803. extensionDef.ior = material.ior;
  1804. materialDef.extensions = materialDef.extensions || {};
  1805. materialDef.extensions[ this.name ] = extensionDef;
  1806. extensionsUsed[ this.name ] = true;
  1807. }
  1808. }
  1809. /**
  1810. * Materials specular Extension
  1811. *
  1812. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular
  1813. */
  1814. class GLTFMaterialsSpecularExtension {
  1815. constructor( writer ) {
  1816. this.writer = writer;
  1817. this.name = 'KHR_materials_specular';
  1818. }
  1819. writeMaterial( material, materialDef ) {
  1820. if ( ! material.isMeshPhysicalMaterial || ( material.specularIntensity === 1.0 &&
  1821. material.specularColor.equals( DEFAULT_SPECULAR_COLOR ) &&
  1822. ! material.specularIntensityMap && ! material.specularColorMap ) ) return;
  1823. const writer = this.writer;
  1824. const extensionsUsed = writer.extensionsUsed;
  1825. const extensionDef = {};
  1826. if ( material.specularIntensityMap ) {
  1827. const specularIntensityMapDef = {
  1828. index: writer.processTexture( material.specularIntensityMap ),
  1829. texCoord: material.specularIntensityMap.channel
  1830. };
  1831. writer.applyTextureTransform( specularIntensityMapDef, material.specularIntensityMap );
  1832. extensionDef.specularTexture = specularIntensityMapDef;
  1833. }
  1834. if ( material.specularColorMap ) {
  1835. const specularColorMapDef = {
  1836. index: writer.processTexture( material.specularColorMap ),
  1837. texCoord: material.specularColorMap.channel
  1838. };
  1839. writer.applyTextureTransform( specularColorMapDef, material.specularColorMap );
  1840. extensionDef.specularColorTexture = specularColorMapDef;
  1841. }
  1842. extensionDef.specularFactor = material.specularIntensity;
  1843. extensionDef.specularColorFactor = material.specularColor.toArray();
  1844. materialDef.extensions = materialDef.extensions || {};
  1845. materialDef.extensions[ this.name ] = extensionDef;
  1846. extensionsUsed[ this.name ] = true;
  1847. }
  1848. }
  1849. /**
  1850. * Sheen Materials Extension
  1851. *
  1852. * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen
  1853. */
  1854. class GLTFMaterialsSheenExtension {
  1855. constructor( writer ) {
  1856. this.writer = writer;
  1857. this.name = 'KHR_materials_sheen';
  1858. }
  1859. writeMaterial( material, materialDef ) {
  1860. if ( ! material.isMeshPhysicalMaterial || material.sheen == 0.0 ) return;
  1861. const writer = this.writer;
  1862. const extensionsUsed = writer.extensionsUsed;
  1863. const extensionDef = {};
  1864. if ( material.sheenRoughnessMap ) {
  1865. const sheenRoughnessMapDef = {
  1866. index: writer.processTexture( material.sheenRoughnessMap ),
  1867. texCoord: material.sheenRoughnessMap.channel
  1868. };
  1869. writer.applyTextureTransform( sheenRoughnessMapDef, material.sheenRoughnessMap );
  1870. extensionDef.sheenRoughnessTexture = sheenRoughnessMapDef;
  1871. }
  1872. if ( material.sheenColorMap ) {
  1873. const sheenColorMapDef = {
  1874. index: writer.processTexture( material.sheenColorMap ),
  1875. texCoord: material.sheenColorMap.channel
  1876. };
  1877. writer.applyTextureTransform( sheenColorMapDef, material.sheenColorMap );
  1878. extensionDef.sheenColorTexture = sheenColorMapDef;
  1879. }
  1880. extensionDef.sheenRoughnessFactor = material.sheenRoughness;
  1881. extensionDef.sheenColorFactor = material.sheenColor.toArray();
  1882. materialDef.extensions = materialDef.extensions || {};
  1883. materialDef.extensions[ this.name ] = extensionDef;
  1884. extensionsUsed[ this.name ] = true;
  1885. }
  1886. }
  1887. /**
  1888. * Anisotropy Materials Extension
  1889. *
  1890. * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_anisotropy
  1891. */
  1892. class GLTFMaterialsAnisotropyExtension {
  1893. constructor( writer ) {
  1894. this.writer = writer;
  1895. this.name = 'KHR_materials_anisotropy';
  1896. }
  1897. writeMaterial( material, materialDef ) {
  1898. if ( ! material.isMeshPhysicalMaterial || material.anisotropy == 0.0 ) return;
  1899. const writer = this.writer;
  1900. const extensionsUsed = writer.extensionsUsed;
  1901. const extensionDef = {};
  1902. if ( material.anisotropyMap ) {
  1903. const anisotropyMapDef = { index: writer.processTexture( material.anisotropyMap ) };
  1904. writer.applyTextureTransform( anisotropyMapDef, material.anisotropyMap );
  1905. extensionDef.anisotropyTexture = anisotropyMapDef;
  1906. }
  1907. extensionDef.anisotropyStrength = material.anisotropy;
  1908. extensionDef.anisotropyRotation = material.anisotropyRotation;
  1909. materialDef.extensions = materialDef.extensions || {};
  1910. materialDef.extensions[ this.name ] = extensionDef;
  1911. extensionsUsed[ this.name ] = true;
  1912. }
  1913. }
  1914. /**
  1915. * Materials Emissive Strength Extension
  1916. *
  1917. * Specification: https://github.com/KhronosGroup/glTF/blob/5768b3ce0ef32bc39cdf1bef10b948586635ead3/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md
  1918. */
  1919. class GLTFMaterialsEmissiveStrengthExtension {
  1920. constructor( writer ) {
  1921. this.writer = writer;
  1922. this.name = 'KHR_materials_emissive_strength';
  1923. }
  1924. writeMaterial( material, materialDef ) {
  1925. if ( ! material.isMeshStandardMaterial || material.emissiveIntensity === 1.0 ) return;
  1926. const writer = this.writer;
  1927. const extensionsUsed = writer.extensionsUsed;
  1928. const extensionDef = {};
  1929. extensionDef.emissiveStrength = material.emissiveIntensity;
  1930. materialDef.extensions = materialDef.extensions || {};
  1931. materialDef.extensions[ this.name ] = extensionDef;
  1932. extensionsUsed[ this.name ] = true;
  1933. }
  1934. }
  1935. /**
  1936. * Materials bump Extension
  1937. *
  1938. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/EXT_materials_bump
  1939. */
  1940. class GLTFMaterialsBumpExtension {
  1941. constructor( writer ) {
  1942. this.writer = writer;
  1943. this.name = 'EXT_materials_bump';
  1944. }
  1945. writeMaterial( material, materialDef ) {
  1946. if ( ! material.isMeshStandardMaterial || (
  1947. material.bumpScale === 1 &&
  1948. ! material.bumpMap ) ) return;
  1949. const writer = this.writer;
  1950. const extensionsUsed = writer.extensionsUsed;
  1951. const extensionDef = {};
  1952. if ( material.bumpMap ) {
  1953. const bumpMapDef = {
  1954. index: writer.processTexture( material.bumpMap ),
  1955. texCoord: material.bumpMap.channel
  1956. };
  1957. writer.applyTextureTransform( bumpMapDef, material.bumpMap );
  1958. extensionDef.bumpTexture = bumpMapDef;
  1959. }
  1960. extensionDef.bumpFactor = material.bumpScale;
  1961. materialDef.extensions = materialDef.extensions || {};
  1962. materialDef.extensions[ this.name ] = extensionDef;
  1963. extensionsUsed[ this.name ] = true;
  1964. }
  1965. }
  1966. /**
  1967. * GPU Instancing Extension
  1968. *
  1969. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_mesh_gpu_instancing
  1970. */
  1971. class GLTFMeshGpuInstancing {
  1972. constructor( writer ) {
  1973. this.writer = writer;
  1974. this.name = 'EXT_mesh_gpu_instancing';
  1975. }
  1976. writeNode( object, nodeDef ) {
  1977. if ( ! object.isInstancedMesh ) return;
  1978. const writer = this.writer;
  1979. const mesh = object;
  1980. const translationAttr = new Float32Array( mesh.count * 3 );
  1981. const rotationAttr = new Float32Array( mesh.count * 4 );
  1982. const scaleAttr = new Float32Array( mesh.count * 3 );
  1983. const matrix = new Matrix4();
  1984. const position = new Vector3();
  1985. const quaternion = new Quaternion();
  1986. const scale = new Vector3();
  1987. for ( let i = 0; i < mesh.count; i ++ ) {
  1988. mesh.getMatrixAt( i, matrix );
  1989. matrix.decompose( position, quaternion, scale );
  1990. position.toArray( translationAttr, i * 3 );
  1991. quaternion.toArray( rotationAttr, i * 4 );
  1992. scale.toArray( scaleAttr, i * 3 );
  1993. }
  1994. const attributes = {
  1995. TRANSLATION: writer.processAccessor( new BufferAttribute( translationAttr, 3 ) ),
  1996. ROTATION: writer.processAccessor( new BufferAttribute( rotationAttr, 4 ) ),
  1997. SCALE: writer.processAccessor( new BufferAttribute( scaleAttr, 3 ) ),
  1998. };
  1999. if ( mesh.instanceColor )
  2000. attributes._COLOR_0 = writer.processAccessor( mesh.instanceColor );
  2001. nodeDef.extensions = nodeDef.extensions || {};
  2002. nodeDef.extensions[ this.name ] = { attributes };
  2003. writer.extensionsUsed[ this.name ] = true;
  2004. writer.extensionsRequired[ this.name ] = true;
  2005. }
  2006. }
  2007. /**
  2008. * Static utility functions
  2009. */
  2010. GLTFExporter.Utils = {
  2011. insertKeyframe: function ( track, time ) {
  2012. const tolerance = 0.001; // 1ms
  2013. const valueSize = track.getValueSize();
  2014. const times = new track.TimeBufferType( track.times.length + 1 );
  2015. const values = new track.ValueBufferType( track.values.length + valueSize );
  2016. const interpolant = track.createInterpolant( new track.ValueBufferType( valueSize ) );
  2017. let index;
  2018. if ( track.times.length === 0 ) {
  2019. times[ 0 ] = time;
  2020. for ( let i = 0; i < valueSize; i ++ ) {
  2021. values[ i ] = 0;
  2022. }
  2023. index = 0;
  2024. } else if ( time < track.times[ 0 ] ) {
  2025. if ( Math.abs( track.times[ 0 ] - time ) < tolerance ) return 0;
  2026. times[ 0 ] = time;
  2027. times.set( track.times, 1 );
  2028. values.set( interpolant.evaluate( time ), 0 );
  2029. values.set( track.values, valueSize );
  2030. index = 0;
  2031. } else if ( time > track.times[ track.times.length - 1 ] ) {
  2032. if ( Math.abs( track.times[ track.times.length - 1 ] - time ) < tolerance ) {
  2033. return track.times.length - 1;
  2034. }
  2035. times[ times.length - 1 ] = time;
  2036. times.set( track.times, 0 );
  2037. values.set( track.values, 0 );
  2038. values.set( interpolant.evaluate( time ), track.values.length );
  2039. index = times.length - 1;
  2040. } else {
  2041. for ( let i = 0; i < track.times.length; i ++ ) {
  2042. if ( Math.abs( track.times[ i ] - time ) < tolerance ) return i;
  2043. if ( track.times[ i ] < time && track.times[ i + 1 ] > time ) {
  2044. times.set( track.times.slice( 0, i + 1 ), 0 );
  2045. times[ i + 1 ] = time;
  2046. times.set( track.times.slice( i + 1 ), i + 2 );
  2047. values.set( track.values.slice( 0, ( i + 1 ) * valueSize ), 0 );
  2048. values.set( interpolant.evaluate( time ), ( i + 1 ) * valueSize );
  2049. values.set( track.values.slice( ( i + 1 ) * valueSize ), ( i + 2 ) * valueSize );
  2050. index = i + 1;
  2051. break;
  2052. }
  2053. }
  2054. }
  2055. track.times = times;
  2056. track.values = values;
  2057. return index;
  2058. },
  2059. mergeMorphTargetTracks: function ( clip, root ) {
  2060. const tracks = [];
  2061. const mergedTracks = {};
  2062. const sourceTracks = clip.tracks;
  2063. for ( let i = 0; i < sourceTracks.length; ++ i ) {
  2064. let sourceTrack = sourceTracks[ i ];
  2065. const sourceTrackBinding = PropertyBinding.parseTrackName( sourceTrack.name );
  2066. const sourceTrackNode = PropertyBinding.findNode( root, sourceTrackBinding.nodeName );
  2067. if ( sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined ) {
  2068. // Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is.
  2069. tracks.push( sourceTrack );
  2070. continue;
  2071. }
  2072. if ( sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete
  2073. && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear ) {
  2074. if ( sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  2075. // This should never happen, because glTF morph target animations
  2076. // affect all targets already.
  2077. throw new Error( 'THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.' );
  2078. }
  2079. console.warn( 'THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.' );
  2080. sourceTrack = sourceTrack.clone();
  2081. sourceTrack.setInterpolation( InterpolateLinear );
  2082. }
  2083. const targetCount = sourceTrackNode.morphTargetInfluences.length;
  2084. const targetIndex = sourceTrackNode.morphTargetDictionary[ sourceTrackBinding.propertyIndex ];
  2085. if ( targetIndex === undefined ) {
  2086. throw new Error( 'THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex );
  2087. }
  2088. let mergedTrack;
  2089. // If this is the first time we've seen this object, create a new
  2090. // track to store merged keyframe data for each morph target.
  2091. if ( mergedTracks[ sourceTrackNode.uuid ] === undefined ) {
  2092. mergedTrack = sourceTrack.clone();
  2093. const values = new mergedTrack.ValueBufferType( targetCount * mergedTrack.times.length );
  2094. for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
  2095. values[ j * targetCount + targetIndex ] = mergedTrack.values[ j ];
  2096. }
  2097. // We need to take into consideration the intended target node
  2098. // of our original un-merged morphTarget animation.
  2099. mergedTrack.name = ( sourceTrackBinding.nodeName || '' ) + '.morphTargetInfluences';
  2100. mergedTrack.values = values;
  2101. mergedTracks[ sourceTrackNode.uuid ] = mergedTrack;
  2102. tracks.push( mergedTrack );
  2103. continue;
  2104. }
  2105. const sourceInterpolant = sourceTrack.createInterpolant( new sourceTrack.ValueBufferType( 1 ) );
  2106. mergedTrack = mergedTracks[ sourceTrackNode.uuid ];
  2107. // For every existing keyframe of the merged track, write a (possibly
  2108. // interpolated) value from the source track.
  2109. for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
  2110. mergedTrack.values[ j * targetCount + targetIndex ] = sourceInterpolant.evaluate( mergedTrack.times[ j ] );
  2111. }
  2112. // For every existing keyframe of the source track, write a (possibly
  2113. // new) keyframe to the merged track. Values from the previous loop may
  2114. // be written again, but keyframes are de-duplicated.
  2115. for ( let j = 0; j < sourceTrack.times.length; j ++ ) {
  2116. const keyframeIndex = this.insertKeyframe( mergedTrack, sourceTrack.times[ j ] );
  2117. mergedTrack.values[ keyframeIndex * targetCount + targetIndex ] = sourceTrack.values[ j ];
  2118. }
  2119. }
  2120. clip.tracks = tracks;
  2121. return clip;
  2122. }
  2123. };
  2124. export { GLTFExporter };