babylon.glTFFileLoader.js 239 KB

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