babylon.glTFFileLoader.js 272 KB

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