GLTFExporter.js 84 KB

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