babylon.glTFFileLoader.js 233 KB

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