babylon.glTFFileLoader.js 264 KB

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