babylon.glTFFileLoader.js 228 KB

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