babylon.glTFFileLoader.js 240 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686
  1. "use strict";
  2. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  3. var BABYLON;
  4. (function (BABYLON) {
  5. var GLTFLoaderCoordinateSystemMode;
  6. (function (GLTFLoaderCoordinateSystemMode) {
  7. /**
  8. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  9. */
  10. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  11. /**
  12. * Sets the useRightHandedSystem flag on the scene.
  13. */
  14. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  15. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  16. var GLTFLoaderAnimationStartMode;
  17. (function (GLTFLoaderAnimationStartMode) {
  18. /**
  19. * No animation will start.
  20. */
  21. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  22. /**
  23. * The first animation will start.
  24. */
  25. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  26. /**
  27. * All animations will start.
  28. */
  29. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  30. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  31. var GLTFLoaderState;
  32. (function (GLTFLoaderState) {
  33. /**
  34. * The asset is loading.
  35. */
  36. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  37. /**
  38. * The asset is ready for rendering.
  39. */
  40. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  41. /**
  42. * The asset is completely loaded.
  43. */
  44. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  45. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  46. var GLTFFileLoader = /** @class */ (function () {
  47. function GLTFFileLoader() {
  48. // #region Common options
  49. /**
  50. * Raised when the asset has been parsed.
  51. * The data.json property stores the glTF JSON.
  52. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  53. */
  54. this.onParsedObservable = new BABYLON.Observable();
  55. // #endregion
  56. // #region V2 options
  57. /**
  58. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  59. */
  60. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  61. /**
  62. * The animation start mode (NONE, FIRST, ALL).
  63. */
  64. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  65. /**
  66. * Set to true to compile materials before raising the success callback.
  67. */
  68. this.compileMaterials = false;
  69. /**
  70. * Set to true to also compile materials with clip planes.
  71. */
  72. this.useClipPlane = false;
  73. /**
  74. * Set to true to compile shadow generators before raising the success callback.
  75. */
  76. this.compileShadowGenerators = false;
  77. /**
  78. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  79. */
  80. this.onMeshLoadedObservable = new BABYLON.Observable();
  81. /**
  82. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  83. */
  84. this.onTextureLoadedObservable = new BABYLON.Observable();
  85. /**
  86. * Raised when the loader creates a material after parsing the glTF properties of the material.
  87. */
  88. this.onMaterialLoadedObservable = new BABYLON.Observable();
  89. /**
  90. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  91. * For assets with LODs, raised when all of the LODs are complete.
  92. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  93. */
  94. this.onCompleteObservable = new BABYLON.Observable();
  95. /**
  96. * Raised after the loader is disposed.
  97. */
  98. this.onDisposeObservable = new BABYLON.Observable();
  99. /**
  100. * Raised after a loader extension is created.
  101. * Set additional options for a loader extension in this event.
  102. */
  103. this.onExtensionLoadedObservable = new BABYLON.Observable();
  104. // #endregion
  105. this._loader = null;
  106. this.name = "gltf";
  107. this.extensions = {
  108. ".gltf": { isBinary: false },
  109. ".glb": { isBinary: true }
  110. };
  111. }
  112. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  113. set: function (callback) {
  114. if (this._onParsedObserver) {
  115. this.onParsedObservable.remove(this._onParsedObserver);
  116. }
  117. this._onParsedObserver = this.onParsedObservable.add(callback);
  118. },
  119. enumerable: true,
  120. configurable: true
  121. });
  122. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  123. set: function (callback) {
  124. if (this._onMeshLoadedObserver) {
  125. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  126. }
  127. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  128. },
  129. enumerable: true,
  130. configurable: true
  131. });
  132. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  133. set: function (callback) {
  134. if (this._onTextureLoadedObserver) {
  135. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  136. }
  137. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  138. },
  139. enumerable: true,
  140. configurable: true
  141. });
  142. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  143. set: function (callback) {
  144. if (this._onMaterialLoadedObserver) {
  145. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  146. }
  147. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  148. },
  149. enumerable: true,
  150. configurable: true
  151. });
  152. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  153. set: function (callback) {
  154. if (this._onCompleteObserver) {
  155. this.onCompleteObservable.remove(this._onCompleteObserver);
  156. }
  157. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  158. },
  159. enumerable: true,
  160. configurable: true
  161. });
  162. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  163. set: function (callback) {
  164. if (this._onDisposeObserver) {
  165. this.onDisposeObservable.remove(this._onDisposeObserver);
  166. }
  167. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  168. },
  169. enumerable: true,
  170. configurable: true
  171. });
  172. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  173. set: function (callback) {
  174. if (this._onExtensionLoadedObserver) {
  175. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  176. }
  177. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  178. },
  179. enumerable: true,
  180. configurable: true
  181. });
  182. /**
  183. * Returns a promise that resolves when the asset is completely loaded.
  184. * @returns A promise that resolves when the asset is completely loaded.
  185. */
  186. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  187. var _this = this;
  188. return new Promise(function (resolve) {
  189. _this.onCompleteObservable.add(function () {
  190. resolve();
  191. }, undefined, undefined, undefined, true);
  192. });
  193. };
  194. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  195. /**
  196. * The loader state (LOADING, READY, COMPLETE) or null if the loader is not active.
  197. */
  198. get: function () {
  199. return this._loader ? this._loader.state : null;
  200. },
  201. enumerable: true,
  202. configurable: true
  203. });
  204. /**
  205. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  206. */
  207. GLTFFileLoader.prototype.dispose = function () {
  208. if (this._loader) {
  209. this._loader.dispose();
  210. this._loader = null;
  211. }
  212. this.onMeshLoadedObservable.clear();
  213. this.onTextureLoadedObservable.clear();
  214. this.onMaterialLoadedObservable.clear();
  215. this.onDisposeObservable.notifyObservers(this);
  216. this.onDisposeObservable.clear();
  217. };
  218. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  219. var _this = this;
  220. return Promise.resolve().then(function () {
  221. var loaderData = _this._parse(data);
  222. _this._loader = _this._getLoader(loaderData);
  223. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  224. });
  225. };
  226. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  227. var _this = this;
  228. return Promise.resolve().then(function () {
  229. var loaderData = _this._parse(data);
  230. _this._loader = _this._getLoader(loaderData);
  231. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  232. });
  233. };
  234. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  235. var _this = this;
  236. return Promise.resolve().then(function () {
  237. var loaderData = _this._parse(data);
  238. _this._loader = _this._getLoader(loaderData);
  239. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  240. var container = new BABYLON.AssetContainer(scene);
  241. Array.prototype.push.apply(container.meshes, result.meshes);
  242. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  243. Array.prototype.push.apply(container.skeletons, result.skeletons);
  244. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  245. container.removeAllFromScene();
  246. return container;
  247. });
  248. });
  249. };
  250. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  251. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  252. };
  253. GLTFFileLoader.prototype.createPlugin = function () {
  254. return new GLTFFileLoader();
  255. };
  256. GLTFFileLoader.prototype._parse = function (data) {
  257. var parsedData;
  258. if (data instanceof ArrayBuffer) {
  259. parsedData = GLTFFileLoader._parseBinary(data);
  260. }
  261. else {
  262. parsedData = {
  263. json: JSON.parse(data),
  264. bin: null
  265. };
  266. }
  267. this.onParsedObservable.notifyObservers(parsedData);
  268. this.onParsedObservable.clear();
  269. return parsedData;
  270. };
  271. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  272. var _this = this;
  273. var loaderVersion = { major: 2, minor: 0 };
  274. var asset = loaderData.json.asset || {};
  275. var version = GLTFFileLoader._parseVersion(asset.version);
  276. if (!version) {
  277. throw new Error("Invalid version: " + asset.version);
  278. }
  279. if (asset.minVersion !== undefined) {
  280. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  281. if (!minVersion) {
  282. throw new Error("Invalid minimum version: " + asset.minVersion);
  283. }
  284. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  285. throw new Error("Incompatible minimum version: " + asset.minVersion);
  286. }
  287. }
  288. var createLoaders = {
  289. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  290. 2: GLTFFileLoader.CreateGLTFLoaderV2
  291. };
  292. var createLoader = createLoaders[version.major];
  293. if (!createLoader) {
  294. throw new Error("Unsupported version: " + asset.version);
  295. }
  296. var loader = createLoader();
  297. loader.coordinateSystemMode = this.coordinateSystemMode;
  298. loader.animationStartMode = this.animationStartMode;
  299. loader.compileMaterials = this.compileMaterials;
  300. loader.useClipPlane = this.useClipPlane;
  301. loader.compileShadowGenerators = this.compileShadowGenerators;
  302. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  303. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  304. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  305. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  306. loader.onCompleteObservable.add(function () {
  307. _this.onMeshLoadedObservable.clear();
  308. _this.onTextureLoadedObservable.clear();
  309. _this.onMaterialLoadedObservable.clear();
  310. _this.onCompleteObservable.notifyObservers(_this);
  311. _this.onCompleteObservable.clear();
  312. });
  313. return loader;
  314. };
  315. GLTFFileLoader._parseBinary = function (data) {
  316. var Binary = {
  317. Magic: 0x46546C67
  318. };
  319. var binaryReader = new BinaryReader(data);
  320. var magic = binaryReader.readUint32();
  321. if (magic !== Binary.Magic) {
  322. throw new Error("Unexpected magic: " + magic);
  323. }
  324. var version = binaryReader.readUint32();
  325. switch (version) {
  326. case 1: return GLTFFileLoader._parseV1(binaryReader);
  327. case 2: return GLTFFileLoader._parseV2(binaryReader);
  328. }
  329. throw new Error("Unsupported version: " + version);
  330. };
  331. GLTFFileLoader._parseV1 = function (binaryReader) {
  332. var ContentFormat = {
  333. JSON: 0
  334. };
  335. var length = binaryReader.readUint32();
  336. if (length != binaryReader.getLength()) {
  337. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  338. }
  339. var contentLength = binaryReader.readUint32();
  340. var contentFormat = binaryReader.readUint32();
  341. var content;
  342. switch (contentFormat) {
  343. case ContentFormat.JSON: {
  344. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  345. break;
  346. }
  347. default: {
  348. throw new Error("Unexpected content format: " + contentFormat);
  349. }
  350. }
  351. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  352. var body = binaryReader.readUint8Array(bytesRemaining);
  353. return {
  354. json: content,
  355. bin: body
  356. };
  357. };
  358. GLTFFileLoader._parseV2 = function (binaryReader) {
  359. var ChunkFormat = {
  360. JSON: 0x4E4F534A,
  361. BIN: 0x004E4942
  362. };
  363. var length = binaryReader.readUint32();
  364. if (length !== binaryReader.getLength()) {
  365. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  366. }
  367. // JSON chunk
  368. var chunkLength = binaryReader.readUint32();
  369. var chunkFormat = binaryReader.readUint32();
  370. if (chunkFormat !== ChunkFormat.JSON) {
  371. throw new Error("First chunk format is not JSON");
  372. }
  373. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  374. // Look for BIN chunk
  375. var bin = null;
  376. while (binaryReader.getPosition() < binaryReader.getLength()) {
  377. var chunkLength_1 = binaryReader.readUint32();
  378. var chunkFormat_1 = binaryReader.readUint32();
  379. switch (chunkFormat_1) {
  380. case ChunkFormat.JSON: {
  381. throw new Error("Unexpected JSON chunk");
  382. }
  383. case ChunkFormat.BIN: {
  384. bin = binaryReader.readUint8Array(chunkLength_1);
  385. break;
  386. }
  387. default: {
  388. // ignore unrecognized chunkFormat
  389. binaryReader.skipBytes(chunkLength_1);
  390. break;
  391. }
  392. }
  393. }
  394. return {
  395. json: json,
  396. bin: bin
  397. };
  398. };
  399. GLTFFileLoader._parseVersion = function (version) {
  400. if (version === "1.0" || version === "1.0.1") {
  401. return {
  402. major: 1,
  403. minor: 0
  404. };
  405. }
  406. var match = (version + "").match(/^(\d+)\.(\d+)/);
  407. if (!match) {
  408. return null;
  409. }
  410. return {
  411. major: parseInt(match[1]),
  412. minor: parseInt(match[2])
  413. };
  414. };
  415. GLTFFileLoader._compareVersion = function (a, b) {
  416. if (a.major > b.major)
  417. return 1;
  418. if (a.major < b.major)
  419. return -1;
  420. if (a.minor > b.minor)
  421. return 1;
  422. if (a.minor < b.minor)
  423. return -1;
  424. return 0;
  425. };
  426. GLTFFileLoader._decodeBufferToText = function (buffer) {
  427. var result = "";
  428. var length = buffer.byteLength;
  429. for (var i = 0; i < length; i++) {
  430. result += String.fromCharCode(buffer[i]);
  431. }
  432. return result;
  433. };
  434. // #endregion
  435. // #region V1 options
  436. GLTFFileLoader.IncrementalLoading = true;
  437. GLTFFileLoader.HomogeneousCoordinates = false;
  438. return GLTFFileLoader;
  439. }());
  440. BABYLON.GLTFFileLoader = GLTFFileLoader;
  441. var BinaryReader = /** @class */ (function () {
  442. function BinaryReader(arrayBuffer) {
  443. this._arrayBuffer = arrayBuffer;
  444. this._dataView = new DataView(arrayBuffer);
  445. this._byteOffset = 0;
  446. }
  447. BinaryReader.prototype.getPosition = function () {
  448. return this._byteOffset;
  449. };
  450. BinaryReader.prototype.getLength = function () {
  451. return this._arrayBuffer.byteLength;
  452. };
  453. BinaryReader.prototype.readUint32 = function () {
  454. var value = this._dataView.getUint32(this._byteOffset, true);
  455. this._byteOffset += 4;
  456. return value;
  457. };
  458. BinaryReader.prototype.readUint8Array = function (length) {
  459. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  460. this._byteOffset += length;
  461. return value;
  462. };
  463. BinaryReader.prototype.skipBytes = function (length) {
  464. this._byteOffset += length;
  465. };
  466. return BinaryReader;
  467. }());
  468. if (BABYLON.SceneLoader) {
  469. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  470. }
  471. })(BABYLON || (BABYLON = {}));
  472. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  473. "use strict";
  474. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  475. var BABYLON;
  476. (function (BABYLON) {
  477. var GLTF1;
  478. (function (GLTF1) {
  479. /**
  480. * Enums
  481. */
  482. var EComponentType;
  483. (function (EComponentType) {
  484. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  485. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  486. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  487. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  488. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  489. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  490. var EShaderType;
  491. (function (EShaderType) {
  492. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  493. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  494. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  495. var EParameterType;
  496. (function (EParameterType) {
  497. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  498. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  499. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  500. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  501. EParameterType[EParameterType["INT"] = 5124] = "INT";
  502. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  503. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  504. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  505. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  506. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  507. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  508. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  509. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  510. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  511. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  512. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  513. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  514. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  515. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  516. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  517. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  518. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  519. var ETextureWrapMode;
  520. (function (ETextureWrapMode) {
  521. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  522. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  523. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  524. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  525. var ETextureFilterType;
  526. (function (ETextureFilterType) {
  527. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  528. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  529. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  530. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  531. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  532. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  533. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  534. var ETextureFormat;
  535. (function (ETextureFormat) {
  536. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  537. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  538. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  539. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  540. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  541. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  542. var ECullingType;
  543. (function (ECullingType) {
  544. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  545. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  546. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  547. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  548. var EBlendingFunction;
  549. (function (EBlendingFunction) {
  550. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  551. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  552. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  553. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  554. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  555. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  556. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  557. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  558. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  559. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  560. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  561. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  562. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  563. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  564. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  565. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  566. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  567. })(BABYLON || (BABYLON = {}));
  568. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  569. "use strict";
  570. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  571. var BABYLON;
  572. (function (BABYLON) {
  573. var GLTF1;
  574. (function (GLTF1) {
  575. /**
  576. * Tokenizer. Used for shaders compatibility
  577. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  578. */
  579. var ETokenType;
  580. (function (ETokenType) {
  581. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  582. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  583. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  584. })(ETokenType || (ETokenType = {}));
  585. var Tokenizer = /** @class */ (function () {
  586. function Tokenizer(toParse) {
  587. this._pos = 0;
  588. this.currentToken = ETokenType.UNKNOWN;
  589. this.currentIdentifier = "";
  590. this.currentString = "";
  591. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  592. this._toParse = toParse;
  593. this._maxPos = toParse.length;
  594. }
  595. Tokenizer.prototype.getNextToken = function () {
  596. if (this.isEnd())
  597. return ETokenType.END_OF_INPUT;
  598. this.currentString = this.read();
  599. this.currentToken = ETokenType.UNKNOWN;
  600. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  601. this.currentToken = ETokenType.IDENTIFIER;
  602. this.currentIdentifier = this.currentString;
  603. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  604. this.currentIdentifier += this.currentString;
  605. this.forward();
  606. }
  607. }
  608. return this.currentToken;
  609. };
  610. Tokenizer.prototype.peek = function () {
  611. return this._toParse[this._pos];
  612. };
  613. Tokenizer.prototype.read = function () {
  614. return this._toParse[this._pos++];
  615. };
  616. Tokenizer.prototype.forward = function () {
  617. this._pos++;
  618. };
  619. Tokenizer.prototype.isEnd = function () {
  620. return this._pos >= this._maxPos;
  621. };
  622. return Tokenizer;
  623. }());
  624. /**
  625. * Values
  626. */
  627. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  628. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  629. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  630. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  631. /**
  632. * Parse
  633. */
  634. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  635. for (var buf in parsedBuffers) {
  636. var parsedBuffer = parsedBuffers[buf];
  637. gltfRuntime.buffers[buf] = parsedBuffer;
  638. gltfRuntime.buffersCount++;
  639. }
  640. };
  641. var parseShaders = function (parsedShaders, gltfRuntime) {
  642. for (var sha in parsedShaders) {
  643. var parsedShader = parsedShaders[sha];
  644. gltfRuntime.shaders[sha] = parsedShader;
  645. gltfRuntime.shaderscount++;
  646. }
  647. };
  648. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  649. for (var object in parsedObjects) {
  650. var parsedObject = parsedObjects[object];
  651. gltfRuntime[runtimeProperty][object] = parsedObject;
  652. }
  653. };
  654. /**
  655. * Utils
  656. */
  657. var normalizeUVs = function (buffer) {
  658. if (!buffer) {
  659. return;
  660. }
  661. for (var i = 0; i < buffer.length / 2; i++) {
  662. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  663. }
  664. };
  665. var getAttribute = function (attributeParameter) {
  666. if (attributeParameter.semantic === "NORMAL") {
  667. return "normal";
  668. }
  669. else if (attributeParameter.semantic === "POSITION") {
  670. return "position";
  671. }
  672. else if (attributeParameter.semantic === "JOINT") {
  673. return "matricesIndices";
  674. }
  675. else if (attributeParameter.semantic === "WEIGHT") {
  676. return "matricesWeights";
  677. }
  678. else if (attributeParameter.semantic === "COLOR") {
  679. return "color";
  680. }
  681. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  682. var channel = Number(attributeParameter.semantic.split("_")[1]);
  683. return "uv" + (channel === 0 ? "" : channel + 1);
  684. }
  685. return null;
  686. };
  687. /**
  688. * Loads and creates animations
  689. */
  690. var loadAnimations = function (gltfRuntime) {
  691. for (var anim in gltfRuntime.animations) {
  692. var animation = gltfRuntime.animations[anim];
  693. if (!animation.channels || !animation.samplers) {
  694. continue;
  695. }
  696. var lastAnimation = null;
  697. for (var i = 0; i < animation.channels.length; i++) {
  698. // Get parameters and load buffers
  699. var channel = animation.channels[i];
  700. var sampler = animation.samplers[channel.sampler];
  701. if (!sampler) {
  702. continue;
  703. }
  704. var inputData = null;
  705. var outputData = null;
  706. if (animation.parameters) {
  707. inputData = animation.parameters[sampler.input];
  708. outputData = animation.parameters[sampler.output];
  709. }
  710. else {
  711. inputData = sampler.input;
  712. outputData = sampler.output;
  713. }
  714. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  715. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  716. var targetID = channel.target.id;
  717. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  718. if (targetNode === null) {
  719. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  720. }
  721. if (targetNode === null) {
  722. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  723. continue;
  724. }
  725. var isBone = targetNode instanceof BABYLON.Bone;
  726. // Get target path (position, rotation or scaling)
  727. var targetPath = channel.target.path;
  728. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  729. if (targetPathIndex !== -1) {
  730. targetPath = babylonAnimationPaths[targetPathIndex];
  731. }
  732. // Determine animation type
  733. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  734. if (!isBone) {
  735. if (targetPath === "rotationQuaternion") {
  736. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  737. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  738. }
  739. else {
  740. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  741. }
  742. }
  743. // Create animation and key frames
  744. var babylonAnimation = null;
  745. var keys = [];
  746. var arrayOffset = 0;
  747. var modifyKey = false;
  748. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  749. babylonAnimation = lastAnimation;
  750. modifyKey = true;
  751. }
  752. if (!modifyKey) {
  753. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  754. }
  755. // For each frame
  756. for (var j = 0; j < bufferInput.length; j++) {
  757. var value = null;
  758. if (targetPath === "rotationQuaternion") {
  759. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  760. arrayOffset += 4;
  761. }
  762. else {
  763. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  764. arrayOffset += 3;
  765. }
  766. if (isBone) {
  767. var bone = targetNode;
  768. var translation = BABYLON.Vector3.Zero();
  769. var rotationQuaternion = new BABYLON.Quaternion();
  770. var scaling = BABYLON.Vector3.Zero();
  771. // Warning on decompose
  772. var mat = bone.getBaseMatrix();
  773. if (modifyKey && lastAnimation) {
  774. mat = lastAnimation.getKeys()[j].value;
  775. }
  776. mat.decompose(scaling, rotationQuaternion, translation);
  777. if (targetPath === "position") {
  778. translation = value;
  779. }
  780. else if (targetPath === "rotationQuaternion") {
  781. rotationQuaternion = value;
  782. }
  783. else {
  784. scaling = value;
  785. }
  786. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  787. }
  788. if (!modifyKey) {
  789. keys.push({
  790. frame: bufferInput[j],
  791. value: value
  792. });
  793. }
  794. else if (lastAnimation) {
  795. lastAnimation.getKeys()[j].value = value;
  796. }
  797. }
  798. // Finish
  799. if (!modifyKey && babylonAnimation) {
  800. babylonAnimation.setKeys(keys);
  801. targetNode.animations.push(babylonAnimation);
  802. }
  803. lastAnimation = babylonAnimation;
  804. gltfRuntime.scene.stopAnimation(targetNode);
  805. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  806. }
  807. }
  808. };
  809. /**
  810. * Returns the bones transformation matrix
  811. */
  812. var configureBoneTransformation = function (node) {
  813. var mat = null;
  814. if (node.translation || node.rotation || node.scale) {
  815. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  816. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  817. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  818. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  819. }
  820. else {
  821. mat = BABYLON.Matrix.FromArray(node.matrix);
  822. }
  823. return mat;
  824. };
  825. /**
  826. * Returns the parent bone
  827. */
  828. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  829. // Try to find
  830. for (var i = 0; i < newSkeleton.bones.length; i++) {
  831. if (newSkeleton.bones[i].name === jointName) {
  832. return newSkeleton.bones[i];
  833. }
  834. }
  835. // Not found, search in gltf nodes
  836. var nodes = gltfRuntime.nodes;
  837. for (var nde in nodes) {
  838. var node = nodes[nde];
  839. if (!node.jointName) {
  840. continue;
  841. }
  842. var children = node.children;
  843. for (var i = 0; i < children.length; i++) {
  844. var child = gltfRuntime.nodes[children[i]];
  845. if (!child.jointName) {
  846. continue;
  847. }
  848. if (child.jointName === jointName) {
  849. var mat = configureBoneTransformation(node);
  850. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  851. bone.id = nde;
  852. return bone;
  853. }
  854. }
  855. }
  856. return null;
  857. };
  858. /**
  859. * Returns the appropriate root node
  860. */
  861. var getNodeToRoot = function (nodesToRoot, id) {
  862. for (var i = 0; i < nodesToRoot.length; i++) {
  863. var nodeToRoot = nodesToRoot[i];
  864. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  865. var child = nodeToRoot.node.children[j];
  866. if (child === id) {
  867. return nodeToRoot.bone;
  868. }
  869. }
  870. }
  871. return null;
  872. };
  873. /**
  874. * Returns the node with the joint name
  875. */
  876. var getJointNode = function (gltfRuntime, jointName) {
  877. var nodes = gltfRuntime.nodes;
  878. var node = nodes[jointName];
  879. if (node) {
  880. return {
  881. node: node,
  882. id: jointName
  883. };
  884. }
  885. for (var nde in nodes) {
  886. node = nodes[nde];
  887. if (node.jointName === jointName) {
  888. return {
  889. node: node,
  890. id: nde
  891. };
  892. }
  893. }
  894. return null;
  895. };
  896. /**
  897. * Checks if a nodes is in joints
  898. */
  899. var nodeIsInJoints = function (skins, id) {
  900. for (var i = 0; i < skins.jointNames.length; i++) {
  901. if (skins.jointNames[i] === id) {
  902. return true;
  903. }
  904. }
  905. return false;
  906. };
  907. /**
  908. * Fills the nodes to root for bones and builds hierarchy
  909. */
  910. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  911. // Creates nodes for root
  912. for (var nde in gltfRuntime.nodes) {
  913. var node = gltfRuntime.nodes[nde];
  914. var id = nde;
  915. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  916. continue;
  917. }
  918. // Create node to root bone
  919. var mat = configureBoneTransformation(node);
  920. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  921. bone.id = id;
  922. nodesToRoot.push({ bone: bone, node: node, id: id });
  923. }
  924. // Parenting
  925. for (var i = 0; i < nodesToRoot.length; i++) {
  926. var nodeToRoot = nodesToRoot[i];
  927. var children = nodeToRoot.node.children;
  928. for (var j = 0; j < children.length; j++) {
  929. var child = null;
  930. for (var k = 0; k < nodesToRoot.length; k++) {
  931. if (nodesToRoot[k].id === children[j]) {
  932. child = nodesToRoot[k];
  933. break;
  934. }
  935. }
  936. if (child) {
  937. child.bone._parent = nodeToRoot.bone;
  938. nodeToRoot.bone.children.push(child.bone);
  939. }
  940. }
  941. }
  942. };
  943. /**
  944. * Imports a skeleton
  945. */
  946. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  947. if (!newSkeleton) {
  948. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  949. }
  950. if (!skins.babylonSkeleton) {
  951. return newSkeleton;
  952. }
  953. // Find the root bones
  954. var nodesToRoot = [];
  955. var nodesToRootToAdd = [];
  956. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  957. newSkeleton.bones = [];
  958. // Joints
  959. for (var i = 0; i < skins.jointNames.length; i++) {
  960. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  961. if (!jointNode) {
  962. continue;
  963. }
  964. var node = jointNode.node;
  965. if (!node) {
  966. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  967. continue;
  968. }
  969. var id = jointNode.id;
  970. // Optimize, if the bone already exists...
  971. var existingBone = gltfRuntime.scene.getBoneByID(id);
  972. if (existingBone) {
  973. newSkeleton.bones.push(existingBone);
  974. continue;
  975. }
  976. // Search for parent bone
  977. var foundBone = false;
  978. var parentBone = null;
  979. for (var j = 0; j < i; j++) {
  980. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  981. if (!jointNode_1) {
  982. continue;
  983. }
  984. var joint = jointNode_1.node;
  985. if (!joint) {
  986. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  987. continue;
  988. }
  989. var children = joint.children;
  990. if (!children) {
  991. continue;
  992. }
  993. foundBone = false;
  994. for (var k = 0; k < children.length; k++) {
  995. if (children[k] === id) {
  996. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  997. foundBone = true;
  998. break;
  999. }
  1000. }
  1001. if (foundBone) {
  1002. break;
  1003. }
  1004. }
  1005. // Create bone
  1006. var mat = configureBoneTransformation(node);
  1007. if (!parentBone && nodesToRoot.length > 0) {
  1008. parentBone = getNodeToRoot(nodesToRoot, id);
  1009. if (parentBone) {
  1010. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  1011. nodesToRootToAdd.push(parentBone);
  1012. }
  1013. }
  1014. }
  1015. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  1016. bone.id = id;
  1017. }
  1018. // Polish
  1019. var bones = newSkeleton.bones;
  1020. newSkeleton.bones = [];
  1021. for (var i = 0; i < skins.jointNames.length; i++) {
  1022. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1023. if (!jointNode) {
  1024. continue;
  1025. }
  1026. for (var j = 0; j < bones.length; j++) {
  1027. if (bones[j].id === jointNode.id) {
  1028. newSkeleton.bones.push(bones[j]);
  1029. break;
  1030. }
  1031. }
  1032. }
  1033. newSkeleton.prepare();
  1034. // Finish
  1035. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  1036. newSkeleton.bones.push(nodesToRootToAdd[i]);
  1037. }
  1038. return newSkeleton;
  1039. };
  1040. /**
  1041. * Imports a mesh and its geometries
  1042. */
  1043. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  1044. if (!newMesh) {
  1045. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1046. newMesh.id = id;
  1047. }
  1048. if (!node.babylonNode) {
  1049. return newMesh;
  1050. }
  1051. var subMaterials = [];
  1052. var vertexData = null;
  1053. var verticesStarts = new Array();
  1054. var verticesCounts = new Array();
  1055. var indexStarts = new Array();
  1056. var indexCounts = new Array();
  1057. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1058. var meshID = meshes[meshIndex];
  1059. var mesh = gltfRuntime.meshes[meshID];
  1060. if (!mesh) {
  1061. continue;
  1062. }
  1063. // Positions, normals and UVs
  1064. for (var i = 0; i < mesh.primitives.length; i++) {
  1065. // Temporary vertex data
  1066. var tempVertexData = new BABYLON.VertexData();
  1067. var primitive = mesh.primitives[i];
  1068. if (primitive.mode !== 4) {
  1069. // continue;
  1070. }
  1071. var attributes = primitive.attributes;
  1072. var accessor = null;
  1073. var buffer = null;
  1074. // Set positions, normal and uvs
  1075. for (var semantic in attributes) {
  1076. // Link accessor and buffer view
  1077. accessor = gltfRuntime.accessors[attributes[semantic]];
  1078. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1079. if (semantic === "NORMAL") {
  1080. tempVertexData.normals = new Float32Array(buffer.length);
  1081. tempVertexData.normals.set(buffer);
  1082. }
  1083. else if (semantic === "POSITION") {
  1084. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  1085. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  1086. for (var j = 0; j < buffer.length; j += 4) {
  1087. tempVertexData.positions[j] = buffer[j];
  1088. tempVertexData.positions[j + 1] = buffer[j + 1];
  1089. tempVertexData.positions[j + 2] = buffer[j + 2];
  1090. }
  1091. }
  1092. else {
  1093. tempVertexData.positions = new Float32Array(buffer.length);
  1094. tempVertexData.positions.set(buffer);
  1095. }
  1096. verticesCounts.push(tempVertexData.positions.length);
  1097. }
  1098. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  1099. var channel = Number(semantic.split("_")[1]);
  1100. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  1101. var uvs = new Float32Array(buffer.length);
  1102. uvs.set(buffer);
  1103. normalizeUVs(uvs);
  1104. tempVertexData.set(uvs, uvKind);
  1105. }
  1106. else if (semantic === "JOINT") {
  1107. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  1108. tempVertexData.matricesIndices.set(buffer);
  1109. }
  1110. else if (semantic === "WEIGHT") {
  1111. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  1112. tempVertexData.matricesWeights.set(buffer);
  1113. }
  1114. else if (semantic === "COLOR") {
  1115. tempVertexData.colors = new Float32Array(buffer.length);
  1116. tempVertexData.colors.set(buffer);
  1117. }
  1118. }
  1119. // Indices
  1120. accessor = gltfRuntime.accessors[primitive.indices];
  1121. if (accessor) {
  1122. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1123. tempVertexData.indices = new Int32Array(buffer.length);
  1124. tempVertexData.indices.set(buffer);
  1125. indexCounts.push(tempVertexData.indices.length);
  1126. }
  1127. else {
  1128. // Set indices on the fly
  1129. var indices = [];
  1130. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  1131. indices.push(j);
  1132. }
  1133. tempVertexData.indices = new Int32Array(indices);
  1134. indexCounts.push(tempVertexData.indices.length);
  1135. }
  1136. if (!vertexData) {
  1137. vertexData = tempVertexData;
  1138. }
  1139. else {
  1140. vertexData.merge(tempVertexData);
  1141. }
  1142. // Sub material
  1143. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  1144. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  1145. // Update vertices start and index start
  1146. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  1147. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  1148. }
  1149. }
  1150. var material;
  1151. if (subMaterials.length > 1) {
  1152. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  1153. material.subMaterials = subMaterials;
  1154. }
  1155. else {
  1156. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  1157. }
  1158. if (subMaterials.length === 1) {
  1159. material = subMaterials[0];
  1160. }
  1161. if (!newMesh.material) {
  1162. newMesh.material = material;
  1163. }
  1164. // Apply geometry
  1165. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  1166. newMesh.computeWorldMatrix(true);
  1167. // Apply submeshes
  1168. newMesh.subMeshes = [];
  1169. var index = 0;
  1170. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1171. var meshID = meshes[meshIndex];
  1172. var mesh = gltfRuntime.meshes[meshID];
  1173. if (!mesh) {
  1174. continue;
  1175. }
  1176. for (var i = 0; i < mesh.primitives.length; i++) {
  1177. if (mesh.primitives[i].mode !== 4) {
  1178. //continue;
  1179. }
  1180. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  1181. index++;
  1182. }
  1183. }
  1184. // Finish
  1185. return newMesh;
  1186. };
  1187. /**
  1188. * Configure node transformation from position, rotation and scaling
  1189. */
  1190. var configureNode = function (newNode, position, rotation, scaling) {
  1191. if (newNode.position) {
  1192. newNode.position = position;
  1193. }
  1194. if (newNode.rotationQuaternion || newNode.rotation) {
  1195. newNode.rotationQuaternion = rotation;
  1196. }
  1197. if (newNode.scaling) {
  1198. newNode.scaling = scaling;
  1199. }
  1200. };
  1201. /**
  1202. * Configures node from transformation matrix
  1203. */
  1204. var configureNodeFromMatrix = function (newNode, node, parent) {
  1205. if (node.matrix) {
  1206. var position = new BABYLON.Vector3(0, 0, 0);
  1207. var rotation = new BABYLON.Quaternion();
  1208. var scaling = new BABYLON.Vector3(0, 0, 0);
  1209. var mat = BABYLON.Matrix.FromArray(node.matrix);
  1210. mat.decompose(scaling, rotation, position);
  1211. configureNode(newNode, position, rotation, scaling);
  1212. }
  1213. else if (node.translation && node.rotation && node.scale) {
  1214. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  1215. }
  1216. newNode.computeWorldMatrix(true);
  1217. };
  1218. /**
  1219. * Imports a node
  1220. */
  1221. var importNode = function (gltfRuntime, node, id, parent) {
  1222. var lastNode = null;
  1223. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  1224. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  1225. return null;
  1226. }
  1227. }
  1228. // Meshes
  1229. if (node.skin) {
  1230. if (node.meshes) {
  1231. var skin = gltfRuntime.skins[node.skin];
  1232. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  1233. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  1234. if (newMesh.skeleton === null) {
  1235. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  1236. if (!skin.babylonSkeleton) {
  1237. skin.babylonSkeleton = newMesh.skeleton;
  1238. }
  1239. }
  1240. lastNode = newMesh;
  1241. }
  1242. }
  1243. else if (node.meshes) {
  1244. /**
  1245. * Improve meshes property
  1246. */
  1247. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  1248. lastNode = newMesh;
  1249. }
  1250. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1251. var light = gltfRuntime.lights[node.light];
  1252. if (light) {
  1253. if (light.type === "ambient") {
  1254. var ambienLight = light[light.type];
  1255. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1256. hemiLight.name = node.name || "";
  1257. if (ambienLight.color) {
  1258. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  1259. }
  1260. lastNode = hemiLight;
  1261. }
  1262. else if (light.type === "directional") {
  1263. var directionalLight = light[light.type];
  1264. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1265. dirLight.name = node.name || "";
  1266. if (directionalLight.color) {
  1267. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  1268. }
  1269. lastNode = dirLight;
  1270. }
  1271. else if (light.type === "point") {
  1272. var pointLight = light[light.type];
  1273. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1274. ptLight.name = node.name || "";
  1275. if (pointLight.color) {
  1276. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  1277. }
  1278. lastNode = ptLight;
  1279. }
  1280. else if (light.type === "spot") {
  1281. var spotLight = light[light.type];
  1282. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1283. spLight.name = node.name || "";
  1284. if (spotLight.color) {
  1285. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  1286. }
  1287. if (spotLight.fallOfAngle) {
  1288. spLight.angle = spotLight.fallOfAngle;
  1289. }
  1290. if (spotLight.fallOffExponent) {
  1291. spLight.exponent = spotLight.fallOffExponent;
  1292. }
  1293. lastNode = spLight;
  1294. }
  1295. }
  1296. }
  1297. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1298. var camera = gltfRuntime.cameras[node.camera];
  1299. if (camera) {
  1300. if (camera.type === "orthographic") {
  1301. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1302. orthoCamera.name = node.name || "";
  1303. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1304. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1305. lastNode = orthoCamera;
  1306. }
  1307. else if (camera.type === "perspective") {
  1308. var perspectiveCamera = camera[camera.type];
  1309. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1310. persCamera.name = node.name || "";
  1311. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1312. if (!perspectiveCamera.aspectRatio) {
  1313. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1314. }
  1315. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1316. persCamera.maxZ = perspectiveCamera.zfar;
  1317. persCamera.minZ = perspectiveCamera.znear;
  1318. }
  1319. lastNode = persCamera;
  1320. }
  1321. }
  1322. }
  1323. // Empty node
  1324. if (!node.jointName) {
  1325. if (node.babylonNode) {
  1326. return node.babylonNode;
  1327. }
  1328. else if (lastNode === null) {
  1329. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1330. node.babylonNode = dummy;
  1331. lastNode = dummy;
  1332. }
  1333. }
  1334. if (lastNode !== null) {
  1335. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  1336. configureNodeFromMatrix(lastNode, node, parent);
  1337. }
  1338. else {
  1339. var translation = node.translation || [0, 0, 0];
  1340. var rotation = node.rotation || [0, 0, 0, 1];
  1341. var scale = node.scale || [1, 1, 1];
  1342. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  1343. }
  1344. lastNode.updateCache(true);
  1345. node.babylonNode = lastNode;
  1346. }
  1347. return lastNode;
  1348. };
  1349. /**
  1350. * Traverses nodes and creates them
  1351. */
  1352. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1353. if (meshIncluded === void 0) { meshIncluded = false; }
  1354. var node = gltfRuntime.nodes[id];
  1355. var newNode = null;
  1356. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  1357. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1358. meshIncluded = true;
  1359. }
  1360. else {
  1361. meshIncluded = false;
  1362. }
  1363. }
  1364. else {
  1365. meshIncluded = true;
  1366. }
  1367. if (!node.jointName && meshIncluded) {
  1368. newNode = importNode(gltfRuntime, node, id, parent);
  1369. if (newNode !== null) {
  1370. newNode.id = id;
  1371. newNode.parent = parent;
  1372. }
  1373. }
  1374. if (node.children) {
  1375. for (var i = 0; i < node.children.length; i++) {
  1376. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1377. }
  1378. }
  1379. };
  1380. /**
  1381. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1382. */
  1383. var postLoad = function (gltfRuntime) {
  1384. // Nodes
  1385. var currentScene = gltfRuntime.currentScene;
  1386. if (currentScene) {
  1387. for (var i = 0; i < currentScene.nodes.length; i++) {
  1388. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1389. }
  1390. }
  1391. else {
  1392. for (var thing in gltfRuntime.scenes) {
  1393. currentScene = gltfRuntime.scenes[thing];
  1394. for (var i = 0; i < currentScene.nodes.length; i++) {
  1395. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1396. }
  1397. }
  1398. }
  1399. // Set animations
  1400. loadAnimations(gltfRuntime);
  1401. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1402. var skeleton = gltfRuntime.scene.skeletons[i];
  1403. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1404. }
  1405. };
  1406. /**
  1407. * onBind shaderrs callback to set uniforms and matrices
  1408. */
  1409. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1410. var materialValues = material.values || technique.parameters;
  1411. for (var unif in unTreatedUniforms) {
  1412. var uniform = unTreatedUniforms[unif];
  1413. var type = uniform.type;
  1414. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  1415. if (uniform.semantic && !uniform.source && !uniform.node) {
  1416. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1417. }
  1418. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1419. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  1420. if (source === null) {
  1421. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  1422. }
  1423. if (source === null) {
  1424. continue;
  1425. }
  1426. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1427. }
  1428. }
  1429. else {
  1430. var value = materialValues[technique.uniforms[unif]];
  1431. if (!value) {
  1432. continue;
  1433. }
  1434. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1435. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1436. if (texture === null || texture === undefined) {
  1437. continue;
  1438. }
  1439. shaderMaterial.getEffect().setTexture(unif, texture);
  1440. }
  1441. else {
  1442. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  1443. }
  1444. }
  1445. }
  1446. onSuccess(shaderMaterial);
  1447. };
  1448. /**
  1449. * Prepare uniforms to send the only one time
  1450. * Loads the appropriate textures
  1451. */
  1452. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1453. var materialValues = material.values || technique.parameters;
  1454. var techniqueUniforms = technique.uniforms;
  1455. /**
  1456. * Prepare values here (not matrices)
  1457. */
  1458. for (var unif in unTreatedUniforms) {
  1459. var uniform = unTreatedUniforms[unif];
  1460. var type = uniform.type;
  1461. var value = materialValues[techniqueUniforms[unif]];
  1462. if (value === undefined) {
  1463. // In case the value is the same for all materials
  1464. value = uniform.value;
  1465. }
  1466. if (!value) {
  1467. continue;
  1468. }
  1469. var onLoadTexture = function (uniformName) {
  1470. return function (texture) {
  1471. if (uniform.value && uniformName) {
  1472. // Static uniform
  1473. shaderMaterial.setTexture(uniformName, texture);
  1474. delete unTreatedUniforms[uniformName];
  1475. }
  1476. };
  1477. };
  1478. // Texture (sampler2D)
  1479. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1480. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1481. }
  1482. else {
  1483. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1484. // Static uniform
  1485. delete unTreatedUniforms[unif];
  1486. }
  1487. }
  1488. }
  1489. };
  1490. /**
  1491. * Shader compilation failed
  1492. */
  1493. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1494. return function (effect, error) {
  1495. shaderMaterial.dispose(true);
  1496. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1497. };
  1498. };
  1499. /**
  1500. * Shader compilation success
  1501. */
  1502. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1503. return function (_) {
  1504. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1505. shaderMaterial.onBind = function (mesh) {
  1506. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1507. };
  1508. };
  1509. };
  1510. /**
  1511. * Returns the appropriate uniform if already handled by babylon
  1512. */
  1513. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1514. for (var unif in technique.uniforms) {
  1515. var uniform = technique.uniforms[unif];
  1516. var uniformParameter = technique.parameters[uniform];
  1517. if (tokenizer.currentIdentifier === unif) {
  1518. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1519. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1520. if (transformIndex !== -1) {
  1521. delete unTreatedUniforms[unif];
  1522. return babylonTransforms[transformIndex];
  1523. }
  1524. }
  1525. }
  1526. }
  1527. return tokenizer.currentIdentifier;
  1528. };
  1529. /**
  1530. * All shaders loaded. Create materials one by one
  1531. */
  1532. var importMaterials = function (gltfRuntime) {
  1533. // Create materials
  1534. for (var mat in gltfRuntime.materials) {
  1535. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1536. }
  1537. };
  1538. /**
  1539. * Implementation of the base glTF spec
  1540. */
  1541. var GLTFLoaderBase = /** @class */ (function () {
  1542. function GLTFLoaderBase() {
  1543. }
  1544. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1545. var gltfRuntime = {
  1546. extensions: {},
  1547. accessors: {},
  1548. buffers: {},
  1549. bufferViews: {},
  1550. meshes: {},
  1551. lights: {},
  1552. cameras: {},
  1553. nodes: {},
  1554. images: {},
  1555. textures: {},
  1556. shaders: {},
  1557. programs: {},
  1558. samplers: {},
  1559. techniques: {},
  1560. materials: {},
  1561. animations: {},
  1562. skins: {},
  1563. extensionsUsed: [],
  1564. scenes: {},
  1565. buffersCount: 0,
  1566. shaderscount: 0,
  1567. scene: scene,
  1568. rootUrl: rootUrl,
  1569. loadedBufferCount: 0,
  1570. loadedBufferViews: {},
  1571. loadedShaderCount: 0,
  1572. importOnlyMeshes: false,
  1573. dummyNodes: []
  1574. };
  1575. // Parse
  1576. if (parsedData.extensions) {
  1577. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1578. }
  1579. if (parsedData.extensionsUsed) {
  1580. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1581. }
  1582. if (parsedData.buffers) {
  1583. parseBuffers(parsedData.buffers, gltfRuntime);
  1584. }
  1585. if (parsedData.bufferViews) {
  1586. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1587. }
  1588. if (parsedData.accessors) {
  1589. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1590. }
  1591. if (parsedData.meshes) {
  1592. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1593. }
  1594. if (parsedData.lights) {
  1595. parseObject(parsedData.lights, "lights", gltfRuntime);
  1596. }
  1597. if (parsedData.cameras) {
  1598. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1599. }
  1600. if (parsedData.nodes) {
  1601. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1602. }
  1603. if (parsedData.images) {
  1604. parseObject(parsedData.images, "images", gltfRuntime);
  1605. }
  1606. if (parsedData.textures) {
  1607. parseObject(parsedData.textures, "textures", gltfRuntime);
  1608. }
  1609. if (parsedData.shaders) {
  1610. parseShaders(parsedData.shaders, gltfRuntime);
  1611. }
  1612. if (parsedData.programs) {
  1613. parseObject(parsedData.programs, "programs", gltfRuntime);
  1614. }
  1615. if (parsedData.samplers) {
  1616. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1617. }
  1618. if (parsedData.techniques) {
  1619. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1620. }
  1621. if (parsedData.materials) {
  1622. parseObject(parsedData.materials, "materials", gltfRuntime);
  1623. }
  1624. if (parsedData.animations) {
  1625. parseObject(parsedData.animations, "animations", gltfRuntime);
  1626. }
  1627. if (parsedData.skins) {
  1628. parseObject(parsedData.skins, "skins", gltfRuntime);
  1629. }
  1630. if (parsedData.scenes) {
  1631. gltfRuntime.scenes = parsedData.scenes;
  1632. }
  1633. if (parsedData.scene && parsedData.scenes) {
  1634. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1635. }
  1636. return gltfRuntime;
  1637. };
  1638. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1639. var buffer = gltfRuntime.buffers[id];
  1640. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  1641. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  1642. }
  1643. else {
  1644. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  1645. if (request) {
  1646. onError(request.status + " " + request.statusText);
  1647. }
  1648. });
  1649. }
  1650. };
  1651. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1652. var texture = gltfRuntime.textures[id];
  1653. if (!texture || !texture.source) {
  1654. onError("");
  1655. return;
  1656. }
  1657. if (texture.babylonTexture) {
  1658. onSuccess(null);
  1659. return;
  1660. }
  1661. var source = gltfRuntime.images[texture.source];
  1662. if (BABYLON.Tools.IsBase64(source.uri)) {
  1663. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  1664. }
  1665. else {
  1666. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  1667. if (request) {
  1668. onError(request.status + " " + request.statusText);
  1669. }
  1670. });
  1671. }
  1672. };
  1673. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1674. var texture = gltfRuntime.textures[id];
  1675. if (texture.babylonTexture) {
  1676. onSuccess(texture.babylonTexture);
  1677. return;
  1678. }
  1679. var sampler = gltfRuntime.samplers[texture.sampler];
  1680. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1681. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1682. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1683. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1684. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1685. var blob = new Blob([buffer]);
  1686. var blobURL = URL.createObjectURL(blob);
  1687. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1688. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1689. if (sampler.wrapS !== undefined) {
  1690. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1691. }
  1692. if (sampler.wrapT !== undefined) {
  1693. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1694. }
  1695. newTexture.name = id;
  1696. texture.babylonTexture = newTexture;
  1697. onSuccess(newTexture);
  1698. };
  1699. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1700. var shader = gltfRuntime.shaders[id];
  1701. if (BABYLON.Tools.IsBase64(shader.uri)) {
  1702. var shaderString = atob(shader.uri.split(",")[1]);
  1703. if (onSuccess) {
  1704. onSuccess(shaderString);
  1705. }
  1706. }
  1707. else {
  1708. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  1709. if (request && onError) {
  1710. onError(request.status + " " + request.statusText);
  1711. }
  1712. });
  1713. }
  1714. };
  1715. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1716. var material = gltfRuntime.materials[id];
  1717. if (!material.technique) {
  1718. if (onError) {
  1719. onError("No technique found.");
  1720. }
  1721. return;
  1722. }
  1723. var technique = gltfRuntime.techniques[material.technique];
  1724. if (!technique) {
  1725. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1726. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1727. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1728. onSuccess(defaultMaterial);
  1729. return;
  1730. }
  1731. var program = gltfRuntime.programs[technique.program];
  1732. var states = technique.states;
  1733. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1734. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1735. var newVertexShader = "";
  1736. var newPixelShader = "";
  1737. var vertexTokenizer = new Tokenizer(vertexShader);
  1738. var pixelTokenizer = new Tokenizer(pixelShader);
  1739. var unTreatedUniforms = {};
  1740. var uniforms = [];
  1741. var attributes = [];
  1742. var samplers = [];
  1743. // Fill uniform, sampler2D and attributes
  1744. for (var unif in technique.uniforms) {
  1745. var uniform = technique.uniforms[unif];
  1746. var uniformParameter = technique.parameters[uniform];
  1747. unTreatedUniforms[unif] = uniformParameter;
  1748. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1749. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1750. if (transformIndex !== -1) {
  1751. uniforms.push(babylonTransforms[transformIndex]);
  1752. delete unTreatedUniforms[unif];
  1753. }
  1754. else {
  1755. uniforms.push(unif);
  1756. }
  1757. }
  1758. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  1759. samplers.push(unif);
  1760. }
  1761. else {
  1762. uniforms.push(unif);
  1763. }
  1764. }
  1765. for (var attr in technique.attributes) {
  1766. var attribute = technique.attributes[attr];
  1767. var attributeParameter = technique.parameters[attribute];
  1768. if (attributeParameter.semantic) {
  1769. attributes.push(getAttribute(attributeParameter));
  1770. }
  1771. }
  1772. // Configure vertex shader
  1773. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1774. var tokenType = vertexTokenizer.currentToken;
  1775. if (tokenType !== ETokenType.IDENTIFIER) {
  1776. newVertexShader += vertexTokenizer.currentString;
  1777. continue;
  1778. }
  1779. var foundAttribute = false;
  1780. for (var attr in technique.attributes) {
  1781. var attribute = technique.attributes[attr];
  1782. var attributeParameter = technique.parameters[attribute];
  1783. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1784. newVertexShader += getAttribute(attributeParameter);
  1785. foundAttribute = true;
  1786. break;
  1787. }
  1788. }
  1789. if (foundAttribute) {
  1790. continue;
  1791. }
  1792. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1793. }
  1794. // Configure pixel shader
  1795. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1796. var tokenType = pixelTokenizer.currentToken;
  1797. if (tokenType !== ETokenType.IDENTIFIER) {
  1798. newPixelShader += pixelTokenizer.currentString;
  1799. continue;
  1800. }
  1801. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1802. }
  1803. // Create shader material
  1804. var shaderPath = {
  1805. vertex: program.vertexShader + id,
  1806. fragment: program.fragmentShader + id
  1807. };
  1808. var options = {
  1809. attributes: attributes,
  1810. uniforms: uniforms,
  1811. samplers: samplers,
  1812. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1813. };
  1814. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1815. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1816. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1817. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1818. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1819. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1820. if (states && states.functions) {
  1821. var functions = states.functions;
  1822. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  1823. shaderMaterial.backFaceCulling = false;
  1824. }
  1825. var blendFunc = functions.blendFuncSeparate;
  1826. if (blendFunc) {
  1827. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1828. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1829. }
  1830. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1831. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1832. }
  1833. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1834. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1835. }
  1836. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1837. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1838. }
  1839. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1840. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1841. }
  1842. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1843. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1844. }
  1845. }
  1846. }
  1847. };
  1848. return GLTFLoaderBase;
  1849. }());
  1850. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  1851. /**
  1852. * glTF V1 Loader
  1853. */
  1854. var GLTFLoader = /** @class */ (function () {
  1855. function GLTFLoader() {
  1856. // #region Stubs for IGLTFLoader interface
  1857. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  1858. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  1859. this.compileMaterials = false;
  1860. this.useClipPlane = false;
  1861. this.compileShadowGenerators = false;
  1862. this.onDisposeObservable = new BABYLON.Observable();
  1863. this.onMeshLoadedObservable = new BABYLON.Observable();
  1864. this.onTextureLoadedObservable = new BABYLON.Observable();
  1865. this.onMaterialLoadedObservable = new BABYLON.Observable();
  1866. this.onCompleteObservable = new BABYLON.Observable();
  1867. this.onExtensionLoadedObservable = new BABYLON.Observable();
  1868. this.state = null;
  1869. }
  1870. GLTFLoader.RegisterExtension = function (extension) {
  1871. if (GLTFLoader.Extensions[extension.name]) {
  1872. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1873. return;
  1874. }
  1875. GLTFLoader.Extensions[extension.name] = extension;
  1876. };
  1877. GLTFLoader.prototype.dispose = function () { };
  1878. // #endregion
  1879. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  1880. var _this = this;
  1881. scene.useRightHandedSystem = true;
  1882. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1883. gltfRuntime.importOnlyMeshes = true;
  1884. if (meshesNames === "") {
  1885. gltfRuntime.importMeshesNames = [];
  1886. }
  1887. else if (typeof meshesNames === "string") {
  1888. gltfRuntime.importMeshesNames = [meshesNames];
  1889. }
  1890. else if (meshesNames && !(meshesNames instanceof Array)) {
  1891. gltfRuntime.importMeshesNames = [meshesNames];
  1892. }
  1893. else {
  1894. gltfRuntime.importMeshesNames = [];
  1895. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1896. }
  1897. // Create nodes
  1898. _this._createNodes(gltfRuntime);
  1899. var meshes = new Array();
  1900. var skeletons = new Array();
  1901. // Fill arrays of meshes and skeletons
  1902. for (var nde in gltfRuntime.nodes) {
  1903. var node = gltfRuntime.nodes[nde];
  1904. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1905. meshes.push(node.babylonNode);
  1906. }
  1907. }
  1908. for (var skl in gltfRuntime.skins) {
  1909. var skin = gltfRuntime.skins[skl];
  1910. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1911. skeletons.push(skin.babylonSkeleton);
  1912. }
  1913. }
  1914. // Load buffers, shaders, materials, etc.
  1915. _this._loadBuffersAsync(gltfRuntime, function () {
  1916. _this._loadShadersAsync(gltfRuntime, function () {
  1917. importMaterials(gltfRuntime);
  1918. postLoad(gltfRuntime);
  1919. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1920. onSuccess(meshes, skeletons);
  1921. }
  1922. });
  1923. }, onProgress);
  1924. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1925. onSuccess(meshes, skeletons);
  1926. }
  1927. }, onError);
  1928. return true;
  1929. };
  1930. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  1931. var _this = this;
  1932. return new Promise(function (resolve, reject) {
  1933. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  1934. resolve({
  1935. meshes: meshes,
  1936. particleSystems: [],
  1937. skeletons: skeletons,
  1938. animationGroups: []
  1939. });
  1940. }, onProgress, function (message) {
  1941. reject(new Error(message));
  1942. });
  1943. });
  1944. };
  1945. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  1946. var _this = this;
  1947. scene.useRightHandedSystem = true;
  1948. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1949. // Load runtime extensios
  1950. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1951. // Create nodes
  1952. _this._createNodes(gltfRuntime);
  1953. // Load buffers, shaders, materials, etc.
  1954. _this._loadBuffersAsync(gltfRuntime, function () {
  1955. _this._loadShadersAsync(gltfRuntime, function () {
  1956. importMaterials(gltfRuntime);
  1957. postLoad(gltfRuntime);
  1958. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  1959. onSuccess();
  1960. }
  1961. });
  1962. });
  1963. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  1964. onSuccess();
  1965. }
  1966. }, onError);
  1967. }, onError);
  1968. };
  1969. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  1970. var _this = this;
  1971. return new Promise(function (resolve, reject) {
  1972. _this._loadAsync(scene, data, rootUrl, function () {
  1973. resolve();
  1974. }, onProgress, function (message) {
  1975. reject(new Error(message));
  1976. });
  1977. });
  1978. };
  1979. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1980. var hasShaders = false;
  1981. var processShader = function (sha, shader) {
  1982. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1983. if (shaderString instanceof ArrayBuffer) {
  1984. return;
  1985. }
  1986. gltfRuntime.loadedShaderCount++;
  1987. if (shaderString) {
  1988. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1989. }
  1990. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1991. onload();
  1992. }
  1993. }, function () {
  1994. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1995. });
  1996. };
  1997. for (var sha in gltfRuntime.shaders) {
  1998. hasShaders = true;
  1999. var shader = gltfRuntime.shaders[sha];
  2000. if (shader) {
  2001. processShader.bind(this, sha, shader)();
  2002. }
  2003. else {
  2004. BABYLON.Tools.Error("No shader named: " + sha);
  2005. }
  2006. }
  2007. if (!hasShaders) {
  2008. onload();
  2009. }
  2010. };
  2011. ;
  2012. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  2013. var hasBuffers = false;
  2014. var processBuffer = function (buf, buffer) {
  2015. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  2016. gltfRuntime.loadedBufferCount++;
  2017. if (bufferView) {
  2018. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  2019. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  2020. }
  2021. gltfRuntime.loadedBufferViews[buf] = bufferView;
  2022. }
  2023. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  2024. onLoad();
  2025. }
  2026. }, function () {
  2027. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  2028. });
  2029. };
  2030. for (var buf in gltfRuntime.buffers) {
  2031. hasBuffers = true;
  2032. var buffer = gltfRuntime.buffers[buf];
  2033. if (buffer) {
  2034. processBuffer.bind(this, buf, buffer)();
  2035. }
  2036. else {
  2037. BABYLON.Tools.Error("No buffer named: " + buf);
  2038. }
  2039. }
  2040. if (!hasBuffers) {
  2041. onLoad();
  2042. }
  2043. };
  2044. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  2045. var currentScene = gltfRuntime.currentScene;
  2046. if (currentScene) {
  2047. // Only one scene even if multiple scenes are defined
  2048. for (var i = 0; i < currentScene.nodes.length; i++) {
  2049. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2050. }
  2051. }
  2052. else {
  2053. // Load all scenes
  2054. for (var thing in gltfRuntime.scenes) {
  2055. currentScene = gltfRuntime.scenes[thing];
  2056. for (var i = 0; i < currentScene.nodes.length; i++) {
  2057. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2058. }
  2059. }
  2060. }
  2061. };
  2062. GLTFLoader.Extensions = {};
  2063. return GLTFLoader;
  2064. }());
  2065. GLTF1.GLTFLoader = GLTFLoader;
  2066. ;
  2067. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  2068. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2069. })(BABYLON || (BABYLON = {}));
  2070. //# sourceMappingURL=babylon.glTFLoader.js.map
  2071. "use strict";
  2072. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2073. var BABYLON;
  2074. (function (BABYLON) {
  2075. var GLTF1;
  2076. (function (GLTF1) {
  2077. /**
  2078. * Utils functions for GLTF
  2079. */
  2080. var GLTFUtils = /** @class */ (function () {
  2081. function GLTFUtils() {
  2082. }
  2083. /**
  2084. * Sets the given "parameter" matrix
  2085. * @param scene: the {BABYLON.Scene} object
  2086. * @param source: the source node where to pick the matrix
  2087. * @param parameter: the GLTF technique parameter
  2088. * @param uniformName: the name of the shader's uniform
  2089. * @param shaderMaterial: the shader material
  2090. */
  2091. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  2092. var mat = null;
  2093. if (parameter.semantic === "MODEL") {
  2094. mat = source.getWorldMatrix();
  2095. }
  2096. else if (parameter.semantic === "PROJECTION") {
  2097. mat = scene.getProjectionMatrix();
  2098. }
  2099. else if (parameter.semantic === "VIEW") {
  2100. mat = scene.getViewMatrix();
  2101. }
  2102. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  2103. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  2104. }
  2105. else if (parameter.semantic === "MODELVIEW") {
  2106. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  2107. }
  2108. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  2109. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  2110. }
  2111. else if (parameter.semantic === "MODELINVERSE") {
  2112. mat = source.getWorldMatrix().invert();
  2113. }
  2114. else if (parameter.semantic === "VIEWINVERSE") {
  2115. mat = scene.getViewMatrix().invert();
  2116. }
  2117. else if (parameter.semantic === "PROJECTIONINVERSE") {
  2118. mat = scene.getProjectionMatrix().invert();
  2119. }
  2120. else if (parameter.semantic === "MODELVIEWINVERSE") {
  2121. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  2122. }
  2123. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  2124. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  2125. }
  2126. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  2127. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  2128. }
  2129. else {
  2130. debugger;
  2131. }
  2132. if (mat) {
  2133. switch (parameter.type) {
  2134. case GLTF1.EParameterType.FLOAT_MAT2:
  2135. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  2136. break;
  2137. case GLTF1.EParameterType.FLOAT_MAT3:
  2138. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  2139. break;
  2140. case GLTF1.EParameterType.FLOAT_MAT4:
  2141. shaderMaterial.setMatrix(uniformName, mat);
  2142. break;
  2143. default: break;
  2144. }
  2145. }
  2146. };
  2147. /**
  2148. * Sets the given "parameter" matrix
  2149. * @param shaderMaterial: the shader material
  2150. * @param uniform: the name of the shader's uniform
  2151. * @param value: the value of the uniform
  2152. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  2153. */
  2154. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  2155. switch (type) {
  2156. case GLTF1.EParameterType.FLOAT:
  2157. shaderMaterial.setFloat(uniform, value);
  2158. return true;
  2159. case GLTF1.EParameterType.FLOAT_VEC2:
  2160. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  2161. return true;
  2162. case GLTF1.EParameterType.FLOAT_VEC3:
  2163. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  2164. return true;
  2165. case GLTF1.EParameterType.FLOAT_VEC4:
  2166. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  2167. return true;
  2168. default: return false;
  2169. }
  2170. };
  2171. /**
  2172. * Returns the wrap mode of the texture
  2173. * @param mode: the mode value
  2174. */
  2175. GLTFUtils.GetWrapMode = function (mode) {
  2176. switch (mode) {
  2177. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2178. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2179. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2180. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2181. }
  2182. };
  2183. /**
  2184. * Returns the byte stride giving an accessor
  2185. * @param accessor: the GLTF accessor objet
  2186. */
  2187. GLTFUtils.GetByteStrideFromType = function (accessor) {
  2188. // Needs this function since "byteStride" isn't requiered in glTF format
  2189. var type = accessor.type;
  2190. switch (type) {
  2191. case "VEC2": return 2;
  2192. case "VEC3": return 3;
  2193. case "VEC4": return 4;
  2194. case "MAT2": return 4;
  2195. case "MAT3": return 9;
  2196. case "MAT4": return 16;
  2197. default: return 1;
  2198. }
  2199. };
  2200. /**
  2201. * Returns the texture filter mode giving a mode value
  2202. * @param mode: the filter mode value
  2203. */
  2204. GLTFUtils.GetTextureFilterMode = function (mode) {
  2205. switch (mode) {
  2206. case GLTF1.ETextureFilterType.LINEAR:
  2207. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  2208. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  2209. case GLTF1.ETextureFilterType.NEAREST:
  2210. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  2211. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2212. }
  2213. };
  2214. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  2215. var byteOffset = bufferView.byteOffset + byteOffset;
  2216. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  2217. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  2218. throw new Error("Buffer access is out of range");
  2219. }
  2220. var buffer = loadedBufferView.buffer;
  2221. byteOffset += loadedBufferView.byteOffset;
  2222. switch (componentType) {
  2223. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  2224. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  2225. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  2226. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  2227. default: return new Float32Array(buffer, byteOffset, byteLength);
  2228. }
  2229. };
  2230. /**
  2231. * Returns a buffer from its accessor
  2232. * @param gltfRuntime: the GLTF runtime
  2233. * @param accessor: the GLTF accessor
  2234. */
  2235. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  2236. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  2237. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  2238. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  2239. };
  2240. /**
  2241. * Decodes a buffer view into a string
  2242. * @param view: the buffer view
  2243. */
  2244. GLTFUtils.DecodeBufferToText = function (view) {
  2245. var result = "";
  2246. var length = view.byteLength;
  2247. for (var i = 0; i < length; ++i) {
  2248. result += String.fromCharCode(view[i]);
  2249. }
  2250. return result;
  2251. };
  2252. /**
  2253. * Returns the default material of gltf. Related to
  2254. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  2255. * @param scene: the Babylon.js scene
  2256. */
  2257. GLTFUtils.GetDefaultMaterial = function (scene) {
  2258. if (!GLTFUtils._DefaultMaterial) {
  2259. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2260. "precision highp float;",
  2261. "",
  2262. "uniform mat4 worldView;",
  2263. "uniform mat4 projection;",
  2264. "",
  2265. "attribute vec3 position;",
  2266. "",
  2267. "void main(void)",
  2268. "{",
  2269. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2270. "}"
  2271. ].join("\n");
  2272. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2273. "precision highp float;",
  2274. "",
  2275. "uniform vec4 u_emission;",
  2276. "",
  2277. "void main(void)",
  2278. "{",
  2279. " gl_FragColor = u_emission;",
  2280. "}"
  2281. ].join("\n");
  2282. var shaderPath = {
  2283. vertex: "GLTFDefaultMaterial",
  2284. fragment: "GLTFDefaultMaterial"
  2285. };
  2286. var options = {
  2287. attributes: ["position"],
  2288. uniforms: ["worldView", "projection", "u_emission"],
  2289. samplers: new Array(),
  2290. needAlphaBlending: false
  2291. };
  2292. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2293. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  2294. }
  2295. return GLTFUtils._DefaultMaterial;
  2296. };
  2297. // The GLTF default material
  2298. GLTFUtils._DefaultMaterial = null;
  2299. return GLTFUtils;
  2300. }());
  2301. GLTF1.GLTFUtils = GLTFUtils;
  2302. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2303. })(BABYLON || (BABYLON = {}));
  2304. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2305. "use strict";
  2306. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2307. var BABYLON;
  2308. (function (BABYLON) {
  2309. var GLTF1;
  2310. (function (GLTF1) {
  2311. var GLTFLoaderExtension = /** @class */ (function () {
  2312. function GLTFLoaderExtension(name) {
  2313. this._name = name;
  2314. }
  2315. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2316. get: function () {
  2317. return this._name;
  2318. },
  2319. enumerable: true,
  2320. configurable: true
  2321. });
  2322. /**
  2323. * Defines an override for loading the runtime
  2324. * Return true to stop further extensions from loading the runtime
  2325. */
  2326. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2327. return false;
  2328. };
  2329. /**
  2330. * Defines an onverride for creating gltf runtime
  2331. * Return true to stop further extensions from creating the runtime
  2332. */
  2333. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2334. return false;
  2335. };
  2336. /**
  2337. * Defines an override for loading buffers
  2338. * Return true to stop further extensions from loading this buffer
  2339. */
  2340. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2341. return false;
  2342. };
  2343. /**
  2344. * Defines an override for loading texture buffers
  2345. * Return true to stop further extensions from loading this texture data
  2346. */
  2347. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2348. return false;
  2349. };
  2350. /**
  2351. * Defines an override for creating textures
  2352. * Return true to stop further extensions from loading this texture
  2353. */
  2354. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2355. return false;
  2356. };
  2357. /**
  2358. * Defines an override for loading shader strings
  2359. * Return true to stop further extensions from loading this shader data
  2360. */
  2361. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2362. return false;
  2363. };
  2364. /**
  2365. * Defines an override for loading materials
  2366. * Return true to stop further extensions from loading this material
  2367. */
  2368. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2369. return false;
  2370. };
  2371. // ---------
  2372. // Utilities
  2373. // ---------
  2374. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2375. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2376. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  2377. }, function () {
  2378. setTimeout(function () {
  2379. if (!onSuccess) {
  2380. return;
  2381. }
  2382. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2383. });
  2384. });
  2385. };
  2386. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2387. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2388. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  2389. }, function () {
  2390. setTimeout(function () {
  2391. onSuccess();
  2392. });
  2393. });
  2394. };
  2395. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2396. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2397. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2398. }, function () {
  2399. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2400. });
  2401. };
  2402. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  2403. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2404. if (buffer) {
  2405. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2406. }
  2407. }, onError);
  2408. };
  2409. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2410. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2411. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2412. }, function () {
  2413. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2414. });
  2415. };
  2416. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2417. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2418. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2419. }, function () {
  2420. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2421. });
  2422. };
  2423. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2424. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2425. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2426. }, function () {
  2427. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2428. });
  2429. };
  2430. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2431. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2432. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2433. }, function () {
  2434. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2435. });
  2436. };
  2437. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  2438. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  2439. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  2440. if (func(loaderExtension)) {
  2441. return;
  2442. }
  2443. }
  2444. defaultFunc();
  2445. };
  2446. return GLTFLoaderExtension;
  2447. }());
  2448. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  2449. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2450. })(BABYLON || (BABYLON = {}));
  2451. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2452. "use strict";
  2453. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2454. var __extends = (this && this.__extends) || (function () {
  2455. var extendStatics = Object.setPrototypeOf ||
  2456. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2457. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2458. return function (d, b) {
  2459. extendStatics(d, b);
  2460. function __() { this.constructor = d; }
  2461. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2462. };
  2463. })();
  2464. var BABYLON;
  2465. (function (BABYLON) {
  2466. var GLTF1;
  2467. (function (GLTF1) {
  2468. var BinaryExtensionBufferName = "binary_glTF";
  2469. ;
  2470. ;
  2471. var GLTFBinaryExtension = /** @class */ (function (_super) {
  2472. __extends(GLTFBinaryExtension, _super);
  2473. function GLTFBinaryExtension() {
  2474. return _super.call(this, "KHR_binary_glTF") || this;
  2475. }
  2476. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2477. var extensionsUsed = data.json.extensionsUsed;
  2478. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  2479. return false;
  2480. }
  2481. this._bin = data.bin;
  2482. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2483. return true;
  2484. };
  2485. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2486. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  2487. return false;
  2488. }
  2489. if (id !== BinaryExtensionBufferName) {
  2490. return false;
  2491. }
  2492. onSuccess(this._bin);
  2493. return true;
  2494. };
  2495. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2496. var texture = gltfRuntime.textures[id];
  2497. var source = gltfRuntime.images[texture.source];
  2498. if (!source.extensions || !(this.name in source.extensions)) {
  2499. return false;
  2500. }
  2501. var sourceExt = source.extensions[this.name];
  2502. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  2503. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2504. onSuccess(buffer);
  2505. return true;
  2506. };
  2507. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2508. var shader = gltfRuntime.shaders[id];
  2509. if (!shader.extensions || !(this.name in shader.extensions)) {
  2510. return false;
  2511. }
  2512. var binaryExtensionShader = shader.extensions[this.name];
  2513. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  2514. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2515. setTimeout(function () {
  2516. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  2517. onSuccess(shaderString);
  2518. });
  2519. return true;
  2520. };
  2521. return GLTFBinaryExtension;
  2522. }(GLTF1.GLTFLoaderExtension));
  2523. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  2524. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  2525. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2526. })(BABYLON || (BABYLON = {}));
  2527. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2528. "use strict";
  2529. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2530. var __extends = (this && this.__extends) || (function () {
  2531. var extendStatics = Object.setPrototypeOf ||
  2532. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2533. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2534. return function (d, b) {
  2535. extendStatics(d, b);
  2536. function __() { this.constructor = d; }
  2537. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2538. };
  2539. })();
  2540. var BABYLON;
  2541. (function (BABYLON) {
  2542. var GLTF1;
  2543. (function (GLTF1) {
  2544. ;
  2545. ;
  2546. ;
  2547. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  2548. __extends(GLTFMaterialsCommonExtension, _super);
  2549. function GLTFMaterialsCommonExtension() {
  2550. return _super.call(this, "KHR_materials_common") || this;
  2551. }
  2552. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2553. if (!gltfRuntime.extensions)
  2554. return false;
  2555. var extension = gltfRuntime.extensions[this.name];
  2556. if (!extension)
  2557. return false;
  2558. // Create lights
  2559. var lights = extension.lights;
  2560. if (lights) {
  2561. for (var thing in lights) {
  2562. var light = lights[thing];
  2563. switch (light.type) {
  2564. case "ambient":
  2565. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  2566. var ambient = light.ambient;
  2567. if (ambient) {
  2568. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  2569. }
  2570. break;
  2571. case "point":
  2572. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  2573. var point = light.point;
  2574. if (point) {
  2575. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  2576. }
  2577. break;
  2578. case "directional":
  2579. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  2580. var directional = light.directional;
  2581. if (directional) {
  2582. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  2583. }
  2584. break;
  2585. case "spot":
  2586. var spot = light.spot;
  2587. if (spot) {
  2588. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  2589. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  2590. }
  2591. break;
  2592. default:
  2593. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2594. break;
  2595. }
  2596. }
  2597. }
  2598. return false;
  2599. };
  2600. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2601. var material = gltfRuntime.materials[id];
  2602. if (!material || !material.extensions)
  2603. return false;
  2604. var extension = material.extensions[this.name];
  2605. if (!extension)
  2606. return false;
  2607. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2608. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2609. if (extension.technique === "CONSTANT") {
  2610. standardMaterial.disableLighting = true;
  2611. }
  2612. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2613. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2614. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2615. // Ambient
  2616. if (typeof extension.values.ambient === "string") {
  2617. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2618. }
  2619. else {
  2620. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2621. }
  2622. // Diffuse
  2623. if (typeof extension.values.diffuse === "string") {
  2624. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2625. }
  2626. else {
  2627. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2628. }
  2629. // Emission
  2630. if (typeof extension.values.emission === "string") {
  2631. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2632. }
  2633. else {
  2634. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2635. }
  2636. // Specular
  2637. if (typeof extension.values.specular === "string") {
  2638. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2639. }
  2640. else {
  2641. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2642. }
  2643. return true;
  2644. };
  2645. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2646. // Create buffer from texture url
  2647. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2648. // Create texture from buffer
  2649. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2650. }, onError);
  2651. };
  2652. return GLTFMaterialsCommonExtension;
  2653. }(GLTF1.GLTFLoaderExtension));
  2654. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2655. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2656. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2657. })(BABYLON || (BABYLON = {}));
  2658. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  2659. "use strict";
  2660. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2661. var BABYLON;
  2662. (function (BABYLON) {
  2663. var GLTF2;
  2664. (function (GLTF2) {
  2665. var ArrayItem = /** @class */ (function () {
  2666. function ArrayItem() {
  2667. }
  2668. ArrayItem.Assign = function (values) {
  2669. if (values) {
  2670. for (var index = 0; index < values.length; index++) {
  2671. values[index]._index = index;
  2672. }
  2673. }
  2674. };
  2675. return ArrayItem;
  2676. }());
  2677. GLTF2.ArrayItem = ArrayItem;
  2678. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2679. })(BABYLON || (BABYLON = {}));
  2680. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  2681. "use strict";
  2682. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2683. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  2684. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  2685. "use strict";
  2686. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2687. var BABYLON;
  2688. (function (BABYLON) {
  2689. var GLTF2;
  2690. (function (GLTF2) {
  2691. var GLTFLoader = /** @class */ (function () {
  2692. function GLTFLoader() {
  2693. this._completePromises = new Array();
  2694. this._disposed = false;
  2695. this._state = null;
  2696. this._extensions = {};
  2697. this._defaultSampler = {};
  2698. this._defaultBabylonMaterials = {};
  2699. this._requests = new Array();
  2700. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  2701. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  2702. this.compileMaterials = false;
  2703. this.useClipPlane = false;
  2704. this.compileShadowGenerators = false;
  2705. this.onDisposeObservable = new BABYLON.Observable();
  2706. this.onMeshLoadedObservable = new BABYLON.Observable();
  2707. this.onTextureLoadedObservable = new BABYLON.Observable();
  2708. this.onMaterialLoadedObservable = new BABYLON.Observable();
  2709. this.onExtensionLoadedObservable = new BABYLON.Observable();
  2710. this.onCompleteObservable = new BABYLON.Observable();
  2711. }
  2712. GLTFLoader._Register = function (name, factory) {
  2713. if (GLTFLoader._Factories[name]) {
  2714. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  2715. return;
  2716. }
  2717. GLTFLoader._Factories[name] = factory;
  2718. // Keep the order of registration so that extensions registered first are called first.
  2719. GLTFLoader._Names.push(name);
  2720. };
  2721. Object.defineProperty(GLTFLoader.prototype, "state", {
  2722. get: function () {
  2723. return this._state;
  2724. },
  2725. enumerable: true,
  2726. configurable: true
  2727. });
  2728. GLTFLoader.prototype.dispose = function () {
  2729. if (this._disposed) {
  2730. return;
  2731. }
  2732. this._disposed = true;
  2733. this.onDisposeObservable.notifyObservers(this);
  2734. this.onDisposeObservable.clear();
  2735. this._clear();
  2736. };
  2737. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  2738. var _this = this;
  2739. return Promise.resolve().then(function () {
  2740. var nodes = null;
  2741. if (meshesNames) {
  2742. var nodeMap_1 = {};
  2743. if (_this._gltf.nodes) {
  2744. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  2745. var node = _a[_i];
  2746. if (node.name) {
  2747. nodeMap_1[node.name] = node;
  2748. }
  2749. }
  2750. }
  2751. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  2752. nodes = names.map(function (name) {
  2753. var node = nodeMap_1[name];
  2754. if (!node) {
  2755. throw new Error("Failed to find node '" + name + "'");
  2756. }
  2757. return node;
  2758. });
  2759. }
  2760. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  2761. return {
  2762. meshes: _this._getMeshes(),
  2763. particleSystems: [],
  2764. skeletons: _this._getSkeletons(),
  2765. animationGroups: _this._getAnimationGroups()
  2766. };
  2767. });
  2768. });
  2769. };
  2770. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  2771. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  2772. };
  2773. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  2774. var _this = this;
  2775. return Promise.resolve().then(function () {
  2776. _this._loadExtensions();
  2777. _this._babylonScene = scene;
  2778. _this._rootUrl = rootUrl;
  2779. _this._progressCallback = onProgress;
  2780. _this._state = BABYLON.GLTFLoaderState.LOADING;
  2781. _this._loadData(data);
  2782. _this._checkExtensions();
  2783. var promises = new Array();
  2784. if (nodes) {
  2785. promises.push(_this._loadNodesAsync(nodes));
  2786. }
  2787. else {
  2788. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  2789. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  2790. }
  2791. if (_this.compileMaterials) {
  2792. promises.push(_this._compileMaterialsAsync());
  2793. }
  2794. if (_this.compileShadowGenerators) {
  2795. promises.push(_this._compileShadowGeneratorsAsync());
  2796. }
  2797. var resultPromise = Promise.all(promises).then(function () {
  2798. _this._state = BABYLON.GLTFLoaderState.READY;
  2799. _this._startAnimations();
  2800. });
  2801. resultPromise.then(function () {
  2802. _this._rootBabylonMesh.setEnabled(true);
  2803. BABYLON.Tools.SetImmediate(function () {
  2804. if (!_this._disposed) {
  2805. Promise.all(_this._completePromises).then(function () {
  2806. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  2807. _this.onCompleteObservable.notifyObservers(_this);
  2808. _this.onCompleteObservable.clear();
  2809. _this._clear();
  2810. }).catch(function (error) {
  2811. BABYLON.Tools.Error("glTF Loader: " + error.message);
  2812. _this._clear();
  2813. });
  2814. }
  2815. });
  2816. });
  2817. return resultPromise;
  2818. }).catch(function (error) {
  2819. BABYLON.Tools.Error("glTF Loader: " + error.message);
  2820. _this._clear();
  2821. throw error;
  2822. });
  2823. };
  2824. GLTFLoader.prototype._loadExtensions = function () {
  2825. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  2826. var name_1 = _a[_i];
  2827. var extension = GLTFLoader._Factories[name_1](this);
  2828. this._extensions[name_1] = extension;
  2829. this.onExtensionLoadedObservable.notifyObservers(extension);
  2830. }
  2831. this.onExtensionLoadedObservable.clear();
  2832. };
  2833. GLTFLoader.prototype._loadData = function (data) {
  2834. this._gltf = data.json;
  2835. this._setupData();
  2836. if (data.bin) {
  2837. var buffers = this._gltf.buffers;
  2838. if (buffers && buffers[0] && !buffers[0].uri) {
  2839. var binaryBuffer = buffers[0];
  2840. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  2841. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  2842. }
  2843. binaryBuffer._data = Promise.resolve(data.bin);
  2844. }
  2845. else {
  2846. BABYLON.Tools.Warn("Unexpected BIN chunk");
  2847. }
  2848. }
  2849. };
  2850. GLTFLoader.prototype._setupData = function () {
  2851. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  2852. GLTF2.ArrayItem.Assign(this._gltf.animations);
  2853. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  2854. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  2855. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  2856. GLTF2.ArrayItem.Assign(this._gltf.images);
  2857. GLTF2.ArrayItem.Assign(this._gltf.materials);
  2858. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  2859. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  2860. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  2861. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  2862. GLTF2.ArrayItem.Assign(this._gltf.skins);
  2863. GLTF2.ArrayItem.Assign(this._gltf.textures);
  2864. if (this._gltf.nodes) {
  2865. var nodeParents = {};
  2866. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  2867. var node = _a[_i];
  2868. if (node.children) {
  2869. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  2870. var index = _c[_b];
  2871. nodeParents[index] = node._index;
  2872. }
  2873. }
  2874. }
  2875. var rootNode = this._createRootNode();
  2876. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  2877. var node = _e[_d];
  2878. var parentIndex = nodeParents[node._index];
  2879. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  2880. }
  2881. }
  2882. };
  2883. GLTFLoader.prototype._checkExtensions = function () {
  2884. if (this._gltf.extensionsRequired) {
  2885. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  2886. var name_2 = _a[_i];
  2887. var extension = this._extensions[name_2];
  2888. if (!extension || !extension.enabled) {
  2889. throw new Error("Require extension " + name_2 + " is not available");
  2890. }
  2891. }
  2892. }
  2893. };
  2894. GLTFLoader.prototype._createRootNode = function () {
  2895. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  2896. this._rootBabylonMesh.setEnabled(false);
  2897. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  2898. switch (this.coordinateSystemMode) {
  2899. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  2900. if (!this._babylonScene.useRightHandedSystem) {
  2901. rootNode.rotation = [0, 1, 0, 0];
  2902. rootNode.scale = [1, 1, -1];
  2903. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  2904. }
  2905. break;
  2906. }
  2907. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  2908. this._babylonScene.useRightHandedSystem = true;
  2909. break;
  2910. }
  2911. default: {
  2912. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  2913. }
  2914. }
  2915. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  2916. return rootNode;
  2917. };
  2918. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  2919. var promises = new Array();
  2920. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  2921. var node = nodes_1[_i];
  2922. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  2923. }
  2924. promises.push(this._loadAnimationsAsync());
  2925. return Promise.all(promises).then(function () { });
  2926. };
  2927. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  2928. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  2929. if (promise) {
  2930. return promise;
  2931. }
  2932. var promises = new Array();
  2933. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  2934. var index = _a[_i];
  2935. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  2936. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  2937. }
  2938. promises.push(this._loadAnimationsAsync());
  2939. return Promise.all(promises).then(function () { });
  2940. };
  2941. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  2942. if (node._primitiveBabylonMeshes) {
  2943. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  2944. var babylonMesh = _a[_i];
  2945. callback(babylonMesh);
  2946. }
  2947. }
  2948. else {
  2949. callback(node._babylonMesh);
  2950. }
  2951. };
  2952. GLTFLoader.prototype._getMeshes = function () {
  2953. var meshes = new Array();
  2954. // Root mesh is always first.
  2955. meshes.push(this._rootBabylonMesh);
  2956. var nodes = this._gltf.nodes;
  2957. if (nodes) {
  2958. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  2959. var node = nodes_2[_i];
  2960. if (node._babylonMesh) {
  2961. meshes.push(node._babylonMesh);
  2962. }
  2963. if (node._primitiveBabylonMeshes) {
  2964. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  2965. var babylonMesh = _b[_a];
  2966. meshes.push(babylonMesh);
  2967. }
  2968. }
  2969. }
  2970. }
  2971. return meshes;
  2972. };
  2973. GLTFLoader.prototype._getSkeletons = function () {
  2974. var skeletons = new Array();
  2975. var skins = this._gltf.skins;
  2976. if (skins) {
  2977. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  2978. var skin = skins_1[_i];
  2979. if (skin._babylonSkeleton) {
  2980. skeletons.push(skin._babylonSkeleton);
  2981. }
  2982. }
  2983. }
  2984. return skeletons;
  2985. };
  2986. GLTFLoader.prototype._getAnimationGroups = function () {
  2987. var animationGroups = new Array();
  2988. var animations = this._gltf.animations;
  2989. if (animations) {
  2990. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  2991. var animation = animations_1[_i];
  2992. if (animation._babylonAnimationGroup) {
  2993. animationGroups.push(animation._babylonAnimationGroup);
  2994. }
  2995. }
  2996. }
  2997. return animationGroups;
  2998. };
  2999. GLTFLoader.prototype._startAnimations = function () {
  3000. switch (this.animationStartMode) {
  3001. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  3002. // do nothing
  3003. break;
  3004. }
  3005. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  3006. var babylonAnimationGroups = this._getAnimationGroups();
  3007. if (babylonAnimationGroups.length !== 0) {
  3008. babylonAnimationGroups[0].start(true);
  3009. }
  3010. break;
  3011. }
  3012. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  3013. var babylonAnimationGroups = this._getAnimationGroups();
  3014. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  3015. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  3016. babylonAnimationGroup.start(true);
  3017. }
  3018. break;
  3019. }
  3020. default: {
  3021. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  3022. return;
  3023. }
  3024. }
  3025. };
  3026. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  3027. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  3028. if (promise) {
  3029. return promise;
  3030. }
  3031. if (node._babylonMesh) {
  3032. throw new Error(context + ": Invalid recursive node hierarchy");
  3033. }
  3034. var promises = new Array();
  3035. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  3036. node._babylonMesh = babylonMesh;
  3037. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  3038. node._babylonAnimationTargets.push(babylonMesh);
  3039. GLTFLoader._LoadTransform(node, babylonMesh);
  3040. if (node.mesh != undefined) {
  3041. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  3042. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  3043. }
  3044. if (node.children) {
  3045. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  3046. var index = _a[_i];
  3047. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  3048. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  3049. }
  3050. }
  3051. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  3052. return Promise.all(promises).then(function () { });
  3053. };
  3054. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  3055. // TODO: instancing
  3056. var _this = this;
  3057. var promises = new Array();
  3058. var primitives = mesh.primitives;
  3059. if (!primitives || primitives.length === 0) {
  3060. throw new Error(context + ": Primitives are missing");
  3061. }
  3062. GLTF2.ArrayItem.Assign(primitives);
  3063. if (primitives.length === 1) {
  3064. var primitive = primitives[0];
  3065. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  3066. }
  3067. else {
  3068. node._primitiveBabylonMeshes = [];
  3069. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  3070. var primitive = primitives_1[_i];
  3071. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  3072. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  3073. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  3074. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  3075. }
  3076. }
  3077. if (node.skin != undefined) {
  3078. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  3079. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  3080. }
  3081. return Promise.all(promises).then(function () {
  3082. _this._forEachPrimitive(node, function (babylonMesh) {
  3083. babylonMesh._refreshBoundingInfo(true);
  3084. });
  3085. });
  3086. };
  3087. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  3088. var _this = this;
  3089. var promises = new Array();
  3090. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  3091. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  3092. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  3093. babylonGeometry.applyToMesh(babylonMesh);
  3094. });
  3095. }));
  3096. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  3097. if (primitive.material == undefined) {
  3098. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  3099. }
  3100. else {
  3101. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  3102. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  3103. babylonMesh.material = babylonMaterial;
  3104. }));
  3105. }
  3106. return Promise.all(promises).then(function () { });
  3107. };
  3108. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  3109. var _this = this;
  3110. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  3111. if (promise) {
  3112. return promise;
  3113. }
  3114. var attributes = primitive.attributes;
  3115. if (!attributes) {
  3116. throw new Error(context + ": Attributes are missing");
  3117. }
  3118. var promises = new Array();
  3119. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  3120. if (primitive.indices == undefined) {
  3121. babylonMesh.isUnIndexed = true;
  3122. }
  3123. else {
  3124. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  3125. promises.push(this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3126. babylonGeometry.setIndices(data);
  3127. }));
  3128. }
  3129. var loadAttribute = function (attribute, kind, callback) {
  3130. if (attributes[attribute] == undefined) {
  3131. return;
  3132. }
  3133. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  3134. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  3135. babylonMesh._delayInfo.push(kind);
  3136. }
  3137. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  3138. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  3139. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  3140. }));
  3141. if (callback) {
  3142. callback(accessor);
  3143. }
  3144. };
  3145. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  3146. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  3147. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  3148. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  3149. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  3150. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  3151. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  3152. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  3153. if (accessor.type === "VEC4" /* VEC4 */) {
  3154. babylonMesh.hasVertexAlpha = true;
  3155. }
  3156. });
  3157. return Promise.all(promises).then(function () {
  3158. return babylonGeometry;
  3159. });
  3160. };
  3161. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  3162. if (!primitive.targets) {
  3163. return;
  3164. }
  3165. if (node._numMorphTargets == undefined) {
  3166. node._numMorphTargets = primitive.targets.length;
  3167. }
  3168. else if (primitive.targets.length !== node._numMorphTargets) {
  3169. throw new Error(context + ": Primitives do not have the same number of targets");
  3170. }
  3171. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  3172. for (var index = 0; index < primitive.targets.length; index++) {
  3173. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  3174. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  3175. // TODO: tell the target whether it has positions, normals, tangents
  3176. }
  3177. };
  3178. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  3179. if (!primitive.targets) {
  3180. return Promise.resolve();
  3181. }
  3182. var promises = new Array();
  3183. var morphTargetManager = babylonMesh.morphTargetManager;
  3184. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  3185. var babylonMorphTarget = morphTargetManager.getTarget(index);
  3186. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  3187. }
  3188. return Promise.all(promises).then(function () { });
  3189. };
  3190. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  3191. var _this = this;
  3192. var promises = new Array();
  3193. var loadAttribute = function (attribute, kind, setData) {
  3194. if (attributes[attribute] == undefined) {
  3195. return;
  3196. }
  3197. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  3198. if (!babylonVertexBuffer) {
  3199. return;
  3200. }
  3201. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  3202. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3203. if (!(data instanceof Float32Array)) {
  3204. throw new Error(context + ": Morph target accessor must have float data");
  3205. }
  3206. setData(babylonVertexBuffer, data);
  3207. }));
  3208. };
  3209. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  3210. babylonVertexBuffer.forEach(data.length, function (value, index) {
  3211. data[index] += value;
  3212. });
  3213. babylonMorphTarget.setPositions(data);
  3214. });
  3215. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  3216. babylonVertexBuffer.forEach(data.length, function (value, index) {
  3217. data[index] += value;
  3218. });
  3219. babylonMorphTarget.setNormals(data);
  3220. });
  3221. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  3222. var dataIndex = 0;
  3223. babylonVertexBuffer.forEach(data.length, function (value, index) {
  3224. // Tangent data for morph targets is stored as xyz delta.
  3225. // The vertexData.tangent is stored as xyzw.
  3226. // So we need to skip every fourth vertexData.tangent.
  3227. if (((index + 1) % 4) !== 0) {
  3228. data[dataIndex++] += value;
  3229. }
  3230. });
  3231. babylonMorphTarget.setTangents(data);
  3232. });
  3233. return Promise.all(promises).then(function () { });
  3234. };
  3235. GLTFLoader._LoadTransform = function (node, babylonNode) {
  3236. var position = BABYLON.Vector3.Zero();
  3237. var rotation = BABYLON.Quaternion.Identity();
  3238. var scaling = BABYLON.Vector3.One();
  3239. if (node.matrix) {
  3240. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  3241. matrix.decompose(scaling, rotation, position);
  3242. }
  3243. else {
  3244. if (node.translation)
  3245. position = BABYLON.Vector3.FromArray(node.translation);
  3246. if (node.rotation)
  3247. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  3248. if (node.scale)
  3249. scaling = BABYLON.Vector3.FromArray(node.scale);
  3250. }
  3251. babylonNode.position = position;
  3252. babylonNode.rotationQuaternion = rotation;
  3253. babylonNode.scaling = scaling;
  3254. };
  3255. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  3256. var _this = this;
  3257. var assignSkeleton = function () {
  3258. _this._forEachPrimitive(node, function (babylonMesh) {
  3259. babylonMesh.skeleton = skin._babylonSkeleton;
  3260. });
  3261. // Ignore the TRS of skinned nodes.
  3262. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  3263. node._babylonMesh.parent = _this._rootBabylonMesh;
  3264. node._babylonMesh.position = BABYLON.Vector3.Zero();
  3265. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  3266. node._babylonMesh.scaling = BABYLON.Vector3.One();
  3267. };
  3268. if (skin._loaded) {
  3269. return skin._loaded.then(function () {
  3270. assignSkeleton();
  3271. });
  3272. }
  3273. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  3274. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  3275. var skeletonId = "skeleton" + skin._index;
  3276. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  3277. skin._babylonSkeleton = babylonSkeleton;
  3278. _this._loadBones(context, skin, inverseBindMatricesData);
  3279. assignSkeleton();
  3280. }));
  3281. };
  3282. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  3283. if (skin.inverseBindMatrices == undefined) {
  3284. return Promise.resolve(null);
  3285. }
  3286. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  3287. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3288. return data;
  3289. });
  3290. };
  3291. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  3292. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  3293. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  3294. node._babylonAnimationTargets.push(babylonBone);
  3295. return babylonBone;
  3296. };
  3297. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  3298. var babylonBones = {};
  3299. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  3300. var index = _a[_i];
  3301. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  3302. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  3303. }
  3304. };
  3305. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  3306. var babylonBone = babylonBones[node._index];
  3307. if (babylonBone) {
  3308. return babylonBone;
  3309. }
  3310. var boneIndex = skin.joints.indexOf(node._index);
  3311. var baseMatrix = BABYLON.Matrix.Identity();
  3312. if (inverseBindMatricesData && boneIndex !== -1) {
  3313. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  3314. baseMatrix.invertToRef(baseMatrix);
  3315. }
  3316. var babylonParentBone = null;
  3317. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  3318. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  3319. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  3320. }
  3321. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  3322. babylonBones[node._index] = babylonBone;
  3323. return babylonBone;
  3324. };
  3325. GLTFLoader.prototype._getNodeMatrix = function (node) {
  3326. return node.matrix ?
  3327. BABYLON.Matrix.FromArray(node.matrix) :
  3328. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  3329. };
  3330. GLTFLoader.prototype._loadAnimationsAsync = function () {
  3331. var animations = this._gltf.animations;
  3332. if (!animations) {
  3333. return Promise.resolve();
  3334. }
  3335. var promises = new Array();
  3336. for (var index = 0; index < animations.length; index++) {
  3337. var animation = animations[index];
  3338. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  3339. }
  3340. return Promise.all(promises).then(function () { });
  3341. };
  3342. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  3343. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  3344. animation._babylonAnimationGroup = babylonAnimationGroup;
  3345. var promises = new Array();
  3346. GLTF2.ArrayItem.Assign(animation.channels);
  3347. GLTF2.ArrayItem.Assign(animation.samplers);
  3348. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  3349. var channel = _a[_i];
  3350. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  3351. }
  3352. return Promise.all(promises).then(function () {
  3353. babylonAnimationGroup.normalize();
  3354. });
  3355. };
  3356. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  3357. var _this = this;
  3358. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  3359. if (!targetNode._babylonMesh) {
  3360. return Promise.resolve();
  3361. }
  3362. // Ignore animations targeting TRS of skinned nodes.
  3363. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  3364. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  3365. return Promise.resolve();
  3366. }
  3367. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  3368. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  3369. var targetPath;
  3370. var animationType;
  3371. switch (channel.target.path) {
  3372. case "translation" /* TRANSLATION */: {
  3373. targetPath = "position";
  3374. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  3375. break;
  3376. }
  3377. case "rotation" /* ROTATION */: {
  3378. targetPath = "rotationQuaternion";
  3379. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  3380. break;
  3381. }
  3382. case "scale" /* SCALE */: {
  3383. targetPath = "scaling";
  3384. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  3385. break;
  3386. }
  3387. case "weights" /* WEIGHTS */: {
  3388. targetPath = "influence";
  3389. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  3390. break;
  3391. }
  3392. default: {
  3393. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  3394. }
  3395. }
  3396. var outputBufferOffset = 0;
  3397. var getNextOutputValue;
  3398. switch (targetPath) {
  3399. case "position": {
  3400. getNextOutputValue = function () {
  3401. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  3402. outputBufferOffset += 3;
  3403. return value;
  3404. };
  3405. break;
  3406. }
  3407. case "rotationQuaternion": {
  3408. getNextOutputValue = function () {
  3409. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  3410. outputBufferOffset += 4;
  3411. return value;
  3412. };
  3413. break;
  3414. }
  3415. case "scaling": {
  3416. getNextOutputValue = function () {
  3417. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  3418. outputBufferOffset += 3;
  3419. return value;
  3420. };
  3421. break;
  3422. }
  3423. case "influence": {
  3424. getNextOutputValue = function () {
  3425. var value = new Array(targetNode._numMorphTargets);
  3426. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  3427. value[i] = data.output[outputBufferOffset++];
  3428. }
  3429. return value;
  3430. };
  3431. break;
  3432. }
  3433. }
  3434. var getNextKey;
  3435. switch (data.interpolation) {
  3436. case "STEP" /* STEP */: {
  3437. getNextKey = function (frameIndex) { return ({
  3438. frame: data.input[frameIndex],
  3439. value: getNextOutputValue(),
  3440. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  3441. }); };
  3442. break;
  3443. }
  3444. case "LINEAR" /* LINEAR */: {
  3445. getNextKey = function (frameIndex) { return ({
  3446. frame: data.input[frameIndex],
  3447. value: getNextOutputValue()
  3448. }); };
  3449. break;
  3450. }
  3451. case "CUBICSPLINE" /* CUBICSPLINE */: {
  3452. getNextKey = function (frameIndex) { return ({
  3453. frame: data.input[frameIndex],
  3454. inTangent: getNextOutputValue(),
  3455. value: getNextOutputValue(),
  3456. outTangent: getNextOutputValue()
  3457. }); };
  3458. break;
  3459. }
  3460. }
  3461. var keys = new Array(data.input.length);
  3462. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  3463. keys[frameIndex] = getNextKey(frameIndex);
  3464. }
  3465. if (targetPath === "influence") {
  3466. var _loop_1 = function (targetIndex) {
  3467. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  3468. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  3469. babylonAnimation.setKeys(keys.map(function (key) { return ({
  3470. frame: key.frame,
  3471. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  3472. value: key.value[targetIndex],
  3473. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  3474. }); }));
  3475. var morphTargets = new Array();
  3476. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  3477. morphTargets.push(babylonMesh.morphTargetManager.getTarget(targetIndex));
  3478. });
  3479. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTargets);
  3480. };
  3481. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  3482. _loop_1(targetIndex);
  3483. }
  3484. }
  3485. else {
  3486. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  3487. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  3488. babylonAnimation.setKeys(keys);
  3489. if (targetNode._babylonAnimationTargets) {
  3490. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonAnimationTargets);
  3491. }
  3492. }
  3493. });
  3494. };
  3495. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  3496. if (sampler._data) {
  3497. return sampler._data;
  3498. }
  3499. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  3500. switch (interpolation) {
  3501. case "STEP" /* STEP */:
  3502. case "LINEAR" /* LINEAR */:
  3503. case "CUBICSPLINE" /* CUBICSPLINE */: {
  3504. break;
  3505. }
  3506. default: {
  3507. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  3508. }
  3509. }
  3510. var inputData;
  3511. var outputData;
  3512. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  3513. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  3514. sampler._data = Promise.all([
  3515. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  3516. inputData = data;
  3517. }),
  3518. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  3519. outputData = data;
  3520. })
  3521. ]).then(function () {
  3522. return {
  3523. input: inputData,
  3524. interpolation: interpolation,
  3525. output: outputData,
  3526. };
  3527. });
  3528. return sampler._data;
  3529. };
  3530. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  3531. if (buffer._data) {
  3532. return buffer._data;
  3533. }
  3534. if (!buffer.uri) {
  3535. throw new Error(context + ": Uri is missing");
  3536. }
  3537. buffer._data = this._loadUriAsync(context, buffer.uri);
  3538. return buffer._data;
  3539. };
  3540. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  3541. if (bufferView._data) {
  3542. return bufferView._data;
  3543. }
  3544. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  3545. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  3546. try {
  3547. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  3548. }
  3549. catch (e) {
  3550. throw new Error(context + ": " + e.message);
  3551. }
  3552. });
  3553. return bufferView._data;
  3554. };
  3555. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  3556. if (accessor.sparse) {
  3557. throw new Error(context + ": Sparse accessors are not currently supported");
  3558. }
  3559. if (accessor._data) {
  3560. return accessor._data;
  3561. }
  3562. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  3563. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  3564. var buffer = data.buffer;
  3565. var byteOffset = data.byteOffset + (accessor.byteOffset || 0);
  3566. var length = GLTFLoader._GetNumComponents(context, accessor.type) * accessor.count;
  3567. try {
  3568. switch (accessor.componentType) {
  3569. case 5120 /* BYTE */: {
  3570. return new Int8Array(buffer, byteOffset, length);
  3571. }
  3572. case 5121 /* UNSIGNED_BYTE */: {
  3573. return new Uint8Array(buffer, byteOffset, length);
  3574. }
  3575. case 5122 /* SHORT */: {
  3576. return new Int16Array(buffer, byteOffset, length);
  3577. }
  3578. case 5123 /* UNSIGNED_SHORT */: {
  3579. return new Uint16Array(buffer, byteOffset, length);
  3580. }
  3581. case 5125 /* UNSIGNED_INT */: {
  3582. return new Uint32Array(buffer, byteOffset, length);
  3583. }
  3584. case 5126 /* FLOAT */: {
  3585. return new Float32Array(buffer, byteOffset, length);
  3586. }
  3587. default: {
  3588. throw new Error(context + ": Invalid accessor component type " + accessor.componentType);
  3589. }
  3590. }
  3591. }
  3592. catch (e) {
  3593. throw new Error(context + ": " + e);
  3594. }
  3595. });
  3596. return accessor._data;
  3597. };
  3598. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  3599. var _this = this;
  3600. if (bufferView._babylonBuffer) {
  3601. return bufferView._babylonBuffer;
  3602. }
  3603. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  3604. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  3605. });
  3606. return bufferView._babylonBuffer;
  3607. };
  3608. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  3609. var _this = this;
  3610. if (accessor.sparse) {
  3611. throw new Error(context + ": Sparse accessors are not currently supported");
  3612. }
  3613. if (accessor._babylonVertexBuffer) {
  3614. return accessor._babylonVertexBuffer;
  3615. }
  3616. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  3617. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView, kind).then(function (buffer) {
  3618. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  3619. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  3620. });
  3621. return accessor._babylonVertexBuffer;
  3622. };
  3623. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  3624. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  3625. if (!babylonMaterial) {
  3626. babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, "__gltf_default", drawMode);
  3627. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  3628. babylonMaterial.metallic = 1;
  3629. babylonMaterial.roughness = 1;
  3630. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  3631. }
  3632. return babylonMaterial;
  3633. };
  3634. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  3635. var promises = new Array();
  3636. // Ensure metallic workflow
  3637. babylonMaterial.metallic = 1;
  3638. babylonMaterial.roughness = 1;
  3639. var properties = material.pbrMetallicRoughness;
  3640. if (properties) {
  3641. if (properties.baseColorFactor) {
  3642. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  3643. babylonMaterial.alpha = properties.baseColorFactor[3];
  3644. }
  3645. else {
  3646. babylonMaterial.albedoColor = BABYLON.Color3.White();
  3647. }
  3648. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  3649. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  3650. if (properties.baseColorTexture) {
  3651. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  3652. babylonMaterial.albedoTexture = texture;
  3653. }));
  3654. }
  3655. if (properties.metallicRoughnessTexture) {
  3656. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  3657. babylonMaterial.metallicTexture = texture;
  3658. }));
  3659. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  3660. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  3661. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  3662. }
  3663. }
  3664. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  3665. return Promise.all(promises).then(function () { });
  3666. };
  3667. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  3668. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  3669. if (promise) {
  3670. return promise;
  3671. }
  3672. material._babylonData = material._babylonData || {};
  3673. var babylonData = material._babylonData[babylonDrawMode];
  3674. if (!babylonData) {
  3675. var promises = new Array();
  3676. var name_3 = material.name || "materialSG_" + material._index;
  3677. var babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, name_3, babylonDrawMode);
  3678. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  3679. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  3680. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  3681. babylonData = {
  3682. material: babylonMaterial,
  3683. meshes: [],
  3684. loaded: Promise.all(promises).then(function () { })
  3685. };
  3686. material._babylonData[babylonDrawMode] = babylonData;
  3687. }
  3688. babylonData.meshes.push(babylonMesh);
  3689. assign(babylonData.material);
  3690. return babylonData.loaded;
  3691. };
  3692. GLTFLoader.prototype._createMaterial = function (type, name, drawMode) {
  3693. var babylonMaterial = new type(name, this._babylonScene);
  3694. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  3695. babylonMaterial.fillMode = drawMode;
  3696. return babylonMaterial;
  3697. };
  3698. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  3699. var promises = new Array();
  3700. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  3701. if (material.doubleSided) {
  3702. babylonMaterial.backFaceCulling = false;
  3703. babylonMaterial.twoSidedLighting = true;
  3704. }
  3705. if (material.normalTexture) {
  3706. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  3707. babylonMaterial.bumpTexture = texture;
  3708. }));
  3709. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  3710. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  3711. if (material.normalTexture.scale != undefined) {
  3712. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  3713. }
  3714. }
  3715. if (material.occlusionTexture) {
  3716. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  3717. babylonMaterial.ambientTexture = texture;
  3718. }));
  3719. babylonMaterial.useAmbientInGrayScale = true;
  3720. if (material.occlusionTexture.strength != undefined) {
  3721. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  3722. }
  3723. }
  3724. if (material.emissiveTexture) {
  3725. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  3726. babylonMaterial.emissiveTexture = texture;
  3727. }));
  3728. }
  3729. return Promise.all(promises).then(function () { });
  3730. };
  3731. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  3732. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  3733. switch (alphaMode) {
  3734. case "OPAQUE" /* OPAQUE */: {
  3735. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  3736. break;
  3737. }
  3738. case "MASK" /* MASK */: {
  3739. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  3740. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  3741. if (babylonMaterial.albedoTexture) {
  3742. babylonMaterial.albedoTexture.hasAlpha = true;
  3743. }
  3744. break;
  3745. }
  3746. case "BLEND" /* BLEND */: {
  3747. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  3748. if (babylonMaterial.albedoTexture) {
  3749. babylonMaterial.albedoTexture.hasAlpha = true;
  3750. babylonMaterial.useAlphaFromAlbedoTexture = true;
  3751. }
  3752. break;
  3753. }
  3754. default: {
  3755. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  3756. }
  3757. }
  3758. };
  3759. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  3760. var _this = this;
  3761. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  3762. context = "#/textures/" + textureInfo.index;
  3763. var promises = new Array();
  3764. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  3765. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  3766. var deferred = new BABYLON.Deferred();
  3767. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  3768. if (!_this._disposed) {
  3769. deferred.resolve();
  3770. }
  3771. }, function (message, exception) {
  3772. if (!_this._disposed) {
  3773. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  3774. }
  3775. });
  3776. promises.push(deferred.promise);
  3777. babylonTexture.name = texture.name || "texture" + texture._index;
  3778. babylonTexture.wrapU = samplerData.wrapU;
  3779. babylonTexture.wrapV = samplerData.wrapV;
  3780. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  3781. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  3782. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  3783. babylonTexture.updateURL(objectURL);
  3784. }));
  3785. assign(babylonTexture);
  3786. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  3787. return Promise.all(promises).then(function () { });
  3788. };
  3789. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  3790. if (!sampler._data) {
  3791. sampler._data = {
  3792. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  3793. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  3794. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  3795. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  3796. };
  3797. }
  3798. ;
  3799. return sampler._data;
  3800. };
  3801. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  3802. if (image._objectURL) {
  3803. return image._objectURL;
  3804. }
  3805. var promise;
  3806. if (image.uri) {
  3807. promise = this._loadUriAsync(context, image.uri);
  3808. }
  3809. else {
  3810. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  3811. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  3812. }
  3813. image._objectURL = promise.then(function (data) {
  3814. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  3815. });
  3816. return image._objectURL;
  3817. };
  3818. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  3819. var _this = this;
  3820. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  3821. if (promise) {
  3822. return promise;
  3823. }
  3824. if (!GLTFLoader._ValidateUri(uri)) {
  3825. throw new Error(context + ": Uri '" + uri + "' is invalid");
  3826. }
  3827. if (BABYLON.Tools.IsBase64(uri)) {
  3828. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  3829. }
  3830. return new Promise(function (resolve, reject) {
  3831. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  3832. if (!_this._disposed) {
  3833. resolve(new Uint8Array(data));
  3834. }
  3835. }, function (event) {
  3836. if (!_this._disposed) {
  3837. try {
  3838. if (request && _this._state === BABYLON.GLTFLoaderState.LOADING) {
  3839. request._lengthComputable = event.lengthComputable;
  3840. request._loaded = event.loaded;
  3841. request._total = event.total;
  3842. _this._onProgress();
  3843. }
  3844. }
  3845. catch (e) {
  3846. reject(e);
  3847. }
  3848. }
  3849. }, _this._babylonScene.database, true, function (request, exception) {
  3850. if (!_this._disposed) {
  3851. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  3852. }
  3853. });
  3854. _this._requests.push(request);
  3855. });
  3856. };
  3857. GLTFLoader.prototype._onProgress = function () {
  3858. if (!this._progressCallback) {
  3859. return;
  3860. }
  3861. var lengthComputable = true;
  3862. var loaded = 0;
  3863. var total = 0;
  3864. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  3865. var request = _a[_i];
  3866. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  3867. return;
  3868. }
  3869. lengthComputable = lengthComputable && request._lengthComputable;
  3870. loaded += request._loaded;
  3871. total += request._total;
  3872. }
  3873. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  3874. };
  3875. GLTFLoader._GetProperty = function (context, array, index) {
  3876. if (!array || index == undefined || !array[index]) {
  3877. throw new Error(context + ": Failed to find index (" + index + ")");
  3878. }
  3879. return array[index];
  3880. };
  3881. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  3882. // Set defaults if undefined
  3883. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  3884. switch (mode) {
  3885. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  3886. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  3887. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3888. default:
  3889. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  3890. return BABYLON.Texture.WRAP_ADDRESSMODE;
  3891. }
  3892. };
  3893. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  3894. // Set defaults if undefined
  3895. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  3896. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  3897. if (magFilter === 9729 /* LINEAR */) {
  3898. switch (minFilter) {
  3899. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  3900. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  3901. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  3902. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  3903. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  3904. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  3905. default:
  3906. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  3907. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  3908. }
  3909. }
  3910. else {
  3911. if (magFilter !== 9728 /* NEAREST */) {
  3912. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  3913. }
  3914. switch (minFilter) {
  3915. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  3916. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  3917. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  3918. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  3919. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  3920. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  3921. default:
  3922. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  3923. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  3924. }
  3925. }
  3926. };
  3927. GLTFLoader._GetNumComponents = function (context, type) {
  3928. switch (type) {
  3929. case "SCALAR": return 1;
  3930. case "VEC2": return 2;
  3931. case "VEC3": return 3;
  3932. case "VEC4": return 4;
  3933. case "MAT2": return 4;
  3934. case "MAT3": return 9;
  3935. case "MAT4": return 16;
  3936. }
  3937. throw new Error(context + ": Invalid type (" + type + ")");
  3938. };
  3939. GLTFLoader._ValidateUri = function (uri) {
  3940. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  3941. };
  3942. GLTFLoader._GetDrawMode = function (context, mode) {
  3943. if (mode == undefined) {
  3944. mode = 4 /* TRIANGLES */;
  3945. }
  3946. switch (mode) {
  3947. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  3948. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  3949. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  3950. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  3951. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  3952. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  3953. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  3954. }
  3955. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  3956. };
  3957. GLTFLoader.prototype._compileMaterialsAsync = function () {
  3958. var promises = new Array();
  3959. if (this._gltf.materials) {
  3960. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  3961. var material = _a[_i];
  3962. if (material._babylonData) {
  3963. for (var babylonDrawMode in material._babylonData) {
  3964. var babylonData = material._babylonData[babylonDrawMode];
  3965. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  3966. var babylonMesh = _c[_b];
  3967. // Ensure nonUniformScaling is set if necessary.
  3968. babylonMesh.computeWorldMatrix(true);
  3969. var babylonMaterial = babylonData.material;
  3970. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  3971. if (this.useClipPlane) {
  3972. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  3973. }
  3974. }
  3975. }
  3976. }
  3977. }
  3978. }
  3979. return Promise.all(promises).then(function () { });
  3980. };
  3981. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  3982. var promises = new Array();
  3983. var lights = this._babylonScene.lights;
  3984. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  3985. var light = lights_1[_i];
  3986. var generator = light.getShadowGenerator();
  3987. if (generator) {
  3988. promises.push(generator.forceCompilationAsync());
  3989. }
  3990. }
  3991. return Promise.all(promises).then(function () { });
  3992. };
  3993. GLTFLoader.prototype._clear = function () {
  3994. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  3995. var request = _a[_i];
  3996. request.abort();
  3997. }
  3998. this._requests.length = 0;
  3999. if (this._gltf && this._gltf.images) {
  4000. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  4001. var image = _c[_b];
  4002. if (image._objectURL) {
  4003. image._objectURL.then(function (value) {
  4004. URL.revokeObjectURL(value);
  4005. });
  4006. image._objectURL = undefined;
  4007. }
  4008. }
  4009. }
  4010. delete this._gltf;
  4011. delete this._babylonScene;
  4012. this._completePromises.length = 0;
  4013. for (var name_4 in this._extensions) {
  4014. this._extensions[name_4].dispose();
  4015. }
  4016. this._extensions = {};
  4017. delete this._rootBabylonMesh;
  4018. delete this._progressCallback;
  4019. this.onMeshLoadedObservable.clear();
  4020. this.onTextureLoadedObservable.clear();
  4021. this.onMaterialLoadedObservable.clear();
  4022. };
  4023. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  4024. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  4025. var name_5 = _a[_i];
  4026. var extension = this._extensions[name_5];
  4027. if (extension.enabled) {
  4028. var promise = actionAsync(extension);
  4029. if (promise) {
  4030. return promise;
  4031. }
  4032. }
  4033. }
  4034. return null;
  4035. };
  4036. GLTFLoader._Names = new Array();
  4037. GLTFLoader._Factories = {};
  4038. return GLTFLoader;
  4039. }());
  4040. GLTF2.GLTFLoader = GLTFLoader;
  4041. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  4042. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4043. })(BABYLON || (BABYLON = {}));
  4044. //# sourceMappingURL=babylon.glTFLoader.js.map
  4045. "use strict";
  4046. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  4047. var BABYLON;
  4048. (function (BABYLON) {
  4049. var GLTF2;
  4050. (function (GLTF2) {
  4051. var GLTFLoaderExtension = /** @class */ (function () {
  4052. function GLTFLoaderExtension(loader) {
  4053. this.enabled = true;
  4054. this._loader = loader;
  4055. }
  4056. GLTFLoaderExtension.prototype.dispose = function () {
  4057. delete this._loader;
  4058. };
  4059. // #region Overridable Methods
  4060. /** Override this method to modify the default behavior for loading scenes. */
  4061. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  4062. /** Override this method to modify the default behavior for loading nodes. */
  4063. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  4064. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  4065. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  4066. /** Override this method to modify the default behavior for loading materials. */
  4067. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  4068. /** Override this method to modify the default behavior for loading uris. */
  4069. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  4070. // #endregion
  4071. /** Helper method called by a loader extension to load an glTF extension. */
  4072. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  4073. if (!property.extensions) {
  4074. return null;
  4075. }
  4076. var extensions = property.extensions;
  4077. var extension = extensions[this.name];
  4078. if (!extension) {
  4079. return null;
  4080. }
  4081. // Clear out the extension before executing the action to avoid recursing into the same property.
  4082. delete extensions[this.name];
  4083. try {
  4084. return actionAsync(context + "/extensions/" + this.name, extension);
  4085. }
  4086. finally {
  4087. // Restore the extension after executing the action.
  4088. extensions[this.name] = extension;
  4089. }
  4090. };
  4091. /** Helper method called by the loader to allow extensions to override loading scenes. */
  4092. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  4093. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  4094. };
  4095. /** Helper method called by the loader to allow extensions to override loading nodes. */
  4096. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  4097. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  4098. };
  4099. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  4100. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  4101. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  4102. };
  4103. /** Helper method called by the loader to allow extensions to override loading materials. */
  4104. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  4105. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  4106. };
  4107. /** Helper method called by the loader to allow extensions to override loading uris. */
  4108. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  4109. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  4110. };
  4111. return GLTFLoaderExtension;
  4112. }());
  4113. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  4114. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4115. })(BABYLON || (BABYLON = {}));
  4116. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  4117. "use strict";
  4118. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4119. var __extends = (this && this.__extends) || (function () {
  4120. var extendStatics = Object.setPrototypeOf ||
  4121. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4122. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4123. return function (d, b) {
  4124. extendStatics(d, b);
  4125. function __() { this.constructor = d; }
  4126. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4127. };
  4128. })();
  4129. var BABYLON;
  4130. (function (BABYLON) {
  4131. var GLTF2;
  4132. (function (GLTF2) {
  4133. var Extensions;
  4134. (function (Extensions) {
  4135. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod
  4136. var NAME = "MSFT_lod";
  4137. var MSFT_lod = /** @class */ (function (_super) {
  4138. __extends(MSFT_lod, _super);
  4139. function MSFT_lod() {
  4140. var _this = _super !== null && _super.apply(this, arguments) || this;
  4141. _this.name = NAME;
  4142. /**
  4143. * Maximum number of LODs to load, starting from the lowest LOD.
  4144. */
  4145. _this.maxLODsToLoad = Number.MAX_VALUE;
  4146. _this._loadingNodeLOD = null;
  4147. _this._loadNodeSignals = {};
  4148. _this._loadingMaterialLOD = null;
  4149. _this._loadMaterialSignals = {};
  4150. return _this;
  4151. }
  4152. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  4153. var _this = this;
  4154. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  4155. var firstPromise;
  4156. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  4157. var _loop_1 = function (indexLOD) {
  4158. var nodeLOD = nodeLODs[indexLOD];
  4159. if (indexLOD !== 0) {
  4160. _this._loadingNodeLOD = nodeLOD;
  4161. if (!_this._loadNodeSignals[nodeLOD._index]) {
  4162. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  4163. }
  4164. }
  4165. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  4166. if (indexLOD !== 0) {
  4167. var previousNodeLOD = nodeLODs[indexLOD - 1];
  4168. if (previousNodeLOD._babylonMesh) {
  4169. previousNodeLOD._babylonMesh.dispose(false, true);
  4170. delete previousNodeLOD._babylonMesh;
  4171. }
  4172. }
  4173. if (indexLOD !== nodeLODs.length - 1) {
  4174. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  4175. if (_this._loadNodeSignals[nodeIndex]) {
  4176. _this._loadNodeSignals[nodeIndex].resolve();
  4177. delete _this._loadNodeSignals[nodeIndex];
  4178. }
  4179. }
  4180. });
  4181. if (indexLOD === 0) {
  4182. firstPromise = promise;
  4183. }
  4184. else {
  4185. _this._loader._completePromises.push(promise);
  4186. _this._loadingNodeLOD = null;
  4187. }
  4188. };
  4189. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  4190. _loop_1(indexLOD);
  4191. }
  4192. return firstPromise;
  4193. });
  4194. };
  4195. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  4196. var _this = this;
  4197. // Don't load material LODs if already loading a node LOD.
  4198. if (this._loadingNodeLOD) {
  4199. return null;
  4200. }
  4201. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  4202. var firstPromise;
  4203. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  4204. var _loop_2 = function (indexLOD) {
  4205. var materialLOD = materialLODs[indexLOD];
  4206. if (indexLOD !== 0) {
  4207. _this._loadingMaterialLOD = materialLOD;
  4208. if (!_this._loadMaterialSignals[materialLOD._index]) {
  4209. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  4210. }
  4211. }
  4212. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  4213. if (indexLOD !== 0) {
  4214. var babylonDataLOD = materialLOD._babylonData;
  4215. assign(babylonDataLOD[babylonDrawMode].material);
  4216. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  4217. if (previousBabylonDataLOD[babylonDrawMode]) {
  4218. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  4219. delete previousBabylonDataLOD[babylonDrawMode];
  4220. }
  4221. }
  4222. if (indexLOD !== materialLODs.length - 1) {
  4223. var materialIndex = materialLODs[indexLOD + 1]._index;
  4224. if (_this._loadMaterialSignals[materialIndex]) {
  4225. _this._loadMaterialSignals[materialIndex].resolve();
  4226. delete _this._loadMaterialSignals[materialIndex];
  4227. }
  4228. }
  4229. });
  4230. if (indexLOD === 0) {
  4231. firstPromise = promise;
  4232. }
  4233. else {
  4234. _this._loader._completePromises.push(promise);
  4235. _this._loadingMaterialLOD = null;
  4236. }
  4237. };
  4238. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  4239. _loop_2(indexLOD);
  4240. }
  4241. return firstPromise;
  4242. });
  4243. };
  4244. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  4245. var _this = this;
  4246. // Defer the loading of uris if loading a material or node LOD.
  4247. if (this._loadingMaterialLOD) {
  4248. var index = this._loadingMaterialLOD._index;
  4249. return this._loadMaterialSignals[index].promise.then(function () {
  4250. return _this._loader._loadUriAsync(context, uri);
  4251. });
  4252. }
  4253. else if (this._loadingNodeLOD) {
  4254. var index = this._loadingNodeLOD._index;
  4255. return this._loadNodeSignals[index].promise.then(function () {
  4256. return _this._loader._loadUriAsync(context, uri);
  4257. });
  4258. }
  4259. return null;
  4260. };
  4261. /**
  4262. * Gets an array of LOD properties from lowest to highest.
  4263. */
  4264. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  4265. if (this.maxLODsToLoad <= 0) {
  4266. throw new Error("maxLODsToLoad must be greater than zero");
  4267. }
  4268. var properties = new Array();
  4269. for (var i = ids.length - 1; i >= 0; i--) {
  4270. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  4271. if (properties.length === this.maxLODsToLoad) {
  4272. return properties;
  4273. }
  4274. }
  4275. properties.push(property);
  4276. return properties;
  4277. };
  4278. return MSFT_lod;
  4279. }(GLTF2.GLTFLoaderExtension));
  4280. Extensions.MSFT_lod = MSFT_lod;
  4281. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  4282. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4283. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4284. })(BABYLON || (BABYLON = {}));
  4285. //# sourceMappingURL=MSFT_lod.js.map
  4286. "use strict";
  4287. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4288. var __extends = (this && this.__extends) || (function () {
  4289. var extendStatics = Object.setPrototypeOf ||
  4290. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4291. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4292. return function (d, b) {
  4293. extendStatics(d, b);
  4294. function __() { this.constructor = d; }
  4295. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4296. };
  4297. })();
  4298. var BABYLON;
  4299. (function (BABYLON) {
  4300. var GLTF2;
  4301. (function (GLTF2) {
  4302. var Extensions;
  4303. (function (Extensions) {
  4304. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  4305. var NAME = "KHR_draco_mesh_compression";
  4306. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  4307. __extends(KHR_draco_mesh_compression, _super);
  4308. function KHR_draco_mesh_compression(loader) {
  4309. var _this = _super.call(this, loader) || this;
  4310. _this.name = NAME;
  4311. _this._dracoCompression = null;
  4312. // Disable extension if decoder is not available.
  4313. if (!BABYLON.DracoCompression.DecoderAvailable) {
  4314. _this.enabled = false;
  4315. }
  4316. return _this;
  4317. }
  4318. KHR_draco_mesh_compression.prototype.dispose = function () {
  4319. if (this._dracoCompression) {
  4320. this._dracoCompression.dispose();
  4321. }
  4322. _super.prototype.dispose.call(this);
  4323. };
  4324. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  4325. var _this = this;
  4326. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  4327. if (primitive.mode != undefined) {
  4328. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  4329. primitive.mode !== 4 /* TRIANGLES */) {
  4330. throw new Error(context + ": Unsupported mode " + primitive.mode);
  4331. }
  4332. // TODO: handle triangle strips
  4333. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  4334. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  4335. }
  4336. }
  4337. var attributes = {};
  4338. var loadAttribute = function (name, kind) {
  4339. var uniqueId = extension.attributes[name];
  4340. if (uniqueId == undefined) {
  4341. return;
  4342. }
  4343. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  4344. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  4345. babylonMesh._delayInfo.push(kind);
  4346. }
  4347. attributes[kind] = uniqueId;
  4348. };
  4349. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  4350. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  4351. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  4352. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  4353. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  4354. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  4355. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  4356. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  4357. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  4358. if (!bufferView._dracoBabylonGeometry) {
  4359. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  4360. if (!_this._dracoCompression) {
  4361. _this._dracoCompression = new BABYLON.DracoCompression();
  4362. }
  4363. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  4364. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  4365. babylonVertexData.applyToGeometry(babylonGeometry);
  4366. return babylonGeometry;
  4367. }).catch(function (error) {
  4368. throw new Error(context + ": " + error.message);
  4369. });
  4370. });
  4371. }
  4372. return bufferView._dracoBabylonGeometry;
  4373. });
  4374. };
  4375. return KHR_draco_mesh_compression;
  4376. }(GLTF2.GLTFLoaderExtension));
  4377. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  4378. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  4379. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4380. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4381. })(BABYLON || (BABYLON = {}));
  4382. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  4383. "use strict";
  4384. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4385. var __extends = (this && this.__extends) || (function () {
  4386. var extendStatics = Object.setPrototypeOf ||
  4387. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4388. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4389. return function (d, b) {
  4390. extendStatics(d, b);
  4391. function __() { this.constructor = d; }
  4392. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4393. };
  4394. })();
  4395. var BABYLON;
  4396. (function (BABYLON) {
  4397. var GLTF2;
  4398. (function (GLTF2) {
  4399. var Extensions;
  4400. (function (Extensions) {
  4401. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  4402. var NAME = "KHR_materials_pbrSpecularGlossiness";
  4403. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  4404. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  4405. function KHR_materials_pbrSpecularGlossiness() {
  4406. var _this = _super !== null && _super.apply(this, arguments) || this;
  4407. _this.name = NAME;
  4408. return _this;
  4409. }
  4410. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  4411. var _this = this;
  4412. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  4413. material._babylonData = material._babylonData || {};
  4414. var babylonData = material._babylonData[babylonDrawMode];
  4415. if (!babylonData) {
  4416. var promises = new Array();
  4417. var name_1 = material.name || "materialSG_" + material._index;
  4418. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  4419. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  4420. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  4421. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4422. babylonData = {
  4423. material: babylonMaterial,
  4424. meshes: [],
  4425. loaded: Promise.all(promises).then(function () { })
  4426. };
  4427. material._babylonData[babylonDrawMode] = babylonData;
  4428. }
  4429. babylonData.meshes.push(babylonMesh);
  4430. assign(babylonData.material);
  4431. return babylonData.loaded;
  4432. });
  4433. };
  4434. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  4435. var promises = new Array();
  4436. if (properties.diffuseFactor) {
  4437. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  4438. babylonMaterial.alpha = properties.diffuseFactor[3];
  4439. }
  4440. else {
  4441. babylonMaterial.albedoColor = BABYLON.Color3.White();
  4442. }
  4443. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  4444. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  4445. if (properties.diffuseTexture) {
  4446. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  4447. babylonMaterial.albedoTexture = texture;
  4448. }));
  4449. }
  4450. if (properties.specularGlossinessTexture) {
  4451. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  4452. babylonMaterial.reflectivityTexture = texture;
  4453. }));
  4454. babylonMaterial.reflectivityTexture.hasAlpha = true;
  4455. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  4456. }
  4457. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  4458. return Promise.all(promises).then(function () { });
  4459. };
  4460. return KHR_materials_pbrSpecularGlossiness;
  4461. }(GLTF2.GLTFLoaderExtension));
  4462. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  4463. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  4464. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4465. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4466. })(BABYLON || (BABYLON = {}));
  4467. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  4468. "use strict";
  4469. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4470. var __extends = (this && this.__extends) || (function () {
  4471. var extendStatics = Object.setPrototypeOf ||
  4472. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4473. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4474. return function (d, b) {
  4475. extendStatics(d, b);
  4476. function __() { this.constructor = d; }
  4477. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4478. };
  4479. })();
  4480. var BABYLON;
  4481. (function (BABYLON) {
  4482. var GLTF2;
  4483. (function (GLTF2) {
  4484. var Extensions;
  4485. (function (Extensions) {
  4486. // https://github.com/donmccurdy/glTF/tree/feat-khr-materials-cmnConstant/extensions/2.0/Khronos/KHR_materials_unlit
  4487. var NAME = "KHR_materials_unlit";
  4488. var KHR_materials_unlit = /** @class */ (function (_super) {
  4489. __extends(KHR_materials_unlit, _super);
  4490. function KHR_materials_unlit() {
  4491. var _this = _super !== null && _super.apply(this, arguments) || this;
  4492. _this.name = NAME;
  4493. return _this;
  4494. }
  4495. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  4496. var _this = this;
  4497. return this._loadExtensionAsync(context, material, function () {
  4498. material._babylonData = material._babylonData || {};
  4499. var babylonData = material._babylonData[babylonDrawMode];
  4500. if (!babylonData) {
  4501. var name_1 = material.name || "materialUnlit_" + material._index;
  4502. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  4503. babylonMaterial.unlit = true;
  4504. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  4505. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4506. babylonData = {
  4507. material: babylonMaterial,
  4508. meshes: [],
  4509. loaded: promise
  4510. };
  4511. material._babylonData[babylonDrawMode] = babylonData;
  4512. }
  4513. babylonData.meshes.push(babylonMesh);
  4514. assign(babylonData.material);
  4515. return babylonData.loaded;
  4516. });
  4517. };
  4518. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  4519. var promises = new Array();
  4520. // Ensure metallic workflow
  4521. babylonMaterial.metallic = 1;
  4522. babylonMaterial.roughness = 1;
  4523. var properties = material.pbrMetallicRoughness;
  4524. if (properties) {
  4525. if (properties.baseColorFactor) {
  4526. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  4527. babylonMaterial.alpha = properties.baseColorFactor[3];
  4528. }
  4529. else {
  4530. babylonMaterial.albedoColor = BABYLON.Color3.White();
  4531. }
  4532. if (properties.baseColorTexture) {
  4533. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  4534. babylonMaterial.albedoTexture = texture;
  4535. }));
  4536. }
  4537. }
  4538. if (material.doubleSided) {
  4539. babylonMaterial.backFaceCulling = false;
  4540. babylonMaterial.twoSidedLighting = true;
  4541. }
  4542. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  4543. return Promise.all(promises).then(function () { });
  4544. };
  4545. return KHR_materials_unlit;
  4546. }(GLTF2.GLTFLoaderExtension));
  4547. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  4548. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  4549. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4550. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4551. })(BABYLON || (BABYLON = {}));
  4552. //# sourceMappingURL=KHR_materials_unlit.js.map
  4553. "use strict";
  4554. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4555. var __extends = (this && this.__extends) || (function () {
  4556. var extendStatics = Object.setPrototypeOf ||
  4557. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4558. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4559. return function (d, b) {
  4560. extendStatics(d, b);
  4561. function __() { this.constructor = d; }
  4562. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4563. };
  4564. })();
  4565. var BABYLON;
  4566. (function (BABYLON) {
  4567. var GLTF2;
  4568. (function (GLTF2) {
  4569. var Extensions;
  4570. (function (Extensions) {
  4571. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  4572. var NAME = "KHR_lights";
  4573. var LightType;
  4574. (function (LightType) {
  4575. LightType["AMBIENT"] = "ambient";
  4576. LightType["DIRECTIONAL"] = "directional";
  4577. LightType["POINT"] = "point";
  4578. LightType["SPOT"] = "spot";
  4579. })(LightType || (LightType = {}));
  4580. var KHR_lights = /** @class */ (function (_super) {
  4581. __extends(KHR_lights, _super);
  4582. function KHR_lights() {
  4583. var _this = _super !== null && _super.apply(this, arguments) || this;
  4584. _this.name = NAME;
  4585. return _this;
  4586. }
  4587. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  4588. var _this = this;
  4589. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  4590. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  4591. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  4592. if (light.type !== LightType.AMBIENT) {
  4593. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  4594. }
  4595. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  4596. return promise;
  4597. });
  4598. };
  4599. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  4600. var _this = this;
  4601. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  4602. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  4603. var babylonLight;
  4604. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  4605. var name = node._babylonMesh.name;
  4606. switch (light.type) {
  4607. case LightType.AMBIENT: {
  4608. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  4609. }
  4610. case LightType.DIRECTIONAL: {
  4611. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  4612. break;
  4613. }
  4614. case LightType.POINT: {
  4615. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  4616. break;
  4617. }
  4618. case LightType.SPOT: {
  4619. var spotLight = light;
  4620. // TODO: support inner and outer cone angles
  4621. //const innerConeAngle = spotLight.innerConeAngle || 0;
  4622. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  4623. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  4624. break;
  4625. }
  4626. default: {
  4627. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  4628. }
  4629. }
  4630. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  4631. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  4632. babylonLight.parent = node._babylonMesh;
  4633. return promise;
  4634. });
  4635. };
  4636. Object.defineProperty(KHR_lights.prototype, "_lights", {
  4637. get: function () {
  4638. var extensions = this._loader._gltf.extensions;
  4639. if (!extensions || !extensions[this.name]) {
  4640. throw new Error("#/extensions: '" + this.name + "' not found");
  4641. }
  4642. var extension = extensions[this.name];
  4643. return extension.lights;
  4644. },
  4645. enumerable: true,
  4646. configurable: true
  4647. });
  4648. return KHR_lights;
  4649. }(GLTF2.GLTFLoaderExtension));
  4650. Extensions.KHR_lights = KHR_lights;
  4651. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  4652. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4653. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4654. })(BABYLON || (BABYLON = {}));
  4655. //# sourceMappingURL=KHR_lights.js.map