babylon.glTFFileLoader.js 224 KB

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