babylonjs.loaders.js 277 KB

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