babylonjs.loaders.js 246 KB

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