GLTFLoader.js 112 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881
  1. import {
  2. AnimationClip,
  3. Bone,
  4. Box3,
  5. BufferAttribute,
  6. BufferGeometry,
  7. ClampToEdgeWrapping,
  8. Color,
  9. ColorManagement,
  10. DirectionalLight,
  11. DoubleSide,
  12. FileLoader,
  13. FrontSide,
  14. Group,
  15. ImageBitmapLoader,
  16. InstancedMesh,
  17. InterleavedBuffer,
  18. InterleavedBufferAttribute,
  19. Interpolant,
  20. InterpolateDiscrete,
  21. InterpolateLinear,
  22. Line,
  23. LineBasicMaterial,
  24. LineLoop,
  25. LineSegments,
  26. LinearFilter,
  27. LinearMipmapLinearFilter,
  28. LinearMipmapNearestFilter,
  29. LinearSRGBColorSpace,
  30. Loader,
  31. LoaderUtils,
  32. Material,
  33. MathUtils,
  34. Matrix4,
  35. Mesh,
  36. MeshBasicMaterial,
  37. MeshPhysicalMaterial,
  38. MeshStandardMaterial,
  39. MirroredRepeatWrapping,
  40. NearestFilter,
  41. NearestMipmapLinearFilter,
  42. NearestMipmapNearestFilter,
  43. NumberKeyframeTrack,
  44. Object3D,
  45. OrthographicCamera,
  46. PerspectiveCamera,
  47. PointLight,
  48. Points,
  49. PointsMaterial,
  50. PropertyBinding,
  51. Quaternion,
  52. QuaternionKeyframeTrack,
  53. RepeatWrapping,
  54. Skeleton,
  55. SkinnedMesh,
  56. Sphere,
  57. SpotLight,
  58. Texture,
  59. TextureLoader,
  60. TriangleFanDrawMode,
  61. TriangleStripDrawMode,
  62. Vector2,
  63. Vector3,
  64. VectorKeyframeTrack,
  65. SRGBColorSpace,
  66. InstancedBufferAttribute
  67. } from 'three';
  68. import { toTrianglesDrawMode } from '../utils/BufferGeometryUtils.js';
  69. /**
  70. * A loader for the glTF 2.0 format.
  71. *
  72. * [glTF]{@link https://www.khronos.org/gltf/} (GL Transmission Format) is an [open format specification]{@link https://github.com/KhronosGroup/glTF/tree/main/specification/2.0}
  73. * for efficient delivery and loading of 3D content. Assets may be provided either in JSON (.gltf) or binary (.glb)
  74. * format. External files store textures (.jpg, .png) and additional binary data (.bin). A glTF asset may deliver
  75. * one or more scenes, including meshes, materials, textures, skins, skeletons, morph targets, animations, lights,
  76. * and/or cameras.
  77. *
  78. * `GLTFLoader` uses {@link ImageBitmapLoader} whenever possible. Be advised that image bitmaps are not
  79. * automatically GC-collected when they are no longer referenced, and they require special handling during
  80. * the disposal process.
  81. *
  82. * `GLTFLoader` supports the following glTF 2.0 extensions:
  83. * - KHR_draco_mesh_compression
  84. * - KHR_materials_clearcoat
  85. * - KHR_materials_dispersion
  86. * - KHR_materials_ior
  87. * - KHR_materials_specular
  88. * - KHR_materials_transmission
  89. * - KHR_materials_iridescence
  90. * - KHR_materials_unlit
  91. * - KHR_materials_volume
  92. * - KHR_mesh_quantization
  93. * - KHR_lights_punctual
  94. * - KHR_texture_basisu
  95. * - KHR_texture_transform
  96. * - EXT_texture_webp
  97. * - EXT_meshopt_compression
  98. * - EXT_mesh_gpu_instancing
  99. *
  100. * The following glTF 2.0 extension is supported by an external user plugin:
  101. * - [KHR_materials_variants]{@link https://github.com/takahirox/three-gltf-extensions}
  102. * - [MSFT_texture_dds]{@link https://github.com/takahirox/three-gltf-extensions}
  103. *
  104. * ```js
  105. * const loader = new GLTFLoader();
  106. *
  107. * // Optional: Provide a DRACOLoader instance to decode compressed mesh data
  108. * const dracoLoader = new DRACOLoader();
  109. * dracoLoader.setDecoderPath( '/examples/jsm/libs/draco/' );
  110. * loader.setDRACOLoader( dracoLoader );
  111. *
  112. * const gltf = await loader.loadAsync( 'models/gltf/duck/duck.gltf' );
  113. * scene.add( gltf.scene );
  114. * ```
  115. *
  116. * @augments Loader
  117. * @three_import import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  118. */
  119. class GLTFLoader extends Loader {
  120. /**
  121. * Constructs a new glTF loader.
  122. *
  123. * @param {LoadingManager} [manager] - The loading manager.
  124. */
  125. constructor( manager ) {
  126. super( manager );
  127. this.dracoLoader = null;
  128. this.ktx2Loader = null;
  129. this.meshoptDecoder = null;
  130. this.pluginCallbacks = [];
  131. this.register( function ( parser ) {
  132. return new GLTFMaterialsClearcoatExtension( parser );
  133. } );
  134. this.register( function ( parser ) {
  135. return new GLTFMaterialsDispersionExtension( parser );
  136. } );
  137. this.register( function ( parser ) {
  138. return new GLTFTextureBasisUExtension( parser );
  139. } );
  140. this.register( function ( parser ) {
  141. return new GLTFTextureWebPExtension( parser );
  142. } );
  143. this.register( function ( parser ) {
  144. return new GLTFTextureAVIFExtension( parser );
  145. } );
  146. this.register( function ( parser ) {
  147. return new GLTFMaterialsSheenExtension( parser );
  148. } );
  149. this.register( function ( parser ) {
  150. return new GLTFMaterialsTransmissionExtension( parser );
  151. } );
  152. this.register( function ( parser ) {
  153. return new GLTFMaterialsVolumeExtension( parser );
  154. } );
  155. this.register( function ( parser ) {
  156. return new GLTFMaterialsIorExtension( parser );
  157. } );
  158. this.register( function ( parser ) {
  159. return new GLTFMaterialsEmissiveStrengthExtension( parser );
  160. } );
  161. this.register( function ( parser ) {
  162. return new GLTFMaterialsSpecularExtension( parser );
  163. } );
  164. this.register( function ( parser ) {
  165. return new GLTFMaterialsIridescenceExtension( parser );
  166. } );
  167. this.register( function ( parser ) {
  168. return new GLTFMaterialsAnisotropyExtension( parser );
  169. } );
  170. this.register( function ( parser ) {
  171. return new GLTFMaterialsBumpExtension( parser );
  172. } );
  173. this.register( function ( parser ) {
  174. return new GLTFLightsExtension( parser );
  175. } );
  176. this.register( function ( parser ) {
  177. return new GLTFMeshoptCompression( parser );
  178. } );
  179. this.register( function ( parser ) {
  180. return new GLTFMeshGpuInstancing( parser );
  181. } );
  182. }
  183. /**
  184. * Starts loading from the given URL and passes the loaded glTF asset
  185. * to the `onLoad()` callback.
  186. *
  187. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  188. * @param {function(GLTFLoader~LoadObject)} onLoad - Executed when the loading process has been finished.
  189. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  190. * @param {onErrorCallback} onError - Executed when errors occur.
  191. */
  192. load( url, onLoad, onProgress, onError ) {
  193. const scope = this;
  194. let resourcePath;
  195. if ( this.resourcePath !== '' ) {
  196. resourcePath = this.resourcePath;
  197. } else if ( this.path !== '' ) {
  198. // If a base path is set, resources will be relative paths from that plus the relative path of the gltf file
  199. // Example path = 'https://my-cnd-server.com/', url = 'assets/models/model.gltf'
  200. // resourcePath = 'https://my-cnd-server.com/assets/models/'
  201. // referenced resource 'model.bin' will be loaded from 'https://my-cnd-server.com/assets/models/model.bin'
  202. // referenced resource '../textures/texture.png' will be loaded from 'https://my-cnd-server.com/assets/textures/texture.png'
  203. const relativeUrl = LoaderUtils.extractUrlBase( url );
  204. resourcePath = LoaderUtils.resolveURL( relativeUrl, this.path );
  205. } else {
  206. resourcePath = LoaderUtils.extractUrlBase( url );
  207. }
  208. // Tells the LoadingManager to track an extra item, which resolves after
  209. // the model is fully loaded. This means the count of items loaded will
  210. // be incorrect, but ensures manager.onLoad() does not fire early.
  211. this.manager.itemStart( url );
  212. const _onError = function ( e ) {
  213. if ( onError ) {
  214. onError( e );
  215. } else {
  216. console.error( e );
  217. }
  218. scope.manager.itemError( url );
  219. scope.manager.itemEnd( url );
  220. };
  221. const loader = new FileLoader( this.manager );
  222. loader.setPath( this.path );
  223. loader.setResponseType( 'arraybuffer' );
  224. loader.setRequestHeader( this.requestHeader );
  225. loader.setWithCredentials( this.withCredentials );
  226. loader.load( url, function ( data ) {
  227. try {
  228. scope.parse( data, resourcePath, function ( gltf ) {
  229. onLoad( gltf );
  230. scope.manager.itemEnd( url );
  231. }, _onError );
  232. } catch ( e ) {
  233. _onError( e );
  234. }
  235. }, onProgress, _onError );
  236. }
  237. /**
  238. * Sets the given Draco loader to this loader. Required for decoding assets
  239. * compressed with the `KHR_draco_mesh_compression` extension.
  240. *
  241. * @param {DRACOLoader} dracoLoader - The Draco loader to set.
  242. * @return {GLTFLoader} A reference to this loader.
  243. */
  244. setDRACOLoader( dracoLoader ) {
  245. this.dracoLoader = dracoLoader;
  246. return this;
  247. }
  248. /**
  249. * Sets the given KTX2 loader to this loader. Required for loading KTX2
  250. * compressed textures.
  251. *
  252. * @param {KTX2Loader} ktx2Loader - The KTX2 loader to set.
  253. * @return {GLTFLoader} A reference to this loader.
  254. */
  255. setKTX2Loader( ktx2Loader ) {
  256. this.ktx2Loader = ktx2Loader;
  257. return this;
  258. }
  259. /**
  260. * Sets the given meshopt decoder. Required for decoding assets
  261. * compressed with the `EXT_meshopt_compression` extension.
  262. *
  263. * @param {Object} meshoptDecoder - The meshopt decoder to set.
  264. * @return {GLTFLoader} A reference to this loader.
  265. */
  266. setMeshoptDecoder( meshoptDecoder ) {
  267. this.meshoptDecoder = meshoptDecoder;
  268. return this;
  269. }
  270. /**
  271. * Registers a plugin callback. This API is internally used to implement the various
  272. * glTF extensions but can also used by third-party code to add additional logic
  273. * to the loader.
  274. *
  275. * @param {function(parser:GLTFParser)} callback - The callback function to register.
  276. * @return {GLTFLoader} A reference to this loader.
  277. */
  278. register( callback ) {
  279. if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
  280. this.pluginCallbacks.push( callback );
  281. }
  282. return this;
  283. }
  284. /**
  285. * Unregisters a plugin callback.
  286. *
  287. * @param {Function} callback - The callback function to unregister.
  288. * @return {GLTFLoader} A reference to this loader.
  289. */
  290. unregister( callback ) {
  291. if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
  292. this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
  293. }
  294. return this;
  295. }
  296. /**
  297. * Parses the given FBX data and returns the resulting group.
  298. *
  299. * @param {string|ArrayBuffer} data - The raw glTF data.
  300. * @param {string} path - The URL base path.
  301. * @param {function(GLTFLoader~LoadObject)} onLoad - Executed when the loading process has been finished.
  302. * @param {onErrorCallback} onError - Executed when errors occur.
  303. */
  304. parse( data, path, onLoad, onError ) {
  305. let json;
  306. const extensions = {};
  307. const plugins = {};
  308. const textDecoder = new TextDecoder();
  309. if ( typeof data === 'string' ) {
  310. json = JSON.parse( data );
  311. } else if ( data instanceof ArrayBuffer ) {
  312. const magic = textDecoder.decode( new Uint8Array( data, 0, 4 ) );
  313. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  314. try {
  315. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  316. } catch ( error ) {
  317. if ( onError ) onError( error );
  318. return;
  319. }
  320. json = JSON.parse( extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content );
  321. } else {
  322. json = JSON.parse( textDecoder.decode( data ) );
  323. }
  324. } else {
  325. json = data;
  326. }
  327. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  328. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
  329. return;
  330. }
  331. const parser = new GLTFParser( json, {
  332. path: path || this.resourcePath || '',
  333. crossOrigin: this.crossOrigin,
  334. requestHeader: this.requestHeader,
  335. manager: this.manager,
  336. ktx2Loader: this.ktx2Loader,
  337. meshoptDecoder: this.meshoptDecoder
  338. } );
  339. parser.fileLoader.setRequestHeader( this.requestHeader );
  340. for ( let i = 0; i < this.pluginCallbacks.length; i ++ ) {
  341. const plugin = this.pluginCallbacks[ i ]( parser );
  342. if ( ! plugin.name ) console.error( 'THREE.GLTFLoader: Invalid plugin found: missing name' );
  343. plugins[ plugin.name ] = plugin;
  344. // Workaround to avoid determining as unknown extension
  345. // in addUnknownExtensionsToUserData().
  346. // Remove this workaround if we move all the existing
  347. // extension handlers to plugin system
  348. extensions[ plugin.name ] = true;
  349. }
  350. if ( json.extensionsUsed ) {
  351. for ( let i = 0; i < json.extensionsUsed.length; ++ i ) {
  352. const extensionName = json.extensionsUsed[ i ];
  353. const extensionsRequired = json.extensionsRequired || [];
  354. switch ( extensionName ) {
  355. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  356. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  357. break;
  358. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  359. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  360. break;
  361. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  362. extensions[ extensionName ] = new GLTFTextureTransformExtension();
  363. break;
  364. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  365. extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
  366. break;
  367. default:
  368. if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {
  369. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  370. }
  371. }
  372. }
  373. }
  374. parser.setExtensions( extensions );
  375. parser.setPlugins( plugins );
  376. parser.parse( onLoad, onError );
  377. }
  378. /**
  379. * Async version of {@link GLTFLoader#parse}.
  380. *
  381. * @async
  382. * @param {string|ArrayBuffer} data - The raw glTF data.
  383. * @param {string} path - The URL base path.
  384. * @return {Promise<GLTFLoader~LoadObject>} A Promise that resolves with the loaded glTF when the parsing has been finished.
  385. */
  386. parseAsync( data, path ) {
  387. const scope = this;
  388. return new Promise( function ( resolve, reject ) {
  389. scope.parse( data, path, resolve, reject );
  390. } );
  391. }
  392. }
  393. /* GLTFREGISTRY */
  394. function GLTFRegistry() {
  395. let objects = {};
  396. return {
  397. get: function ( key ) {
  398. return objects[ key ];
  399. },
  400. add: function ( key, object ) {
  401. objects[ key ] = object;
  402. },
  403. remove: function ( key ) {
  404. delete objects[ key ];
  405. },
  406. removeAll: function () {
  407. objects = {};
  408. }
  409. };
  410. }
  411. /*********************************/
  412. /********** EXTENSIONS ***********/
  413. /*********************************/
  414. const EXTENSIONS = {
  415. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  416. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  417. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  418. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  419. KHR_MATERIALS_DISPERSION: 'KHR_materials_dispersion',
  420. KHR_MATERIALS_IOR: 'KHR_materials_ior',
  421. KHR_MATERIALS_SHEEN: 'KHR_materials_sheen',
  422. KHR_MATERIALS_SPECULAR: 'KHR_materials_specular',
  423. KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
  424. KHR_MATERIALS_IRIDESCENCE: 'KHR_materials_iridescence',
  425. KHR_MATERIALS_ANISOTROPY: 'KHR_materials_anisotropy',
  426. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  427. KHR_MATERIALS_VOLUME: 'KHR_materials_volume',
  428. KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
  429. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  430. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  431. KHR_MATERIALS_EMISSIVE_STRENGTH: 'KHR_materials_emissive_strength',
  432. EXT_MATERIALS_BUMP: 'EXT_materials_bump',
  433. EXT_TEXTURE_WEBP: 'EXT_texture_webp',
  434. EXT_TEXTURE_AVIF: 'EXT_texture_avif',
  435. EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',
  436. EXT_MESH_GPU_INSTANCING: 'EXT_mesh_gpu_instancing'
  437. };
  438. /**
  439. * Punctual Lights Extension
  440. *
  441. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  442. *
  443. * @private
  444. */
  445. class GLTFLightsExtension {
  446. constructor( parser ) {
  447. this.parser = parser;
  448. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  449. // Object3D instance caches
  450. this.cache = { refs: {}, uses: {} };
  451. }
  452. _markDefs() {
  453. const parser = this.parser;
  454. const nodeDefs = this.parser.json.nodes || [];
  455. for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  456. const nodeDef = nodeDefs[ nodeIndex ];
  457. if ( nodeDef.extensions
  458. && nodeDef.extensions[ this.name ]
  459. && nodeDef.extensions[ this.name ].light !== undefined ) {
  460. parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light );
  461. }
  462. }
  463. }
  464. _loadLight( lightIndex ) {
  465. const parser = this.parser;
  466. const cacheKey = 'light:' + lightIndex;
  467. let dependency = parser.cache.get( cacheKey );
  468. if ( dependency ) return dependency;
  469. const json = parser.json;
  470. const extensions = ( json.extensions && json.extensions[ this.name ] ) || {};
  471. const lightDefs = extensions.lights || [];
  472. const lightDef = lightDefs[ lightIndex ];
  473. let lightNode;
  474. const color = new Color( 0xffffff );
  475. if ( lightDef.color !== undefined ) color.setRGB( lightDef.color[ 0 ], lightDef.color[ 1 ], lightDef.color[ 2 ], LinearSRGBColorSpace );
  476. const range = lightDef.range !== undefined ? lightDef.range : 0;
  477. switch ( lightDef.type ) {
  478. case 'directional':
  479. lightNode = new DirectionalLight( color );
  480. lightNode.target.position.set( 0, 0, - 1 );
  481. lightNode.add( lightNode.target );
  482. break;
  483. case 'point':
  484. lightNode = new PointLight( color );
  485. lightNode.distance = range;
  486. break;
  487. case 'spot':
  488. lightNode = new SpotLight( color );
  489. lightNode.distance = range;
  490. // Handle spotlight properties.
  491. lightDef.spot = lightDef.spot || {};
  492. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  493. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  494. lightNode.angle = lightDef.spot.outerConeAngle;
  495. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  496. lightNode.target.position.set( 0, 0, - 1 );
  497. lightNode.add( lightNode.target );
  498. break;
  499. default:
  500. throw new Error( 'THREE.GLTFLoader: Unexpected light type: ' + lightDef.type );
  501. }
  502. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  503. // here, because node-level parsing will only override position if explicitly specified.
  504. lightNode.position.set( 0, 0, 0 );
  505. assignExtrasToUserData( lightNode, lightDef );
  506. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  507. lightNode.name = parser.createUniqueName( lightDef.name || ( 'light_' + lightIndex ) );
  508. dependency = Promise.resolve( lightNode );
  509. parser.cache.add( cacheKey, dependency );
  510. return dependency;
  511. }
  512. getDependency( type, index ) {
  513. if ( type !== 'light' ) return;
  514. return this._loadLight( index );
  515. }
  516. createNodeAttachment( nodeIndex ) {
  517. const self = this;
  518. const parser = this.parser;
  519. const json = parser.json;
  520. const nodeDef = json.nodes[ nodeIndex ];
  521. const lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {};
  522. const lightIndex = lightDef.light;
  523. if ( lightIndex === undefined ) return null;
  524. return this._loadLight( lightIndex ).then( function ( light ) {
  525. return parser._getNodeRef( self.cache, lightIndex, light );
  526. } );
  527. }
  528. }
  529. /**
  530. * Unlit Materials Extension
  531. *
  532. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  533. *
  534. * @private
  535. */
  536. class GLTFMaterialsUnlitExtension {
  537. constructor() {
  538. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  539. }
  540. getMaterialType() {
  541. return MeshBasicMaterial;
  542. }
  543. extendParams( materialParams, materialDef, parser ) {
  544. const pending = [];
  545. materialParams.color = new Color( 1.0, 1.0, 1.0 );
  546. materialParams.opacity = 1.0;
  547. const metallicRoughness = materialDef.pbrMetallicRoughness;
  548. if ( metallicRoughness ) {
  549. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  550. const array = metallicRoughness.baseColorFactor;
  551. materialParams.color.setRGB( array[ 0 ], array[ 1 ], array[ 2 ], LinearSRGBColorSpace );
  552. materialParams.opacity = array[ 3 ];
  553. }
  554. if ( metallicRoughness.baseColorTexture !== undefined ) {
  555. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, SRGBColorSpace ) );
  556. }
  557. }
  558. return Promise.all( pending );
  559. }
  560. }
  561. /**
  562. * Materials Emissive Strength Extension
  563. *
  564. * Specification: https://github.com/KhronosGroup/glTF/blob/5768b3ce0ef32bc39cdf1bef10b948586635ead3/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md
  565. *
  566. * @private
  567. */
  568. class GLTFMaterialsEmissiveStrengthExtension {
  569. constructor( parser ) {
  570. this.parser = parser;
  571. this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH;
  572. }
  573. extendMaterialParams( materialIndex, materialParams ) {
  574. const parser = this.parser;
  575. const materialDef = parser.json.materials[ materialIndex ];
  576. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  577. return Promise.resolve();
  578. }
  579. const emissiveStrength = materialDef.extensions[ this.name ].emissiveStrength;
  580. if ( emissiveStrength !== undefined ) {
  581. materialParams.emissiveIntensity = emissiveStrength;
  582. }
  583. return Promise.resolve();
  584. }
  585. }
  586. /**
  587. * Clearcoat Materials Extension
  588. *
  589. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  590. *
  591. * @private
  592. */
  593. class GLTFMaterialsClearcoatExtension {
  594. constructor( parser ) {
  595. this.parser = parser;
  596. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  597. }
  598. getMaterialType( materialIndex ) {
  599. const parser = this.parser;
  600. const materialDef = parser.json.materials[ materialIndex ];
  601. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  602. return MeshPhysicalMaterial;
  603. }
  604. extendMaterialParams( materialIndex, materialParams ) {
  605. const parser = this.parser;
  606. const materialDef = parser.json.materials[ materialIndex ];
  607. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  608. return Promise.resolve();
  609. }
  610. const pending = [];
  611. const extension = materialDef.extensions[ this.name ];
  612. if ( extension.clearcoatFactor !== undefined ) {
  613. materialParams.clearcoat = extension.clearcoatFactor;
  614. }
  615. if ( extension.clearcoatTexture !== undefined ) {
  616. pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
  617. }
  618. if ( extension.clearcoatRoughnessFactor !== undefined ) {
  619. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  620. }
  621. if ( extension.clearcoatRoughnessTexture !== undefined ) {
  622. pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
  623. }
  624. if ( extension.clearcoatNormalTexture !== undefined ) {
  625. pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
  626. if ( extension.clearcoatNormalTexture.scale !== undefined ) {
  627. const scale = extension.clearcoatNormalTexture.scale;
  628. materialParams.clearcoatNormalScale = new Vector2( scale, scale );
  629. }
  630. }
  631. return Promise.all( pending );
  632. }
  633. }
  634. /**
  635. * Materials dispersion Extension
  636. *
  637. * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_dispersion
  638. *
  639. * @private
  640. */
  641. class GLTFMaterialsDispersionExtension {
  642. constructor( parser ) {
  643. this.parser = parser;
  644. this.name = EXTENSIONS.KHR_MATERIALS_DISPERSION;
  645. }
  646. getMaterialType( materialIndex ) {
  647. const parser = this.parser;
  648. const materialDef = parser.json.materials[ materialIndex ];
  649. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  650. return MeshPhysicalMaterial;
  651. }
  652. extendMaterialParams( materialIndex, materialParams ) {
  653. const parser = this.parser;
  654. const materialDef = parser.json.materials[ materialIndex ];
  655. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  656. return Promise.resolve();
  657. }
  658. const extension = materialDef.extensions[ this.name ];
  659. materialParams.dispersion = extension.dispersion !== undefined ? extension.dispersion : 0;
  660. return Promise.resolve();
  661. }
  662. }
  663. /**
  664. * Iridescence Materials Extension
  665. *
  666. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence
  667. *
  668. * @private
  669. */
  670. class GLTFMaterialsIridescenceExtension {
  671. constructor( parser ) {
  672. this.parser = parser;
  673. this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE;
  674. }
  675. getMaterialType( materialIndex ) {
  676. const parser = this.parser;
  677. const materialDef = parser.json.materials[ materialIndex ];
  678. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  679. return MeshPhysicalMaterial;
  680. }
  681. extendMaterialParams( materialIndex, materialParams ) {
  682. const parser = this.parser;
  683. const materialDef = parser.json.materials[ materialIndex ];
  684. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  685. return Promise.resolve();
  686. }
  687. const pending = [];
  688. const extension = materialDef.extensions[ this.name ];
  689. if ( extension.iridescenceFactor !== undefined ) {
  690. materialParams.iridescence = extension.iridescenceFactor;
  691. }
  692. if ( extension.iridescenceTexture !== undefined ) {
  693. pending.push( parser.assignTexture( materialParams, 'iridescenceMap', extension.iridescenceTexture ) );
  694. }
  695. if ( extension.iridescenceIor !== undefined ) {
  696. materialParams.iridescenceIOR = extension.iridescenceIor;
  697. }
  698. if ( materialParams.iridescenceThicknessRange === undefined ) {
  699. materialParams.iridescenceThicknessRange = [ 100, 400 ];
  700. }
  701. if ( extension.iridescenceThicknessMinimum !== undefined ) {
  702. materialParams.iridescenceThicknessRange[ 0 ] = extension.iridescenceThicknessMinimum;
  703. }
  704. if ( extension.iridescenceThicknessMaximum !== undefined ) {
  705. materialParams.iridescenceThicknessRange[ 1 ] = extension.iridescenceThicknessMaximum;
  706. }
  707. if ( extension.iridescenceThicknessTexture !== undefined ) {
  708. pending.push( parser.assignTexture( materialParams, 'iridescenceThicknessMap', extension.iridescenceThicknessTexture ) );
  709. }
  710. return Promise.all( pending );
  711. }
  712. }
  713. /**
  714. * Sheen Materials Extension
  715. *
  716. * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen
  717. *
  718. * @private
  719. */
  720. class GLTFMaterialsSheenExtension {
  721. constructor( parser ) {
  722. this.parser = parser;
  723. this.name = EXTENSIONS.KHR_MATERIALS_SHEEN;
  724. }
  725. getMaterialType( materialIndex ) {
  726. const parser = this.parser;
  727. const materialDef = parser.json.materials[ materialIndex ];
  728. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  729. return MeshPhysicalMaterial;
  730. }
  731. extendMaterialParams( materialIndex, materialParams ) {
  732. const parser = this.parser;
  733. const materialDef = parser.json.materials[ materialIndex ];
  734. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  735. return Promise.resolve();
  736. }
  737. const pending = [];
  738. materialParams.sheenColor = new Color( 0, 0, 0 );
  739. materialParams.sheenRoughness = 0;
  740. materialParams.sheen = 1;
  741. const extension = materialDef.extensions[ this.name ];
  742. if ( extension.sheenColorFactor !== undefined ) {
  743. const colorFactor = extension.sheenColorFactor;
  744. materialParams.sheenColor.setRGB( colorFactor[ 0 ], colorFactor[ 1 ], colorFactor[ 2 ], LinearSRGBColorSpace );
  745. }
  746. if ( extension.sheenRoughnessFactor !== undefined ) {
  747. materialParams.sheenRoughness = extension.sheenRoughnessFactor;
  748. }
  749. if ( extension.sheenColorTexture !== undefined ) {
  750. pending.push( parser.assignTexture( materialParams, 'sheenColorMap', extension.sheenColorTexture, SRGBColorSpace ) );
  751. }
  752. if ( extension.sheenRoughnessTexture !== undefined ) {
  753. pending.push( parser.assignTexture( materialParams, 'sheenRoughnessMap', extension.sheenRoughnessTexture ) );
  754. }
  755. return Promise.all( pending );
  756. }
  757. }
  758. /**
  759. * Transmission Materials Extension
  760. *
  761. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  762. * Draft: https://github.com/KhronosGroup/glTF/pull/1698
  763. *
  764. * @private
  765. */
  766. class GLTFMaterialsTransmissionExtension {
  767. constructor( parser ) {
  768. this.parser = parser;
  769. this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
  770. }
  771. getMaterialType( materialIndex ) {
  772. const parser = this.parser;
  773. const materialDef = parser.json.materials[ materialIndex ];
  774. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  775. return MeshPhysicalMaterial;
  776. }
  777. extendMaterialParams( materialIndex, materialParams ) {
  778. const parser = this.parser;
  779. const materialDef = parser.json.materials[ materialIndex ];
  780. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  781. return Promise.resolve();
  782. }
  783. const pending = [];
  784. const extension = materialDef.extensions[ this.name ];
  785. if ( extension.transmissionFactor !== undefined ) {
  786. materialParams.transmission = extension.transmissionFactor;
  787. }
  788. if ( extension.transmissionTexture !== undefined ) {
  789. pending.push( parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );
  790. }
  791. return Promise.all( pending );
  792. }
  793. }
  794. /**
  795. * Materials Volume Extension
  796. *
  797. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume
  798. *
  799. * @private
  800. */
  801. class GLTFMaterialsVolumeExtension {
  802. constructor( parser ) {
  803. this.parser = parser;
  804. this.name = EXTENSIONS.KHR_MATERIALS_VOLUME;
  805. }
  806. getMaterialType( materialIndex ) {
  807. const parser = this.parser;
  808. const materialDef = parser.json.materials[ materialIndex ];
  809. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  810. return MeshPhysicalMaterial;
  811. }
  812. extendMaterialParams( materialIndex, materialParams ) {
  813. const parser = this.parser;
  814. const materialDef = parser.json.materials[ materialIndex ];
  815. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  816. return Promise.resolve();
  817. }
  818. const pending = [];
  819. const extension = materialDef.extensions[ this.name ];
  820. materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0;
  821. if ( extension.thicknessTexture !== undefined ) {
  822. pending.push( parser.assignTexture( materialParams, 'thicknessMap', extension.thicknessTexture ) );
  823. }
  824. materialParams.attenuationDistance = extension.attenuationDistance || Infinity;
  825. const colorArray = extension.attenuationColor || [ 1, 1, 1 ];
  826. materialParams.attenuationColor = new Color().setRGB( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ], LinearSRGBColorSpace );
  827. return Promise.all( pending );
  828. }
  829. }
  830. /**
  831. * Materials ior Extension
  832. *
  833. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior
  834. *
  835. * @private
  836. */
  837. class GLTFMaterialsIorExtension {
  838. constructor( parser ) {
  839. this.parser = parser;
  840. this.name = EXTENSIONS.KHR_MATERIALS_IOR;
  841. }
  842. getMaterialType( materialIndex ) {
  843. const parser = this.parser;
  844. const materialDef = parser.json.materials[ materialIndex ];
  845. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  846. return MeshPhysicalMaterial;
  847. }
  848. extendMaterialParams( materialIndex, materialParams ) {
  849. const parser = this.parser;
  850. const materialDef = parser.json.materials[ materialIndex ];
  851. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  852. return Promise.resolve();
  853. }
  854. const extension = materialDef.extensions[ this.name ];
  855. materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5;
  856. return Promise.resolve();
  857. }
  858. }
  859. /**
  860. * Materials specular Extension
  861. *
  862. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular
  863. *
  864. * @private
  865. */
  866. class GLTFMaterialsSpecularExtension {
  867. constructor( parser ) {
  868. this.parser = parser;
  869. this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR;
  870. }
  871. getMaterialType( materialIndex ) {
  872. const parser = this.parser;
  873. const materialDef = parser.json.materials[ materialIndex ];
  874. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  875. return MeshPhysicalMaterial;
  876. }
  877. extendMaterialParams( materialIndex, materialParams ) {
  878. const parser = this.parser;
  879. const materialDef = parser.json.materials[ materialIndex ];
  880. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  881. return Promise.resolve();
  882. }
  883. const pending = [];
  884. const extension = materialDef.extensions[ this.name ];
  885. materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1.0;
  886. if ( extension.specularTexture !== undefined ) {
  887. pending.push( parser.assignTexture( materialParams, 'specularIntensityMap', extension.specularTexture ) );
  888. }
  889. const colorArray = extension.specularColorFactor || [ 1, 1, 1 ];
  890. materialParams.specularColor = new Color().setRGB( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ], LinearSRGBColorSpace );
  891. if ( extension.specularColorTexture !== undefined ) {
  892. pending.push( parser.assignTexture( materialParams, 'specularColorMap', extension.specularColorTexture, SRGBColorSpace ) );
  893. }
  894. return Promise.all( pending );
  895. }
  896. }
  897. /**
  898. * Materials bump Extension
  899. *
  900. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/EXT_materials_bump
  901. *
  902. * @private
  903. */
  904. class GLTFMaterialsBumpExtension {
  905. constructor( parser ) {
  906. this.parser = parser;
  907. this.name = EXTENSIONS.EXT_MATERIALS_BUMP;
  908. }
  909. getMaterialType( materialIndex ) {
  910. const parser = this.parser;
  911. const materialDef = parser.json.materials[ materialIndex ];
  912. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  913. return MeshPhysicalMaterial;
  914. }
  915. extendMaterialParams( materialIndex, materialParams ) {
  916. const parser = this.parser;
  917. const materialDef = parser.json.materials[ materialIndex ];
  918. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  919. return Promise.resolve();
  920. }
  921. const pending = [];
  922. const extension = materialDef.extensions[ this.name ];
  923. materialParams.bumpScale = extension.bumpFactor !== undefined ? extension.bumpFactor : 1.0;
  924. if ( extension.bumpTexture !== undefined ) {
  925. pending.push( parser.assignTexture( materialParams, 'bumpMap', extension.bumpTexture ) );
  926. }
  927. return Promise.all( pending );
  928. }
  929. }
  930. /**
  931. * Materials anisotropy Extension
  932. *
  933. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_anisotropy
  934. *
  935. * @private
  936. */
  937. class GLTFMaterialsAnisotropyExtension {
  938. constructor( parser ) {
  939. this.parser = parser;
  940. this.name = EXTENSIONS.KHR_MATERIALS_ANISOTROPY;
  941. }
  942. getMaterialType( materialIndex ) {
  943. const parser = this.parser;
  944. const materialDef = parser.json.materials[ materialIndex ];
  945. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  946. return MeshPhysicalMaterial;
  947. }
  948. extendMaterialParams( materialIndex, materialParams ) {
  949. const parser = this.parser;
  950. const materialDef = parser.json.materials[ materialIndex ];
  951. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  952. return Promise.resolve();
  953. }
  954. const pending = [];
  955. const extension = materialDef.extensions[ this.name ];
  956. if ( extension.anisotropyStrength !== undefined ) {
  957. materialParams.anisotropy = extension.anisotropyStrength;
  958. }
  959. if ( extension.anisotropyRotation !== undefined ) {
  960. materialParams.anisotropyRotation = extension.anisotropyRotation;
  961. }
  962. if ( extension.anisotropyTexture !== undefined ) {
  963. pending.push( parser.assignTexture( materialParams, 'anisotropyMap', extension.anisotropyTexture ) );
  964. }
  965. return Promise.all( pending );
  966. }
  967. }
  968. /**
  969. * BasisU Texture Extension
  970. *
  971. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
  972. *
  973. * @private
  974. */
  975. class GLTFTextureBasisUExtension {
  976. constructor( parser ) {
  977. this.parser = parser;
  978. this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
  979. }
  980. loadTexture( textureIndex ) {
  981. const parser = this.parser;
  982. const json = parser.json;
  983. const textureDef = json.textures[ textureIndex ];
  984. if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {
  985. return null;
  986. }
  987. const extension = textureDef.extensions[ this.name ];
  988. const loader = parser.options.ktx2Loader;
  989. if ( ! loader ) {
  990. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  991. throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );
  992. } else {
  993. // Assumes that the extension is optional and that a fallback texture is present
  994. return null;
  995. }
  996. }
  997. return parser.loadTextureImage( textureIndex, extension.source, loader );
  998. }
  999. }
  1000. /**
  1001. * WebP Texture Extension
  1002. *
  1003. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
  1004. *
  1005. * @private
  1006. */
  1007. class GLTFTextureWebPExtension {
  1008. constructor( parser ) {
  1009. this.parser = parser;
  1010. this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
  1011. }
  1012. loadTexture( textureIndex ) {
  1013. const name = this.name;
  1014. const parser = this.parser;
  1015. const json = parser.json;
  1016. const textureDef = json.textures[ textureIndex ];
  1017. if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
  1018. return null;
  1019. }
  1020. const extension = textureDef.extensions[ name ];
  1021. const source = json.images[ extension.source ];
  1022. let loader = parser.textureLoader;
  1023. if ( source.uri ) {
  1024. const handler = parser.options.manager.getHandler( source.uri );
  1025. if ( handler !== null ) loader = handler;
  1026. }
  1027. return parser.loadTextureImage( textureIndex, extension.source, loader );
  1028. }
  1029. }
  1030. /**
  1031. * AVIF Texture Extension
  1032. *
  1033. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_avif
  1034. *
  1035. * @private
  1036. */
  1037. class GLTFTextureAVIFExtension {
  1038. constructor( parser ) {
  1039. this.parser = parser;
  1040. this.name = EXTENSIONS.EXT_TEXTURE_AVIF;
  1041. }
  1042. loadTexture( textureIndex ) {
  1043. const name = this.name;
  1044. const parser = this.parser;
  1045. const json = parser.json;
  1046. const textureDef = json.textures[ textureIndex ];
  1047. if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
  1048. return null;
  1049. }
  1050. const extension = textureDef.extensions[ name ];
  1051. const source = json.images[ extension.source ];
  1052. let loader = parser.textureLoader;
  1053. if ( source.uri ) {
  1054. const handler = parser.options.manager.getHandler( source.uri );
  1055. if ( handler !== null ) loader = handler;
  1056. }
  1057. return parser.loadTextureImage( textureIndex, extension.source, loader );
  1058. }
  1059. }
  1060. /**
  1061. * meshopt BufferView Compression Extension
  1062. *
  1063. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
  1064. *
  1065. * @private
  1066. */
  1067. class GLTFMeshoptCompression {
  1068. constructor( parser ) {
  1069. this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
  1070. this.parser = parser;
  1071. }
  1072. loadBufferView( index ) {
  1073. const json = this.parser.json;
  1074. const bufferView = json.bufferViews[ index ];
  1075. if ( bufferView.extensions && bufferView.extensions[ this.name ] ) {
  1076. const extensionDef = bufferView.extensions[ this.name ];
  1077. const buffer = this.parser.getDependency( 'buffer', extensionDef.buffer );
  1078. const decoder = this.parser.options.meshoptDecoder;
  1079. if ( ! decoder || ! decoder.supported ) {
  1080. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  1081. throw new Error( 'THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files' );
  1082. } else {
  1083. // Assumes that the extension is optional and that fallback buffer data is present
  1084. return null;
  1085. }
  1086. }
  1087. return buffer.then( function ( res ) {
  1088. const byteOffset = extensionDef.byteOffset || 0;
  1089. const byteLength = extensionDef.byteLength || 0;
  1090. const count = extensionDef.count;
  1091. const stride = extensionDef.byteStride;
  1092. const source = new Uint8Array( res, byteOffset, byteLength );
  1093. if ( decoder.decodeGltfBufferAsync ) {
  1094. return decoder.decodeGltfBufferAsync( count, stride, source, extensionDef.mode, extensionDef.filter ).then( function ( res ) {
  1095. return res.buffer;
  1096. } );
  1097. } else {
  1098. // Support for MeshoptDecoder 0.18 or earlier, without decodeGltfBufferAsync
  1099. return decoder.ready.then( function () {
  1100. const result = new ArrayBuffer( count * stride );
  1101. decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter );
  1102. return result;
  1103. } );
  1104. }
  1105. } );
  1106. } else {
  1107. return null;
  1108. }
  1109. }
  1110. }
  1111. /**
  1112. * GPU Instancing Extension
  1113. *
  1114. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_mesh_gpu_instancing
  1115. *
  1116. * @private
  1117. */
  1118. class GLTFMeshGpuInstancing {
  1119. constructor( parser ) {
  1120. this.name = EXTENSIONS.EXT_MESH_GPU_INSTANCING;
  1121. this.parser = parser;
  1122. }
  1123. createNodeMesh( nodeIndex ) {
  1124. const json = this.parser.json;
  1125. const nodeDef = json.nodes[ nodeIndex ];
  1126. if ( ! nodeDef.extensions || ! nodeDef.extensions[ this.name ] ||
  1127. nodeDef.mesh === undefined ) {
  1128. return null;
  1129. }
  1130. const meshDef = json.meshes[ nodeDef.mesh ];
  1131. // No Points or Lines + Instancing support yet
  1132. for ( const primitive of meshDef.primitives ) {
  1133. if ( primitive.mode !== WEBGL_CONSTANTS.TRIANGLES &&
  1134. primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_STRIP &&
  1135. primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_FAN &&
  1136. primitive.mode !== undefined ) {
  1137. return null;
  1138. }
  1139. }
  1140. const extensionDef = nodeDef.extensions[ this.name ];
  1141. const attributesDef = extensionDef.attributes;
  1142. // @TODO: Can we support InstancedMesh + SkinnedMesh?
  1143. const pending = [];
  1144. const attributes = {};
  1145. for ( const key in attributesDef ) {
  1146. pending.push( this.parser.getDependency( 'accessor', attributesDef[ key ] ).then( accessor => {
  1147. attributes[ key ] = accessor;
  1148. return attributes[ key ];
  1149. } ) );
  1150. }
  1151. if ( pending.length < 1 ) {
  1152. return null;
  1153. }
  1154. pending.push( this.parser.createNodeMesh( nodeIndex ) );
  1155. return Promise.all( pending ).then( results => {
  1156. const nodeObject = results.pop();
  1157. const meshes = nodeObject.isGroup ? nodeObject.children : [ nodeObject ];
  1158. const count = results[ 0 ].count; // All attribute counts should be same
  1159. const instancedMeshes = [];
  1160. for ( const mesh of meshes ) {
  1161. // Temporal variables
  1162. const m = new Matrix4();
  1163. const p = new Vector3();
  1164. const q = new Quaternion();
  1165. const s = new Vector3( 1, 1, 1 );
  1166. const instancedMesh = new InstancedMesh( mesh.geometry, mesh.material, count );
  1167. for ( let i = 0; i < count; i ++ ) {
  1168. if ( attributes.TRANSLATION ) {
  1169. p.fromBufferAttribute( attributes.TRANSLATION, i );
  1170. }
  1171. if ( attributes.ROTATION ) {
  1172. q.fromBufferAttribute( attributes.ROTATION, i );
  1173. }
  1174. if ( attributes.SCALE ) {
  1175. s.fromBufferAttribute( attributes.SCALE, i );
  1176. }
  1177. instancedMesh.setMatrixAt( i, m.compose( p, q, s ) );
  1178. }
  1179. // Add instance attributes to the geometry, excluding TRS.
  1180. for ( const attributeName in attributes ) {
  1181. if ( attributeName === '_COLOR_0' ) {
  1182. const attr = attributes[ attributeName ];
  1183. instancedMesh.instanceColor = new InstancedBufferAttribute( attr.array, attr.itemSize, attr.normalized );
  1184. } else if ( attributeName !== 'TRANSLATION' &&
  1185. attributeName !== 'ROTATION' &&
  1186. attributeName !== 'SCALE' ) {
  1187. mesh.geometry.setAttribute( attributeName, attributes[ attributeName ] );
  1188. }
  1189. }
  1190. // Just in case
  1191. Object3D.prototype.copy.call( instancedMesh, mesh );
  1192. this.parser.assignFinalMaterial( instancedMesh );
  1193. instancedMeshes.push( instancedMesh );
  1194. }
  1195. if ( nodeObject.isGroup ) {
  1196. nodeObject.clear();
  1197. nodeObject.add( ... instancedMeshes );
  1198. return nodeObject;
  1199. }
  1200. return instancedMeshes[ 0 ];
  1201. } );
  1202. }
  1203. }
  1204. /* BINARY EXTENSION */
  1205. const BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  1206. const BINARY_EXTENSION_HEADER_LENGTH = 12;
  1207. const BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  1208. class GLTFBinaryExtension {
  1209. constructor( data ) {
  1210. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  1211. this.content = null;
  1212. this.body = null;
  1213. const headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  1214. const textDecoder = new TextDecoder();
  1215. this.header = {
  1216. magic: textDecoder.decode( new Uint8Array( data.slice( 0, 4 ) ) ),
  1217. version: headerView.getUint32( 4, true ),
  1218. length: headerView.getUint32( 8, true )
  1219. };
  1220. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  1221. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  1222. } else if ( this.header.version < 2.0 ) {
  1223. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
  1224. }
  1225. const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH;
  1226. const chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  1227. let chunkIndex = 0;
  1228. while ( chunkIndex < chunkContentsLength ) {
  1229. const chunkLength = chunkView.getUint32( chunkIndex, true );
  1230. chunkIndex += 4;
  1231. const chunkType = chunkView.getUint32( chunkIndex, true );
  1232. chunkIndex += 4;
  1233. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  1234. const contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  1235. this.content = textDecoder.decode( contentArray );
  1236. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  1237. const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  1238. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  1239. }
  1240. // Clients must ignore chunks with unknown types.
  1241. chunkIndex += chunkLength;
  1242. }
  1243. if ( this.content === null ) {
  1244. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  1245. }
  1246. }
  1247. }
  1248. /**
  1249. * DRACO Mesh Compression Extension
  1250. *
  1251. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  1252. *
  1253. * @private
  1254. */
  1255. class GLTFDracoMeshCompressionExtension {
  1256. constructor( json, dracoLoader ) {
  1257. if ( ! dracoLoader ) {
  1258. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  1259. }
  1260. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  1261. this.json = json;
  1262. this.dracoLoader = dracoLoader;
  1263. this.dracoLoader.preload();
  1264. }
  1265. decodePrimitive( primitive, parser ) {
  1266. const json = this.json;
  1267. const dracoLoader = this.dracoLoader;
  1268. const bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  1269. const gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  1270. const threeAttributeMap = {};
  1271. const attributeNormalizedMap = {};
  1272. const attributeTypeMap = {};
  1273. for ( const attributeName in gltfAttributeMap ) {
  1274. const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  1275. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  1276. }
  1277. for ( const attributeName in primitive.attributes ) {
  1278. const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  1279. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  1280. const accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  1281. const componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  1282. attributeTypeMap[ threeAttributeName ] = componentType.name;
  1283. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  1284. }
  1285. }
  1286. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  1287. return new Promise( function ( resolve, reject ) {
  1288. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  1289. for ( const attributeName in geometry.attributes ) {
  1290. const attribute = geometry.attributes[ attributeName ];
  1291. const normalized = attributeNormalizedMap[ attributeName ];
  1292. if ( normalized !== undefined ) attribute.normalized = normalized;
  1293. }
  1294. resolve( geometry );
  1295. }, threeAttributeMap, attributeTypeMap, LinearSRGBColorSpace, reject );
  1296. } );
  1297. } );
  1298. }
  1299. }
  1300. /**
  1301. * Texture Transform Extension
  1302. *
  1303. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  1304. *
  1305. * @private
  1306. */
  1307. class GLTFTextureTransformExtension {
  1308. constructor() {
  1309. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  1310. }
  1311. extendTexture( texture, transform ) {
  1312. if ( ( transform.texCoord === undefined || transform.texCoord === texture.channel )
  1313. && transform.offset === undefined
  1314. && transform.rotation === undefined
  1315. && transform.scale === undefined ) {
  1316. // See https://github.com/mrdoob/three.js/issues/21819.
  1317. return texture;
  1318. }
  1319. texture = texture.clone();
  1320. if ( transform.texCoord !== undefined ) {
  1321. texture.channel = transform.texCoord;
  1322. }
  1323. if ( transform.offset !== undefined ) {
  1324. texture.offset.fromArray( transform.offset );
  1325. }
  1326. if ( transform.rotation !== undefined ) {
  1327. texture.rotation = transform.rotation;
  1328. }
  1329. if ( transform.scale !== undefined ) {
  1330. texture.repeat.fromArray( transform.scale );
  1331. }
  1332. texture.needsUpdate = true;
  1333. return texture;
  1334. }
  1335. }
  1336. /**
  1337. * Mesh Quantization Extension
  1338. *
  1339. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  1340. *
  1341. * @private
  1342. */
  1343. class GLTFMeshQuantizationExtension {
  1344. constructor() {
  1345. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  1346. }
  1347. }
  1348. /*********************************/
  1349. /********** INTERPOLATION ********/
  1350. /*********************************/
  1351. // Spline Interpolation
  1352. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  1353. class GLTFCubicSplineInterpolant extends Interpolant {
  1354. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  1355. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  1356. }
  1357. copySampleValue_( index ) {
  1358. // Copies a sample value to the result buffer. See description of glTF
  1359. // CUBICSPLINE values layout in interpolate_() function below.
  1360. const result = this.resultBuffer,
  1361. values = this.sampleValues,
  1362. valueSize = this.valueSize,
  1363. offset = index * valueSize * 3 + valueSize;
  1364. for ( let i = 0; i !== valueSize; i ++ ) {
  1365. result[ i ] = values[ offset + i ];
  1366. }
  1367. return result;
  1368. }
  1369. interpolate_( i1, t0, t, t1 ) {
  1370. const result = this.resultBuffer;
  1371. const values = this.sampleValues;
  1372. const stride = this.valueSize;
  1373. const stride2 = stride * 2;
  1374. const stride3 = stride * 3;
  1375. const td = t1 - t0;
  1376. const p = ( t - t0 ) / td;
  1377. const pp = p * p;
  1378. const ppp = pp * p;
  1379. const offset1 = i1 * stride3;
  1380. const offset0 = offset1 - stride3;
  1381. const s2 = - 2 * ppp + 3 * pp;
  1382. const s3 = ppp - pp;
  1383. const s0 = 1 - s2;
  1384. const s1 = s3 - pp + p;
  1385. // Layout of keyframe output values for CUBICSPLINE animations:
  1386. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  1387. for ( let i = 0; i !== stride; i ++ ) {
  1388. const p0 = values[ offset0 + i + stride ]; // splineVertex_k
  1389. const m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  1390. const p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  1391. const m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  1392. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  1393. }
  1394. return result;
  1395. }
  1396. }
  1397. const _quaternion = new Quaternion();
  1398. class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant {
  1399. interpolate_( i1, t0, t, t1 ) {
  1400. const result = super.interpolate_( i1, t0, t, t1 );
  1401. _quaternion.fromArray( result ).normalize().toArray( result );
  1402. return result;
  1403. }
  1404. }
  1405. /*********************************/
  1406. /********** INTERNALS ************/
  1407. /*********************************/
  1408. /* CONSTANTS */
  1409. const WEBGL_CONSTANTS = {
  1410. FLOAT: 5126,
  1411. //FLOAT_MAT2: 35674,
  1412. FLOAT_MAT3: 35675,
  1413. FLOAT_MAT4: 35676,
  1414. FLOAT_VEC2: 35664,
  1415. FLOAT_VEC3: 35665,
  1416. FLOAT_VEC4: 35666,
  1417. LINEAR: 9729,
  1418. REPEAT: 10497,
  1419. SAMPLER_2D: 35678,
  1420. POINTS: 0,
  1421. LINES: 1,
  1422. LINE_LOOP: 2,
  1423. LINE_STRIP: 3,
  1424. TRIANGLES: 4,
  1425. TRIANGLE_STRIP: 5,
  1426. TRIANGLE_FAN: 6,
  1427. UNSIGNED_BYTE: 5121,
  1428. UNSIGNED_SHORT: 5123
  1429. };
  1430. const WEBGL_COMPONENT_TYPES = {
  1431. 5120: Int8Array,
  1432. 5121: Uint8Array,
  1433. 5122: Int16Array,
  1434. 5123: Uint16Array,
  1435. 5125: Uint32Array,
  1436. 5126: Float32Array
  1437. };
  1438. const WEBGL_FILTERS = {
  1439. 9728: NearestFilter,
  1440. 9729: LinearFilter,
  1441. 9984: NearestMipmapNearestFilter,
  1442. 9985: LinearMipmapNearestFilter,
  1443. 9986: NearestMipmapLinearFilter,
  1444. 9987: LinearMipmapLinearFilter
  1445. };
  1446. const WEBGL_WRAPPINGS = {
  1447. 33071: ClampToEdgeWrapping,
  1448. 33648: MirroredRepeatWrapping,
  1449. 10497: RepeatWrapping
  1450. };
  1451. const WEBGL_TYPE_SIZES = {
  1452. 'SCALAR': 1,
  1453. 'VEC2': 2,
  1454. 'VEC3': 3,
  1455. 'VEC4': 4,
  1456. 'MAT2': 4,
  1457. 'MAT3': 9,
  1458. 'MAT4': 16
  1459. };
  1460. const ATTRIBUTES = {
  1461. POSITION: 'position',
  1462. NORMAL: 'normal',
  1463. TANGENT: 'tangent',
  1464. TEXCOORD_0: 'uv',
  1465. TEXCOORD_1: 'uv1',
  1466. TEXCOORD_2: 'uv2',
  1467. TEXCOORD_3: 'uv3',
  1468. COLOR_0: 'color',
  1469. WEIGHTS_0: 'skinWeight',
  1470. JOINTS_0: 'skinIndex',
  1471. };
  1472. const PATH_PROPERTIES = {
  1473. scale: 'scale',
  1474. translation: 'position',
  1475. rotation: 'quaternion',
  1476. weights: 'morphTargetInfluences'
  1477. };
  1478. const INTERPOLATION = {
  1479. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  1480. // keyframe track will be initialized with a default interpolation type, then modified.
  1481. LINEAR: InterpolateLinear,
  1482. STEP: InterpolateDiscrete
  1483. };
  1484. const ALPHA_MODES = {
  1485. OPAQUE: 'OPAQUE',
  1486. MASK: 'MASK',
  1487. BLEND: 'BLEND'
  1488. };
  1489. /**
  1490. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  1491. *
  1492. * @private
  1493. * @param {Object<string, Material>} cache
  1494. * @return {Material}
  1495. */
  1496. function createDefaultMaterial( cache ) {
  1497. if ( cache[ 'DefaultMaterial' ] === undefined ) {
  1498. cache[ 'DefaultMaterial' ] = new MeshStandardMaterial( {
  1499. color: 0xFFFFFF,
  1500. emissive: 0x000000,
  1501. metalness: 1,
  1502. roughness: 1,
  1503. transparent: false,
  1504. depthTest: true,
  1505. side: FrontSide
  1506. } );
  1507. }
  1508. return cache[ 'DefaultMaterial' ];
  1509. }
  1510. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  1511. // Add unknown glTF extensions to an object's userData.
  1512. for ( const name in objectDef.extensions ) {
  1513. if ( knownExtensions[ name ] === undefined ) {
  1514. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  1515. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  1516. }
  1517. }
  1518. }
  1519. /**
  1520. *
  1521. * @private
  1522. * @param {Object3D|Material|BufferGeometry|Object} object
  1523. * @param {GLTF.definition} gltfDef
  1524. */
  1525. function assignExtrasToUserData( object, gltfDef ) {
  1526. if ( gltfDef.extras !== undefined ) {
  1527. if ( typeof gltfDef.extras === 'object' ) {
  1528. Object.assign( object.userData, gltfDef.extras );
  1529. } else {
  1530. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  1531. }
  1532. }
  1533. }
  1534. /**
  1535. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  1536. *
  1537. * @private
  1538. * @param {BufferGeometry} geometry
  1539. * @param {Array<GLTF.Target>} targets
  1540. * @param {GLTFParser} parser
  1541. * @return {Promise<BufferGeometry>}
  1542. */
  1543. function addMorphTargets( geometry, targets, parser ) {
  1544. let hasMorphPosition = false;
  1545. let hasMorphNormal = false;
  1546. let hasMorphColor = false;
  1547. for ( let i = 0, il = targets.length; i < il; i ++ ) {
  1548. const target = targets[ i ];
  1549. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  1550. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  1551. if ( target.COLOR_0 !== undefined ) hasMorphColor = true;
  1552. if ( hasMorphPosition && hasMorphNormal && hasMorphColor ) break;
  1553. }
  1554. if ( ! hasMorphPosition && ! hasMorphNormal && ! hasMorphColor ) return Promise.resolve( geometry );
  1555. const pendingPositionAccessors = [];
  1556. const pendingNormalAccessors = [];
  1557. const pendingColorAccessors = [];
  1558. for ( let i = 0, il = targets.length; i < il; i ++ ) {
  1559. const target = targets[ i ];
  1560. if ( hasMorphPosition ) {
  1561. const pendingAccessor = target.POSITION !== undefined
  1562. ? parser.getDependency( 'accessor', target.POSITION )
  1563. : geometry.attributes.position;
  1564. pendingPositionAccessors.push( pendingAccessor );
  1565. }
  1566. if ( hasMorphNormal ) {
  1567. const pendingAccessor = target.NORMAL !== undefined
  1568. ? parser.getDependency( 'accessor', target.NORMAL )
  1569. : geometry.attributes.normal;
  1570. pendingNormalAccessors.push( pendingAccessor );
  1571. }
  1572. if ( hasMorphColor ) {
  1573. const pendingAccessor = target.COLOR_0 !== undefined
  1574. ? parser.getDependency( 'accessor', target.COLOR_0 )
  1575. : geometry.attributes.color;
  1576. pendingColorAccessors.push( pendingAccessor );
  1577. }
  1578. }
  1579. return Promise.all( [
  1580. Promise.all( pendingPositionAccessors ),
  1581. Promise.all( pendingNormalAccessors ),
  1582. Promise.all( pendingColorAccessors )
  1583. ] ).then( function ( accessors ) {
  1584. const morphPositions = accessors[ 0 ];
  1585. const morphNormals = accessors[ 1 ];
  1586. const morphColors = accessors[ 2 ];
  1587. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  1588. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  1589. if ( hasMorphColor ) geometry.morphAttributes.color = morphColors;
  1590. geometry.morphTargetsRelative = true;
  1591. return geometry;
  1592. } );
  1593. }
  1594. /**
  1595. *
  1596. * @private
  1597. * @param {Mesh} mesh
  1598. * @param {GLTF.Mesh} meshDef
  1599. */
  1600. function updateMorphTargets( mesh, meshDef ) {
  1601. mesh.updateMorphTargets();
  1602. if ( meshDef.weights !== undefined ) {
  1603. for ( let i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  1604. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  1605. }
  1606. }
  1607. // .extras has user-defined data, so check that .extras.targetNames is an array.
  1608. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  1609. const targetNames = meshDef.extras.targetNames;
  1610. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  1611. mesh.morphTargetDictionary = {};
  1612. for ( let i = 0, il = targetNames.length; i < il; i ++ ) {
  1613. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  1614. }
  1615. } else {
  1616. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  1617. }
  1618. }
  1619. }
  1620. function createPrimitiveKey( primitiveDef ) {
  1621. let geometryKey;
  1622. const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  1623. if ( dracoExtension ) {
  1624. geometryKey = 'draco:' + dracoExtension.bufferView
  1625. + ':' + dracoExtension.indices
  1626. + ':' + createAttributesKey( dracoExtension.attributes );
  1627. } else {
  1628. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  1629. }
  1630. if ( primitiveDef.targets !== undefined ) {
  1631. for ( let i = 0, il = primitiveDef.targets.length; i < il; i ++ ) {
  1632. geometryKey += ':' + createAttributesKey( primitiveDef.targets[ i ] );
  1633. }
  1634. }
  1635. return geometryKey;
  1636. }
  1637. function createAttributesKey( attributes ) {
  1638. let attributesKey = '';
  1639. const keys = Object.keys( attributes ).sort();
  1640. for ( let i = 0, il = keys.length; i < il; i ++ ) {
  1641. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  1642. }
  1643. return attributesKey;
  1644. }
  1645. function getNormalizedComponentScale( constructor ) {
  1646. // Reference:
  1647. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data
  1648. switch ( constructor ) {
  1649. case Int8Array:
  1650. return 1 / 127;
  1651. case Uint8Array:
  1652. return 1 / 255;
  1653. case Int16Array:
  1654. return 1 / 32767;
  1655. case Uint16Array:
  1656. return 1 / 65535;
  1657. default:
  1658. throw new Error( 'THREE.GLTFLoader: Unsupported normalized accessor component type.' );
  1659. }
  1660. }
  1661. function getImageURIMimeType( uri ) {
  1662. if ( uri.search( /\.jpe?g($|\?)/i ) > 0 || uri.search( /^data\:image\/jpeg/ ) === 0 ) return 'image/jpeg';
  1663. if ( uri.search( /\.webp($|\?)/i ) > 0 || uri.search( /^data\:image\/webp/ ) === 0 ) return 'image/webp';
  1664. if ( uri.search( /\.ktx2($|\?)/i ) > 0 || uri.search( /^data\:image\/ktx2/ ) === 0 ) return 'image/ktx2';
  1665. return 'image/png';
  1666. }
  1667. const _identityMatrix = new Matrix4();
  1668. /* GLTF PARSER */
  1669. class GLTFParser {
  1670. constructor( json = {}, options = {} ) {
  1671. this.json = json;
  1672. this.extensions = {};
  1673. this.plugins = {};
  1674. this.options = options;
  1675. // loader object cache
  1676. this.cache = new GLTFRegistry();
  1677. // associations between Three.js objects and glTF elements
  1678. this.associations = new Map();
  1679. // BufferGeometry caching
  1680. this.primitiveCache = {};
  1681. // Node cache
  1682. this.nodeCache = {};
  1683. // Object3D instance caches
  1684. this.meshCache = { refs: {}, uses: {} };
  1685. this.cameraCache = { refs: {}, uses: {} };
  1686. this.lightCache = { refs: {}, uses: {} };
  1687. this.sourceCache = {};
  1688. this.textureCache = {};
  1689. // Track node names, to ensure no duplicates
  1690. this.nodeNamesUsed = {};
  1691. // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
  1692. // expensive work of uploading a texture to the GPU off the main thread.
  1693. let isSafari = false;
  1694. let safariVersion = - 1;
  1695. let isFirefox = false;
  1696. let firefoxVersion = - 1;
  1697. if ( typeof navigator !== 'undefined' ) {
  1698. const userAgent = navigator.userAgent;
  1699. isSafari = /^((?!chrome|android).)*safari/i.test( userAgent ) === true;
  1700. const safariMatch = userAgent.match( /Version\/(\d+)/ );
  1701. safariVersion = isSafari && safariMatch ? parseInt( safariMatch[ 1 ], 10 ) : - 1;
  1702. isFirefox = userAgent.indexOf( 'Firefox' ) > - 1;
  1703. firefoxVersion = isFirefox ? userAgent.match( /Firefox\/([0-9]+)\./ )[ 1 ] : - 1;
  1704. }
  1705. if ( typeof createImageBitmap === 'undefined' || ( isSafari && safariVersion < 17 ) || ( isFirefox && firefoxVersion < 98 ) ) {
  1706. this.textureLoader = new TextureLoader( this.options.manager );
  1707. } else {
  1708. this.textureLoader = new ImageBitmapLoader( this.options.manager );
  1709. }
  1710. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  1711. this.textureLoader.setRequestHeader( this.options.requestHeader );
  1712. this.fileLoader = new FileLoader( this.options.manager );
  1713. this.fileLoader.setResponseType( 'arraybuffer' );
  1714. if ( this.options.crossOrigin === 'use-credentials' ) {
  1715. this.fileLoader.setWithCredentials( true );
  1716. }
  1717. }
  1718. setExtensions( extensions ) {
  1719. this.extensions = extensions;
  1720. }
  1721. setPlugins( plugins ) {
  1722. this.plugins = plugins;
  1723. }
  1724. parse( onLoad, onError ) {
  1725. const parser = this;
  1726. const json = this.json;
  1727. const extensions = this.extensions;
  1728. // Clear the loader cache
  1729. this.cache.removeAll();
  1730. this.nodeCache = {};
  1731. // Mark the special nodes/meshes in json for efficient parse
  1732. this._invokeAll( function ( ext ) {
  1733. return ext._markDefs && ext._markDefs();
  1734. } );
  1735. Promise.all( this._invokeAll( function ( ext ) {
  1736. return ext.beforeRoot && ext.beforeRoot();
  1737. } ) ).then( function () {
  1738. return Promise.all( [
  1739. parser.getDependencies( 'scene' ),
  1740. parser.getDependencies( 'animation' ),
  1741. parser.getDependencies( 'camera' ),
  1742. ] );
  1743. } ).then( function ( dependencies ) {
  1744. const result = {
  1745. scene: dependencies[ 0 ][ json.scene || 0 ],
  1746. scenes: dependencies[ 0 ],
  1747. animations: dependencies[ 1 ],
  1748. cameras: dependencies[ 2 ],
  1749. asset: json.asset,
  1750. parser: parser,
  1751. userData: {}
  1752. };
  1753. addUnknownExtensionsToUserData( extensions, result, json );
  1754. assignExtrasToUserData( result, json );
  1755. return Promise.all( parser._invokeAll( function ( ext ) {
  1756. return ext.afterRoot && ext.afterRoot( result );
  1757. } ) ).then( function () {
  1758. for ( const scene of result.scenes ) {
  1759. scene.updateMatrixWorld();
  1760. }
  1761. onLoad( result );
  1762. } );
  1763. } ).catch( onError );
  1764. }
  1765. /**
  1766. * Marks the special nodes/meshes in json for efficient parse.
  1767. *
  1768. * @private
  1769. */
  1770. _markDefs() {
  1771. const nodeDefs = this.json.nodes || [];
  1772. const skinDefs = this.json.skins || [];
  1773. const meshDefs = this.json.meshes || [];
  1774. // Nothing in the node definition indicates whether it is a Bone or an
  1775. // Object3D. Use the skins' joint references to mark bones.
  1776. for ( let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  1777. const joints = skinDefs[ skinIndex ].joints;
  1778. for ( let i = 0, il = joints.length; i < il; i ++ ) {
  1779. nodeDefs[ joints[ i ] ].isBone = true;
  1780. }
  1781. }
  1782. // Iterate over all nodes, marking references to shared resources,
  1783. // as well as skeleton joints.
  1784. for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  1785. const nodeDef = nodeDefs[ nodeIndex ];
  1786. if ( nodeDef.mesh !== undefined ) {
  1787. this._addNodeRef( this.meshCache, nodeDef.mesh );
  1788. // Nothing in the mesh definition indicates whether it is
  1789. // a SkinnedMesh or Mesh. Use the node's mesh reference
  1790. // to mark SkinnedMesh if node has skin.
  1791. if ( nodeDef.skin !== undefined ) {
  1792. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  1793. }
  1794. }
  1795. if ( nodeDef.camera !== undefined ) {
  1796. this._addNodeRef( this.cameraCache, nodeDef.camera );
  1797. }
  1798. }
  1799. }
  1800. /**
  1801. * Counts references to shared node / Object3D resources. These resources
  1802. * can be reused, or "instantiated", at multiple nodes in the scene
  1803. * hierarchy. Mesh, Camera, and Light instances are instantiated and must
  1804. * be marked. Non-scenegraph resources (like Materials, Geometries, and
  1805. * Textures) can be reused directly and are not marked here.
  1806. *
  1807. * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  1808. *
  1809. * @private
  1810. * @param {Object} cache
  1811. * @param {Object3D} index
  1812. */
  1813. _addNodeRef( cache, index ) {
  1814. if ( index === undefined ) return;
  1815. if ( cache.refs[ index ] === undefined ) {
  1816. cache.refs[ index ] = cache.uses[ index ] = 0;
  1817. }
  1818. cache.refs[ index ] ++;
  1819. }
  1820. /**
  1821. * Returns a reference to a shared resource, cloning it if necessary.
  1822. *
  1823. * @private
  1824. * @param {Object} cache
  1825. * @param {number} index
  1826. * @param {Object} object
  1827. * @return {Object}
  1828. */
  1829. _getNodeRef( cache, index, object ) {
  1830. if ( cache.refs[ index ] <= 1 ) return object;
  1831. const ref = object.clone();
  1832. // Propagates mappings to the cloned object, prevents mappings on the
  1833. // original object from being lost.
  1834. const updateMappings = ( original, clone ) => {
  1835. const mappings = this.associations.get( original );
  1836. if ( mappings != null ) {
  1837. this.associations.set( clone, mappings );
  1838. }
  1839. for ( const [ i, child ] of original.children.entries() ) {
  1840. updateMappings( child, clone.children[ i ] );
  1841. }
  1842. };
  1843. updateMappings( object, ref );
  1844. ref.name += '_instance_' + ( cache.uses[ index ] ++ );
  1845. return ref;
  1846. }
  1847. _invokeOne( func ) {
  1848. const extensions = Object.values( this.plugins );
  1849. extensions.push( this );
  1850. for ( let i = 0; i < extensions.length; i ++ ) {
  1851. const result = func( extensions[ i ] );
  1852. if ( result ) return result;
  1853. }
  1854. return null;
  1855. }
  1856. _invokeAll( func ) {
  1857. const extensions = Object.values( this.plugins );
  1858. extensions.unshift( this );
  1859. const pending = [];
  1860. for ( let i = 0; i < extensions.length; i ++ ) {
  1861. const result = func( extensions[ i ] );
  1862. if ( result ) pending.push( result );
  1863. }
  1864. return pending;
  1865. }
  1866. /**
  1867. * Requests the specified dependency asynchronously, with caching.
  1868. *
  1869. * @private
  1870. * @param {string} type
  1871. * @param {number} index
  1872. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  1873. */
  1874. getDependency( type, index ) {
  1875. const cacheKey = type + ':' + index;
  1876. let dependency = this.cache.get( cacheKey );
  1877. if ( ! dependency ) {
  1878. switch ( type ) {
  1879. case 'scene':
  1880. dependency = this.loadScene( index );
  1881. break;
  1882. case 'node':
  1883. dependency = this._invokeOne( function ( ext ) {
  1884. return ext.loadNode && ext.loadNode( index );
  1885. } );
  1886. break;
  1887. case 'mesh':
  1888. dependency = this._invokeOne( function ( ext ) {
  1889. return ext.loadMesh && ext.loadMesh( index );
  1890. } );
  1891. break;
  1892. case 'accessor':
  1893. dependency = this.loadAccessor( index );
  1894. break;
  1895. case 'bufferView':
  1896. dependency = this._invokeOne( function ( ext ) {
  1897. return ext.loadBufferView && ext.loadBufferView( index );
  1898. } );
  1899. break;
  1900. case 'buffer':
  1901. dependency = this.loadBuffer( index );
  1902. break;
  1903. case 'material':
  1904. dependency = this._invokeOne( function ( ext ) {
  1905. return ext.loadMaterial && ext.loadMaterial( index );
  1906. } );
  1907. break;
  1908. case 'texture':
  1909. dependency = this._invokeOne( function ( ext ) {
  1910. return ext.loadTexture && ext.loadTexture( index );
  1911. } );
  1912. break;
  1913. case 'skin':
  1914. dependency = this.loadSkin( index );
  1915. break;
  1916. case 'animation':
  1917. dependency = this._invokeOne( function ( ext ) {
  1918. return ext.loadAnimation && ext.loadAnimation( index );
  1919. } );
  1920. break;
  1921. case 'camera':
  1922. dependency = this.loadCamera( index );
  1923. break;
  1924. default:
  1925. dependency = this._invokeOne( function ( ext ) {
  1926. return ext != this && ext.getDependency && ext.getDependency( type, index );
  1927. } );
  1928. if ( ! dependency ) {
  1929. throw new Error( 'Unknown type: ' + type );
  1930. }
  1931. break;
  1932. }
  1933. this.cache.add( cacheKey, dependency );
  1934. }
  1935. return dependency;
  1936. }
  1937. /**
  1938. * Requests all dependencies of the specified type asynchronously, with caching.
  1939. *
  1940. * @private
  1941. * @param {string} type
  1942. * @return {Promise<Array<Object>>}
  1943. */
  1944. getDependencies( type ) {
  1945. let dependencies = this.cache.get( type );
  1946. if ( ! dependencies ) {
  1947. const parser = this;
  1948. const defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  1949. dependencies = Promise.all( defs.map( function ( def, index ) {
  1950. return parser.getDependency( type, index );
  1951. } ) );
  1952. this.cache.add( type, dependencies );
  1953. }
  1954. return dependencies;
  1955. }
  1956. /**
  1957. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1958. *
  1959. * @private
  1960. * @param {number} bufferIndex
  1961. * @return {Promise<ArrayBuffer>}
  1962. */
  1963. loadBuffer( bufferIndex ) {
  1964. const bufferDef = this.json.buffers[ bufferIndex ];
  1965. const loader = this.fileLoader;
  1966. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  1967. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  1968. }
  1969. // If present, GLB container is required to be the first buffer.
  1970. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  1971. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  1972. }
  1973. const options = this.options;
  1974. return new Promise( function ( resolve, reject ) {
  1975. loader.load( LoaderUtils.resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  1976. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  1977. } );
  1978. } );
  1979. }
  1980. /**
  1981. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1982. *
  1983. * @private
  1984. * @param {number} bufferViewIndex
  1985. * @return {Promise<ArrayBuffer>}
  1986. */
  1987. loadBufferView( bufferViewIndex ) {
  1988. const bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  1989. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  1990. const byteLength = bufferViewDef.byteLength || 0;
  1991. const byteOffset = bufferViewDef.byteOffset || 0;
  1992. return buffer.slice( byteOffset, byteOffset + byteLength );
  1993. } );
  1994. }
  1995. /**
  1996. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  1997. *
  1998. * @private
  1999. * @param {number} accessorIndex
  2000. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  2001. */
  2002. loadAccessor( accessorIndex ) {
  2003. const parser = this;
  2004. const json = this.json;
  2005. const accessorDef = this.json.accessors[ accessorIndex ];
  2006. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  2007. const itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  2008. const TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  2009. const normalized = accessorDef.normalized === true;
  2010. const array = new TypedArray( accessorDef.count * itemSize );
  2011. return Promise.resolve( new BufferAttribute( array, itemSize, normalized ) );
  2012. }
  2013. const pendingBufferViews = [];
  2014. if ( accessorDef.bufferView !== undefined ) {
  2015. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  2016. } else {
  2017. pendingBufferViews.push( null );
  2018. }
  2019. if ( accessorDef.sparse !== undefined ) {
  2020. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  2021. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  2022. }
  2023. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  2024. const bufferView = bufferViews[ 0 ];
  2025. const itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  2026. const TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  2027. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  2028. const elementBytes = TypedArray.BYTES_PER_ELEMENT;
  2029. const itemBytes = elementBytes * itemSize;
  2030. const byteOffset = accessorDef.byteOffset || 0;
  2031. const byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  2032. const normalized = accessorDef.normalized === true;
  2033. let array, bufferAttribute;
  2034. // The buffer is not interleaved if the stride is the item size in bytes.
  2035. if ( byteStride && byteStride !== itemBytes ) {
  2036. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  2037. // This makes sure that IBA.count reflects accessor.count properly
  2038. const ibSlice = Math.floor( byteOffset / byteStride );
  2039. const ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  2040. let ib = parser.cache.get( ibCacheKey );
  2041. if ( ! ib ) {
  2042. array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
  2043. // Integer parameters to IB/IBA are in array elements, not bytes.
  2044. ib = new InterleavedBuffer( array, byteStride / elementBytes );
  2045. parser.cache.add( ibCacheKey, ib );
  2046. }
  2047. bufferAttribute = new InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
  2048. } else {
  2049. if ( bufferView === null ) {
  2050. array = new TypedArray( accessorDef.count * itemSize );
  2051. } else {
  2052. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  2053. }
  2054. bufferAttribute = new BufferAttribute( array, itemSize, normalized );
  2055. }
  2056. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  2057. if ( accessorDef.sparse !== undefined ) {
  2058. const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  2059. const TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  2060. const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  2061. const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  2062. const sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  2063. const sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  2064. if ( bufferView !== null ) {
  2065. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  2066. bufferAttribute = new BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
  2067. }
  2068. // Ignore normalized since we copy from sparse
  2069. bufferAttribute.normalized = false;
  2070. for ( let i = 0, il = sparseIndices.length; i < il; i ++ ) {
  2071. const index = sparseIndices[ i ];
  2072. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  2073. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  2074. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  2075. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  2076. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  2077. }
  2078. bufferAttribute.normalized = normalized;
  2079. }
  2080. return bufferAttribute;
  2081. } );
  2082. }
  2083. /**
  2084. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  2085. *
  2086. * @private
  2087. * @param {number} textureIndex
  2088. * @return {Promise<THREE.Texture|null>}
  2089. */
  2090. loadTexture( textureIndex ) {
  2091. const json = this.json;
  2092. const options = this.options;
  2093. const textureDef = json.textures[ textureIndex ];
  2094. const sourceIndex = textureDef.source;
  2095. const sourceDef = json.images[ sourceIndex ];
  2096. let loader = this.textureLoader;
  2097. if ( sourceDef.uri ) {
  2098. const handler = options.manager.getHandler( sourceDef.uri );
  2099. if ( handler !== null ) loader = handler;
  2100. }
  2101. return this.loadTextureImage( textureIndex, sourceIndex, loader );
  2102. }
  2103. loadTextureImage( textureIndex, sourceIndex, loader ) {
  2104. const parser = this;
  2105. const json = this.json;
  2106. const textureDef = json.textures[ textureIndex ];
  2107. const sourceDef = json.images[ sourceIndex ];
  2108. const cacheKey = ( sourceDef.uri || sourceDef.bufferView ) + ':' + textureDef.sampler;
  2109. if ( this.textureCache[ cacheKey ] ) {
  2110. // See https://github.com/mrdoob/three.js/issues/21559.
  2111. return this.textureCache[ cacheKey ];
  2112. }
  2113. const promise = this.loadImageSource( sourceIndex, loader ).then( function ( texture ) {
  2114. texture.flipY = false;
  2115. texture.name = textureDef.name || sourceDef.name || '';
  2116. if ( texture.name === '' && typeof sourceDef.uri === 'string' && sourceDef.uri.startsWith( 'data:image/' ) === false ) {
  2117. texture.name = sourceDef.uri;
  2118. }
  2119. const samplers = json.samplers || {};
  2120. const sampler = samplers[ textureDef.sampler ] || {};
  2121. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || LinearFilter;
  2122. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || LinearMipmapLinearFilter;
  2123. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || RepeatWrapping;
  2124. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || RepeatWrapping;
  2125. texture.generateMipmaps = ! texture.isCompressedTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  2126. parser.associations.set( texture, { textures: textureIndex } );
  2127. return texture;
  2128. } ).catch( function () {
  2129. return null;
  2130. } );
  2131. this.textureCache[ cacheKey ] = promise;
  2132. return promise;
  2133. }
  2134. loadImageSource( sourceIndex, loader ) {
  2135. const parser = this;
  2136. const json = this.json;
  2137. const options = this.options;
  2138. if ( this.sourceCache[ sourceIndex ] !== undefined ) {
  2139. return this.sourceCache[ sourceIndex ].then( ( texture ) => texture.clone() );
  2140. }
  2141. const sourceDef = json.images[ sourceIndex ];
  2142. const URL = self.URL || self.webkitURL;
  2143. let sourceURI = sourceDef.uri || '';
  2144. let isObjectURL = false;
  2145. if ( sourceDef.bufferView !== undefined ) {
  2146. // Load binary image data from bufferView, if provided.
  2147. sourceURI = parser.getDependency( 'bufferView', sourceDef.bufferView ).then( function ( bufferView ) {
  2148. isObjectURL = true;
  2149. const blob = new Blob( [ bufferView ], { type: sourceDef.mimeType } );
  2150. sourceURI = URL.createObjectURL( blob );
  2151. return sourceURI;
  2152. } );
  2153. } else if ( sourceDef.uri === undefined ) {
  2154. throw new Error( 'THREE.GLTFLoader: Image ' + sourceIndex + ' is missing URI and bufferView' );
  2155. }
  2156. const promise = Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  2157. return new Promise( function ( resolve, reject ) {
  2158. let onLoad = resolve;
  2159. if ( loader.isImageBitmapLoader === true ) {
  2160. onLoad = function ( imageBitmap ) {
  2161. const texture = new Texture( imageBitmap );
  2162. texture.needsUpdate = true;
  2163. resolve( texture );
  2164. };
  2165. }
  2166. loader.load( LoaderUtils.resolveURL( sourceURI, options.path ), onLoad, undefined, reject );
  2167. } );
  2168. } ).then( function ( texture ) {
  2169. // Clean up resources and configure Texture.
  2170. if ( isObjectURL === true ) {
  2171. URL.revokeObjectURL( sourceURI );
  2172. }
  2173. assignExtrasToUserData( texture, sourceDef );
  2174. texture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType( sourceDef.uri );
  2175. return texture;
  2176. } ).catch( function ( error ) {
  2177. console.error( 'THREE.GLTFLoader: Couldn\'t load texture', sourceURI );
  2178. throw error;
  2179. } );
  2180. this.sourceCache[ sourceIndex ] = promise;
  2181. return promise;
  2182. }
  2183. /**
  2184. * Asynchronously assigns a texture to the given material parameters.
  2185. *
  2186. * @private
  2187. * @param {Object} materialParams
  2188. * @param {string} mapName
  2189. * @param {Object} mapDef
  2190. * @param {string} [colorSpace]
  2191. * @return {Promise<Texture>}
  2192. */
  2193. assignTexture( materialParams, mapName, mapDef, colorSpace ) {
  2194. const parser = this;
  2195. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  2196. if ( ! texture ) return null;
  2197. if ( mapDef.texCoord !== undefined && mapDef.texCoord > 0 ) {
  2198. texture = texture.clone();
  2199. texture.channel = mapDef.texCoord;
  2200. }
  2201. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  2202. const transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  2203. if ( transform ) {
  2204. const gltfReference = parser.associations.get( texture );
  2205. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  2206. parser.associations.set( texture, gltfReference );
  2207. }
  2208. }
  2209. if ( colorSpace !== undefined ) {
  2210. texture.colorSpace = colorSpace;
  2211. }
  2212. materialParams[ mapName ] = texture;
  2213. return texture;
  2214. } );
  2215. }
  2216. /**
  2217. * Assigns final material to a Mesh, Line, or Points instance. The instance
  2218. * already has a material (generated from the glTF material options alone)
  2219. * but reuse of the same glTF material may require multiple threejs materials
  2220. * to accommodate different primitive types, defines, etc. New materials will
  2221. * be created if necessary, and reused from a cache.
  2222. *
  2223. * @private
  2224. * @param {Object3D} mesh Mesh, Line, or Points instance.
  2225. */
  2226. assignFinalMaterial( mesh ) {
  2227. const geometry = mesh.geometry;
  2228. let material = mesh.material;
  2229. const useDerivativeTangents = geometry.attributes.tangent === undefined;
  2230. const useVertexColors = geometry.attributes.color !== undefined;
  2231. const useFlatShading = geometry.attributes.normal === undefined;
  2232. if ( mesh.isPoints ) {
  2233. const cacheKey = 'PointsMaterial:' + material.uuid;
  2234. let pointsMaterial = this.cache.get( cacheKey );
  2235. if ( ! pointsMaterial ) {
  2236. pointsMaterial = new PointsMaterial();
  2237. Material.prototype.copy.call( pointsMaterial, material );
  2238. pointsMaterial.color.copy( material.color );
  2239. pointsMaterial.map = material.map;
  2240. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  2241. this.cache.add( cacheKey, pointsMaterial );
  2242. }
  2243. material = pointsMaterial;
  2244. } else if ( mesh.isLine ) {
  2245. const cacheKey = 'LineBasicMaterial:' + material.uuid;
  2246. let lineMaterial = this.cache.get( cacheKey );
  2247. if ( ! lineMaterial ) {
  2248. lineMaterial = new LineBasicMaterial();
  2249. Material.prototype.copy.call( lineMaterial, material );
  2250. lineMaterial.color.copy( material.color );
  2251. lineMaterial.map = material.map;
  2252. this.cache.add( cacheKey, lineMaterial );
  2253. }
  2254. material = lineMaterial;
  2255. }
  2256. // Clone the material if it will be modified
  2257. if ( useDerivativeTangents || useVertexColors || useFlatShading ) {
  2258. let cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  2259. if ( useDerivativeTangents ) cacheKey += 'derivative-tangents:';
  2260. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  2261. if ( useFlatShading ) cacheKey += 'flat-shading:';
  2262. let cachedMaterial = this.cache.get( cacheKey );
  2263. if ( ! cachedMaterial ) {
  2264. cachedMaterial = material.clone();
  2265. if ( useVertexColors ) cachedMaterial.vertexColors = true;
  2266. if ( useFlatShading ) cachedMaterial.flatShading = true;
  2267. if ( useDerivativeTangents ) {
  2268. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  2269. if ( cachedMaterial.normalScale ) cachedMaterial.normalScale.y *= - 1;
  2270. if ( cachedMaterial.clearcoatNormalScale ) cachedMaterial.clearcoatNormalScale.y *= - 1;
  2271. }
  2272. this.cache.add( cacheKey, cachedMaterial );
  2273. this.associations.set( cachedMaterial, this.associations.get( material ) );
  2274. }
  2275. material = cachedMaterial;
  2276. }
  2277. mesh.material = material;
  2278. }
  2279. getMaterialType( /* materialIndex */ ) {
  2280. return MeshStandardMaterial;
  2281. }
  2282. /**
  2283. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  2284. *
  2285. * @private
  2286. * @param {number} materialIndex
  2287. * @return {Promise<Material>}
  2288. */
  2289. loadMaterial( materialIndex ) {
  2290. const parser = this;
  2291. const json = this.json;
  2292. const extensions = this.extensions;
  2293. const materialDef = json.materials[ materialIndex ];
  2294. let materialType;
  2295. const materialParams = {};
  2296. const materialExtensions = materialDef.extensions || {};
  2297. const pending = [];
  2298. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  2299. const kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  2300. materialType = kmuExtension.getMaterialType();
  2301. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  2302. } else {
  2303. // Specification:
  2304. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  2305. const metallicRoughness = materialDef.pbrMetallicRoughness || {};
  2306. materialParams.color = new Color( 1.0, 1.0, 1.0 );
  2307. materialParams.opacity = 1.0;
  2308. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  2309. const array = metallicRoughness.baseColorFactor;
  2310. materialParams.color.setRGB( array[ 0 ], array[ 1 ], array[ 2 ], LinearSRGBColorSpace );
  2311. materialParams.opacity = array[ 3 ];
  2312. }
  2313. if ( metallicRoughness.baseColorTexture !== undefined ) {
  2314. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, SRGBColorSpace ) );
  2315. }
  2316. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  2317. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  2318. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  2319. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  2320. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  2321. }
  2322. materialType = this._invokeOne( function ( ext ) {
  2323. return ext.getMaterialType && ext.getMaterialType( materialIndex );
  2324. } );
  2325. pending.push( Promise.all( this._invokeAll( function ( ext ) {
  2326. return ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams );
  2327. } ) ) );
  2328. }
  2329. if ( materialDef.doubleSided === true ) {
  2330. materialParams.side = DoubleSide;
  2331. }
  2332. const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  2333. if ( alphaMode === ALPHA_MODES.BLEND ) {
  2334. materialParams.transparent = true;
  2335. // See: https://github.com/mrdoob/three.js/issues/17706
  2336. materialParams.depthWrite = false;
  2337. } else {
  2338. materialParams.transparent = false;
  2339. if ( alphaMode === ALPHA_MODES.MASK ) {
  2340. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  2341. }
  2342. }
  2343. if ( materialDef.normalTexture !== undefined && materialType !== MeshBasicMaterial ) {
  2344. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  2345. materialParams.normalScale = new Vector2( 1, 1 );
  2346. if ( materialDef.normalTexture.scale !== undefined ) {
  2347. const scale = materialDef.normalTexture.scale;
  2348. materialParams.normalScale.set( scale, scale );
  2349. }
  2350. }
  2351. if ( materialDef.occlusionTexture !== undefined && materialType !== MeshBasicMaterial ) {
  2352. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  2353. if ( materialDef.occlusionTexture.strength !== undefined ) {
  2354. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  2355. }
  2356. }
  2357. if ( materialDef.emissiveFactor !== undefined && materialType !== MeshBasicMaterial ) {
  2358. const emissiveFactor = materialDef.emissiveFactor;
  2359. materialParams.emissive = new Color().setRGB( emissiveFactor[ 0 ], emissiveFactor[ 1 ], emissiveFactor[ 2 ], LinearSRGBColorSpace );
  2360. }
  2361. if ( materialDef.emissiveTexture !== undefined && materialType !== MeshBasicMaterial ) {
  2362. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture, SRGBColorSpace ) );
  2363. }
  2364. return Promise.all( pending ).then( function () {
  2365. const material = new materialType( materialParams );
  2366. if ( materialDef.name ) material.name = materialDef.name;
  2367. assignExtrasToUserData( material, materialDef );
  2368. parser.associations.set( material, { materials: materialIndex } );
  2369. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  2370. return material;
  2371. } );
  2372. }
  2373. /**
  2374. * When Object3D instances are targeted by animation, they need unique names.
  2375. *
  2376. * @private
  2377. * @param {string} originalName
  2378. * @return {string}
  2379. */
  2380. createUniqueName( originalName ) {
  2381. const sanitizedName = PropertyBinding.sanitizeNodeName( originalName || '' );
  2382. if ( sanitizedName in this.nodeNamesUsed ) {
  2383. return sanitizedName + '_' + ( ++ this.nodeNamesUsed[ sanitizedName ] );
  2384. } else {
  2385. this.nodeNamesUsed[ sanitizedName ] = 0;
  2386. return sanitizedName;
  2387. }
  2388. }
  2389. /**
  2390. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  2391. *
  2392. * Creates BufferGeometries from primitives.
  2393. *
  2394. * @private
  2395. * @param {Array<GLTF.Primitive>} primitives
  2396. * @return {Promise<Array<BufferGeometry>>}
  2397. */
  2398. loadGeometries( primitives ) {
  2399. const parser = this;
  2400. const extensions = this.extensions;
  2401. const cache = this.primitiveCache;
  2402. function createDracoPrimitive( primitive ) {
  2403. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  2404. .decodePrimitive( primitive, parser )
  2405. .then( function ( geometry ) {
  2406. return addPrimitiveAttributes( geometry, primitive, parser );
  2407. } );
  2408. }
  2409. const pending = [];
  2410. for ( let i = 0, il = primitives.length; i < il; i ++ ) {
  2411. const primitive = primitives[ i ];
  2412. const cacheKey = createPrimitiveKey( primitive );
  2413. // See if we've already created this geometry
  2414. const cached = cache[ cacheKey ];
  2415. if ( cached ) {
  2416. // Use the cached geometry if it exists
  2417. pending.push( cached.promise );
  2418. } else {
  2419. let geometryPromise;
  2420. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  2421. // Use DRACO geometry if available
  2422. geometryPromise = createDracoPrimitive( primitive );
  2423. } else {
  2424. // Otherwise create a new geometry
  2425. geometryPromise = addPrimitiveAttributes( new BufferGeometry(), primitive, parser );
  2426. }
  2427. // Cache this geometry
  2428. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  2429. pending.push( geometryPromise );
  2430. }
  2431. }
  2432. return Promise.all( pending );
  2433. }
  2434. /**
  2435. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  2436. *
  2437. * @private
  2438. * @param {number} meshIndex
  2439. * @return {Promise<Group|Mesh|SkinnedMesh|Line|Points>}
  2440. */
  2441. loadMesh( meshIndex ) {
  2442. const parser = this;
  2443. const json = this.json;
  2444. const extensions = this.extensions;
  2445. const meshDef = json.meshes[ meshIndex ];
  2446. const primitives = meshDef.primitives;
  2447. const pending = [];
  2448. for ( let i = 0, il = primitives.length; i < il; i ++ ) {
  2449. const material = primitives[ i ].material === undefined
  2450. ? createDefaultMaterial( this.cache )
  2451. : this.getDependency( 'material', primitives[ i ].material );
  2452. pending.push( material );
  2453. }
  2454. pending.push( parser.loadGeometries( primitives ) );
  2455. return Promise.all( pending ).then( function ( results ) {
  2456. const materials = results.slice( 0, results.length - 1 );
  2457. const geometries = results[ results.length - 1 ];
  2458. const meshes = [];
  2459. for ( let i = 0, il = geometries.length; i < il; i ++ ) {
  2460. const geometry = geometries[ i ];
  2461. const primitive = primitives[ i ];
  2462. // 1. create Mesh
  2463. let mesh;
  2464. const material = materials[ i ];
  2465. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  2466. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  2467. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  2468. primitive.mode === undefined ) {
  2469. // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
  2470. mesh = meshDef.isSkinnedMesh === true
  2471. ? new SkinnedMesh( geometry, material )
  2472. : new Mesh( geometry, material );
  2473. if ( mesh.isSkinnedMesh === true ) {
  2474. // normalize skin weights to fix malformed assets (see #15319)
  2475. mesh.normalizeSkinWeights();
  2476. }
  2477. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  2478. mesh.geometry = toTrianglesDrawMode( mesh.geometry, TriangleStripDrawMode );
  2479. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  2480. mesh.geometry = toTrianglesDrawMode( mesh.geometry, TriangleFanDrawMode );
  2481. }
  2482. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  2483. mesh = new LineSegments( geometry, material );
  2484. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  2485. mesh = new Line( geometry, material );
  2486. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  2487. mesh = new LineLoop( geometry, material );
  2488. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  2489. mesh = new Points( geometry, material );
  2490. } else {
  2491. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  2492. }
  2493. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  2494. updateMorphTargets( mesh, meshDef );
  2495. }
  2496. mesh.name = parser.createUniqueName( meshDef.name || ( 'mesh_' + meshIndex ) );
  2497. assignExtrasToUserData( mesh, meshDef );
  2498. if ( primitive.extensions ) addUnknownExtensionsToUserData( extensions, mesh, primitive );
  2499. parser.assignFinalMaterial( mesh );
  2500. meshes.push( mesh );
  2501. }
  2502. for ( let i = 0, il = meshes.length; i < il; i ++ ) {
  2503. parser.associations.set( meshes[ i ], {
  2504. meshes: meshIndex,
  2505. primitives: i
  2506. } );
  2507. }
  2508. if ( meshes.length === 1 ) {
  2509. if ( meshDef.extensions ) addUnknownExtensionsToUserData( extensions, meshes[ 0 ], meshDef );
  2510. return meshes[ 0 ];
  2511. }
  2512. const group = new Group();
  2513. if ( meshDef.extensions ) addUnknownExtensionsToUserData( extensions, group, meshDef );
  2514. parser.associations.set( group, { meshes: meshIndex } );
  2515. for ( let i = 0, il = meshes.length; i < il; i ++ ) {
  2516. group.add( meshes[ i ] );
  2517. }
  2518. return group;
  2519. } );
  2520. }
  2521. /**
  2522. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  2523. *
  2524. * @private
  2525. * @param {number} cameraIndex
  2526. * @return {Promise<THREE.Camera>}
  2527. */
  2528. loadCamera( cameraIndex ) {
  2529. let camera;
  2530. const cameraDef = this.json.cameras[ cameraIndex ];
  2531. const params = cameraDef[ cameraDef.type ];
  2532. if ( ! params ) {
  2533. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  2534. return;
  2535. }
  2536. if ( cameraDef.type === 'perspective' ) {
  2537. camera = new PerspectiveCamera( MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  2538. } else if ( cameraDef.type === 'orthographic' ) {
  2539. camera = new OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );
  2540. }
  2541. if ( cameraDef.name ) camera.name = this.createUniqueName( cameraDef.name );
  2542. assignExtrasToUserData( camera, cameraDef );
  2543. return Promise.resolve( camera );
  2544. }
  2545. /**
  2546. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  2547. *
  2548. * @private
  2549. * @param {number} skinIndex
  2550. * @return {Promise<Skeleton>}
  2551. */
  2552. loadSkin( skinIndex ) {
  2553. const skinDef = this.json.skins[ skinIndex ];
  2554. const pending = [];
  2555. for ( let i = 0, il = skinDef.joints.length; i < il; i ++ ) {
  2556. pending.push( this._loadNodeShallow( skinDef.joints[ i ] ) );
  2557. }
  2558. if ( skinDef.inverseBindMatrices !== undefined ) {
  2559. pending.push( this.getDependency( 'accessor', skinDef.inverseBindMatrices ) );
  2560. } else {
  2561. pending.push( null );
  2562. }
  2563. return Promise.all( pending ).then( function ( results ) {
  2564. const inverseBindMatrices = results.pop();
  2565. const jointNodes = results;
  2566. // Note that bones (joint nodes) may or may not be in the
  2567. // scene graph at this time.
  2568. const bones = [];
  2569. const boneInverses = [];
  2570. for ( let i = 0, il = jointNodes.length; i < il; i ++ ) {
  2571. const jointNode = jointNodes[ i ];
  2572. if ( jointNode ) {
  2573. bones.push( jointNode );
  2574. const mat = new Matrix4();
  2575. if ( inverseBindMatrices !== null ) {
  2576. mat.fromArray( inverseBindMatrices.array, i * 16 );
  2577. }
  2578. boneInverses.push( mat );
  2579. } else {
  2580. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinDef.joints[ i ] );
  2581. }
  2582. }
  2583. return new Skeleton( bones, boneInverses );
  2584. } );
  2585. }
  2586. /**
  2587. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  2588. *
  2589. * @private
  2590. * @param {number} animationIndex
  2591. * @return {Promise<AnimationClip>}
  2592. */
  2593. loadAnimation( animationIndex ) {
  2594. const json = this.json;
  2595. const parser = this;
  2596. const animationDef = json.animations[ animationIndex ];
  2597. const animationName = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  2598. const pendingNodes = [];
  2599. const pendingInputAccessors = [];
  2600. const pendingOutputAccessors = [];
  2601. const pendingSamplers = [];
  2602. const pendingTargets = [];
  2603. for ( let i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  2604. const channel = animationDef.channels[ i ];
  2605. const sampler = animationDef.samplers[ channel.sampler ];
  2606. const target = channel.target;
  2607. const name = target.node;
  2608. const input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  2609. const output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  2610. if ( target.node === undefined ) continue;
  2611. pendingNodes.push( this.getDependency( 'node', name ) );
  2612. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  2613. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  2614. pendingSamplers.push( sampler );
  2615. pendingTargets.push( target );
  2616. }
  2617. return Promise.all( [
  2618. Promise.all( pendingNodes ),
  2619. Promise.all( pendingInputAccessors ),
  2620. Promise.all( pendingOutputAccessors ),
  2621. Promise.all( pendingSamplers ),
  2622. Promise.all( pendingTargets )
  2623. ] ).then( function ( dependencies ) {
  2624. const nodes = dependencies[ 0 ];
  2625. const inputAccessors = dependencies[ 1 ];
  2626. const outputAccessors = dependencies[ 2 ];
  2627. const samplers = dependencies[ 3 ];
  2628. const targets = dependencies[ 4 ];
  2629. const tracks = [];
  2630. for ( let i = 0, il = nodes.length; i < il; i ++ ) {
  2631. const node = nodes[ i ];
  2632. const inputAccessor = inputAccessors[ i ];
  2633. const outputAccessor = outputAccessors[ i ];
  2634. const sampler = samplers[ i ];
  2635. const target = targets[ i ];
  2636. if ( node === undefined ) continue;
  2637. if ( node.updateMatrix ) {
  2638. node.updateMatrix();
  2639. }
  2640. const createdTracks = parser._createAnimationTracks( node, inputAccessor, outputAccessor, sampler, target );
  2641. if ( createdTracks ) {
  2642. for ( let k = 0; k < createdTracks.length; k ++ ) {
  2643. tracks.push( createdTracks[ k ] );
  2644. }
  2645. }
  2646. }
  2647. return new AnimationClip( animationName, undefined, tracks );
  2648. } );
  2649. }
  2650. createNodeMesh( nodeIndex ) {
  2651. const json = this.json;
  2652. const parser = this;
  2653. const nodeDef = json.nodes[ nodeIndex ];
  2654. if ( nodeDef.mesh === undefined ) return null;
  2655. return parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  2656. const node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh );
  2657. // if weights are provided on the node, override weights on the mesh.
  2658. if ( nodeDef.weights !== undefined ) {
  2659. node.traverse( function ( o ) {
  2660. if ( ! o.isMesh ) return;
  2661. for ( let i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  2662. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  2663. }
  2664. } );
  2665. }
  2666. return node;
  2667. } );
  2668. }
  2669. /**
  2670. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  2671. *
  2672. * @private
  2673. * @param {number} nodeIndex
  2674. * @return {Promise<Object3D>}
  2675. */
  2676. loadNode( nodeIndex ) {
  2677. const json = this.json;
  2678. const parser = this;
  2679. const nodeDef = json.nodes[ nodeIndex ];
  2680. const nodePending = parser._loadNodeShallow( nodeIndex );
  2681. const childPending = [];
  2682. const childrenDef = nodeDef.children || [];
  2683. for ( let i = 0, il = childrenDef.length; i < il; i ++ ) {
  2684. childPending.push( parser.getDependency( 'node', childrenDef[ i ] ) );
  2685. }
  2686. const skeletonPending = nodeDef.skin === undefined
  2687. ? Promise.resolve( null )
  2688. : parser.getDependency( 'skin', nodeDef.skin );
  2689. return Promise.all( [
  2690. nodePending,
  2691. Promise.all( childPending ),
  2692. skeletonPending
  2693. ] ).then( function ( results ) {
  2694. const node = results[ 0 ];
  2695. const children = results[ 1 ];
  2696. const skeleton = results[ 2 ];
  2697. if ( skeleton !== null ) {
  2698. // This full traverse should be fine because
  2699. // child glTF nodes have not been added to this node yet.
  2700. node.traverse( function ( mesh ) {
  2701. if ( ! mesh.isSkinnedMesh ) return;
  2702. mesh.bind( skeleton, _identityMatrix );
  2703. } );
  2704. }
  2705. for ( let i = 0, il = children.length; i < il; i ++ ) {
  2706. node.add( children[ i ] );
  2707. }
  2708. return node;
  2709. } );
  2710. }
  2711. // ._loadNodeShallow() parses a single node.
  2712. // skin and child nodes are created and added in .loadNode() (no '_' prefix).
  2713. _loadNodeShallow( nodeIndex ) {
  2714. const json = this.json;
  2715. const extensions = this.extensions;
  2716. const parser = this;
  2717. // This method is called from .loadNode() and .loadSkin().
  2718. // Cache a node to avoid duplication.
  2719. if ( this.nodeCache[ nodeIndex ] !== undefined ) {
  2720. return this.nodeCache[ nodeIndex ];
  2721. }
  2722. const nodeDef = json.nodes[ nodeIndex ];
  2723. // reserve node's name before its dependencies, so the root has the intended name.
  2724. const nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : '';
  2725. const pending = [];
  2726. const meshPromise = parser._invokeOne( function ( ext ) {
  2727. return ext.createNodeMesh && ext.createNodeMesh( nodeIndex );
  2728. } );
  2729. if ( meshPromise ) {
  2730. pending.push( meshPromise );
  2731. }
  2732. if ( nodeDef.camera !== undefined ) {
  2733. pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {
  2734. return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );
  2735. } ) );
  2736. }
  2737. parser._invokeAll( function ( ext ) {
  2738. return ext.createNodeAttachment && ext.createNodeAttachment( nodeIndex );
  2739. } ).forEach( function ( promise ) {
  2740. pending.push( promise );
  2741. } );
  2742. this.nodeCache[ nodeIndex ] = Promise.all( pending ).then( function ( objects ) {
  2743. let node;
  2744. // .isBone isn't in glTF spec. See ._markDefs
  2745. if ( nodeDef.isBone === true ) {
  2746. node = new Bone();
  2747. } else if ( objects.length > 1 ) {
  2748. node = new Group();
  2749. } else if ( objects.length === 1 ) {
  2750. node = objects[ 0 ];
  2751. } else {
  2752. node = new Object3D();
  2753. }
  2754. if ( node !== objects[ 0 ] ) {
  2755. for ( let i = 0, il = objects.length; i < il; i ++ ) {
  2756. node.add( objects[ i ] );
  2757. }
  2758. }
  2759. if ( nodeDef.name ) {
  2760. node.userData.name = nodeDef.name;
  2761. node.name = nodeName;
  2762. }
  2763. assignExtrasToUserData( node, nodeDef );
  2764. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  2765. if ( nodeDef.matrix !== undefined ) {
  2766. const matrix = new Matrix4();
  2767. matrix.fromArray( nodeDef.matrix );
  2768. node.applyMatrix4( matrix );
  2769. } else {
  2770. if ( nodeDef.translation !== undefined ) {
  2771. node.position.fromArray( nodeDef.translation );
  2772. }
  2773. if ( nodeDef.rotation !== undefined ) {
  2774. node.quaternion.fromArray( nodeDef.rotation );
  2775. }
  2776. if ( nodeDef.scale !== undefined ) {
  2777. node.scale.fromArray( nodeDef.scale );
  2778. }
  2779. }
  2780. if ( ! parser.associations.has( node ) ) {
  2781. parser.associations.set( node, {} );
  2782. }
  2783. parser.associations.get( node ).nodes = nodeIndex;
  2784. return node;
  2785. } );
  2786. return this.nodeCache[ nodeIndex ];
  2787. }
  2788. /**
  2789. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  2790. *
  2791. * @private
  2792. * @param {number} sceneIndex
  2793. * @return {Promise<Group>}
  2794. */
  2795. loadScene( sceneIndex ) {
  2796. const extensions = this.extensions;
  2797. const sceneDef = this.json.scenes[ sceneIndex ];
  2798. const parser = this;
  2799. // Loader returns Group, not Scene.
  2800. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  2801. const scene = new Group();
  2802. if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name );
  2803. assignExtrasToUserData( scene, sceneDef );
  2804. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  2805. const nodeIds = sceneDef.nodes || [];
  2806. const pending = [];
  2807. for ( let i = 0, il = nodeIds.length; i < il; i ++ ) {
  2808. pending.push( parser.getDependency( 'node', nodeIds[ i ] ) );
  2809. }
  2810. return Promise.all( pending ).then( function ( nodes ) {
  2811. for ( let i = 0, il = nodes.length; i < il; i ++ ) {
  2812. scene.add( nodes[ i ] );
  2813. }
  2814. // Removes dangling associations, associations that reference a node that
  2815. // didn't make it into the scene.
  2816. const reduceAssociations = ( node ) => {
  2817. const reducedAssociations = new Map();
  2818. for ( const [ key, value ] of parser.associations ) {
  2819. if ( key instanceof Material || key instanceof Texture ) {
  2820. reducedAssociations.set( key, value );
  2821. }
  2822. }
  2823. node.traverse( ( node ) => {
  2824. const mappings = parser.associations.get( node );
  2825. if ( mappings != null ) {
  2826. reducedAssociations.set( node, mappings );
  2827. }
  2828. } );
  2829. return reducedAssociations;
  2830. };
  2831. parser.associations = reduceAssociations( scene );
  2832. return scene;
  2833. } );
  2834. }
  2835. _createAnimationTracks( node, inputAccessor, outputAccessor, sampler, target ) {
  2836. const tracks = [];
  2837. const targetName = node.name ? node.name : node.uuid;
  2838. const targetNames = [];
  2839. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  2840. node.traverse( function ( object ) {
  2841. if ( object.morphTargetInfluences ) {
  2842. targetNames.push( object.name ? object.name : object.uuid );
  2843. }
  2844. } );
  2845. } else {
  2846. targetNames.push( targetName );
  2847. }
  2848. let TypedKeyframeTrack;
  2849. switch ( PATH_PROPERTIES[ target.path ] ) {
  2850. case PATH_PROPERTIES.weights:
  2851. TypedKeyframeTrack = NumberKeyframeTrack;
  2852. break;
  2853. case PATH_PROPERTIES.rotation:
  2854. TypedKeyframeTrack = QuaternionKeyframeTrack;
  2855. break;
  2856. case PATH_PROPERTIES.translation:
  2857. case PATH_PROPERTIES.scale:
  2858. TypedKeyframeTrack = VectorKeyframeTrack;
  2859. break;
  2860. default:
  2861. switch ( outputAccessor.itemSize ) {
  2862. case 1:
  2863. TypedKeyframeTrack = NumberKeyframeTrack;
  2864. break;
  2865. case 2:
  2866. case 3:
  2867. default:
  2868. TypedKeyframeTrack = VectorKeyframeTrack;
  2869. break;
  2870. }
  2871. break;
  2872. }
  2873. const interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : InterpolateLinear;
  2874. const outputArray = this._getArrayFromAccessor( outputAccessor );
  2875. for ( let j = 0, jl = targetNames.length; j < jl; j ++ ) {
  2876. const track = new TypedKeyframeTrack(
  2877. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  2878. inputAccessor.array,
  2879. outputArray,
  2880. interpolation
  2881. );
  2882. // Override interpolation with custom factory method.
  2883. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  2884. this._createCubicSplineTrackInterpolant( track );
  2885. }
  2886. tracks.push( track );
  2887. }
  2888. return tracks;
  2889. }
  2890. _getArrayFromAccessor( accessor ) {
  2891. let outputArray = accessor.array;
  2892. if ( accessor.normalized ) {
  2893. const scale = getNormalizedComponentScale( outputArray.constructor );
  2894. const scaled = new Float32Array( outputArray.length );
  2895. for ( let j = 0, jl = outputArray.length; j < jl; j ++ ) {
  2896. scaled[ j ] = outputArray[ j ] * scale;
  2897. }
  2898. outputArray = scaled;
  2899. }
  2900. return outputArray;
  2901. }
  2902. _createCubicSplineTrackInterpolant( track ) {
  2903. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  2904. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  2905. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  2906. // must be divided by three to get the interpolant's sampleSize argument.
  2907. const interpolantType = ( this instanceof QuaternionKeyframeTrack ) ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant;
  2908. return new interpolantType( this.times, this.values, this.getValueSize() / 3, result );
  2909. };
  2910. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  2911. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  2912. }
  2913. }
  2914. /**
  2915. *
  2916. * @private
  2917. * @param {BufferGeometry} geometry
  2918. * @param {GLTF.Primitive} primitiveDef
  2919. * @param {GLTFParser} parser
  2920. */
  2921. function computeBounds( geometry, primitiveDef, parser ) {
  2922. const attributes = primitiveDef.attributes;
  2923. const box = new Box3();
  2924. if ( attributes.POSITION !== undefined ) {
  2925. const accessor = parser.json.accessors[ attributes.POSITION ];
  2926. const min = accessor.min;
  2927. const max = accessor.max;
  2928. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  2929. if ( min !== undefined && max !== undefined ) {
  2930. box.set(
  2931. new Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
  2932. new Vector3( max[ 0 ], max[ 1 ], max[ 2 ] )
  2933. );
  2934. if ( accessor.normalized ) {
  2935. const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );
  2936. box.min.multiplyScalar( boxScale );
  2937. box.max.multiplyScalar( boxScale );
  2938. }
  2939. } else {
  2940. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  2941. return;
  2942. }
  2943. } else {
  2944. return;
  2945. }
  2946. const targets = primitiveDef.targets;
  2947. if ( targets !== undefined ) {
  2948. const maxDisplacement = new Vector3();
  2949. const vector = new Vector3();
  2950. for ( let i = 0, il = targets.length; i < il; i ++ ) {
  2951. const target = targets[ i ];
  2952. if ( target.POSITION !== undefined ) {
  2953. const accessor = parser.json.accessors[ target.POSITION ];
  2954. const min = accessor.min;
  2955. const max = accessor.max;
  2956. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  2957. if ( min !== undefined && max !== undefined ) {
  2958. // we need to get max of absolute components because target weight is [-1,1]
  2959. vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
  2960. vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
  2961. vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
  2962. if ( accessor.normalized ) {
  2963. const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );
  2964. vector.multiplyScalar( boxScale );
  2965. }
  2966. // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  2967. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  2968. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  2969. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  2970. maxDisplacement.max( vector );
  2971. } else {
  2972. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  2973. }
  2974. }
  2975. }
  2976. // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  2977. box.expandByVector( maxDisplacement );
  2978. }
  2979. geometry.boundingBox = box;
  2980. const sphere = new Sphere();
  2981. box.getCenter( sphere.center );
  2982. sphere.radius = box.min.distanceTo( box.max ) / 2;
  2983. geometry.boundingSphere = sphere;
  2984. }
  2985. /**
  2986. *
  2987. * @private
  2988. * @param {BufferGeometry} geometry
  2989. * @param {GLTF.Primitive} primitiveDef
  2990. * @param {GLTFParser} parser
  2991. * @return {Promise<BufferGeometry>}
  2992. */
  2993. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  2994. const attributes = primitiveDef.attributes;
  2995. const pending = [];
  2996. function assignAttributeAccessor( accessorIndex, attributeName ) {
  2997. return parser.getDependency( 'accessor', accessorIndex )
  2998. .then( function ( accessor ) {
  2999. geometry.setAttribute( attributeName, accessor );
  3000. } );
  3001. }
  3002. for ( const gltfAttributeName in attributes ) {
  3003. const threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  3004. // Skip attributes already provided by e.g. Draco extension.
  3005. if ( threeAttributeName in geometry.attributes ) continue;
  3006. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  3007. }
  3008. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  3009. const accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  3010. geometry.setIndex( accessor );
  3011. } );
  3012. pending.push( accessor );
  3013. }
  3014. if ( ColorManagement.workingColorSpace !== LinearSRGBColorSpace && 'COLOR_0' in attributes ) {
  3015. console.warn( `THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${ColorManagement.workingColorSpace}" not supported.` );
  3016. }
  3017. assignExtrasToUserData( geometry, primitiveDef );
  3018. computeBounds( geometry, primitiveDef, parser );
  3019. return Promise.all( pending ).then( function () {
  3020. return primitiveDef.targets !== undefined
  3021. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  3022. : geometry;
  3023. } );
  3024. }
  3025. /**
  3026. * Loader result of `GLTFLoader`.
  3027. *
  3028. * @typedef {Object} GLTFLoader~LoadObject
  3029. * @property {Array<AnimationClip>} animations - An array of animation clips.
  3030. * @property {Object} asset - Meta data about the loaded asset.
  3031. * @property {Array<Camera>} cameras - An array of cameras.
  3032. * @property {GLTFParser} parser - A reference to the internal parser.
  3033. * @property {Group} scene - The default scene.
  3034. * @property {Array<Group>} scenes - glTF assets might define multiple scenes.
  3035. * @property {Object} userData - Additional data.
  3036. **/
  3037. export { GLTFLoader };