babylonjs.loaders.js 255 KB

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