babylonjs.loaders.js 277 KB

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