babylonjs.loaders.js 238 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794
  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, false) > 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. * This function will read the mtl file and create each material described inside
  191. * This function could be improve by adding :
  192. * -some component missing (Ni, Tf...)
  193. * -including the specific options available
  194. *
  195. * @param scene
  196. * @param data
  197. * @param rootUrl
  198. */
  199. this.parseMTL = function (scene, data, rootUrl) {
  200. //Split the lines from the file
  201. var lines = data.split('\n');
  202. //Space char
  203. var delimiter_pattern = /\s+/;
  204. //Array with RGB colors
  205. var color;
  206. //New material
  207. var material;
  208. //Look at each line
  209. for (var i = 0; i < lines.length; i++) {
  210. var line = lines[i].trim();
  211. // Blank line or comment
  212. if (line.length === 0 || line.charAt(0) === '#') {
  213. continue;
  214. }
  215. //Get the first parameter (keyword)
  216. var pos = line.indexOf(' ');
  217. var key = (pos >= 0) ? line.substring(0, pos) : line;
  218. key = key.toLowerCase();
  219. //Get the data following the key
  220. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  221. //This mtl keyword will create the new material
  222. if (key === "newmtl") {
  223. //Check if it is the first material.
  224. // Materials specifications are described after this keyword.
  225. if (material) {
  226. //Add the previous material in the material array.
  227. this.materials.push(material);
  228. }
  229. //Create a new material.
  230. // value is the name of the material read in the mtl file
  231. material = new BABYLON.StandardMaterial(value, scene);
  232. }
  233. else if (key === "kd") {
  234. // Diffuse color (color under white light) using RGB values
  235. //value = "r g b"
  236. color = value.split(delimiter_pattern, 3);
  237. //color = [r,g,b]
  238. //Set tghe color into the material
  239. material.diffuseColor = BABYLON.Color3.FromArray(color);
  240. }
  241. else if (key === "ka") {
  242. // Ambient color (color under shadow) using RGB values
  243. //value = "r g b"
  244. color = value.split(delimiter_pattern, 3);
  245. //color = [r,g,b]
  246. //Set tghe color into the material
  247. material.ambientColor = BABYLON.Color3.FromArray(color);
  248. }
  249. else if (key === "ks") {
  250. // Specular color (color when light is reflected from shiny surface) using RGB values
  251. //value = "r g b"
  252. color = value.split(delimiter_pattern, 3);
  253. //color = [r,g,b]
  254. //Set the color into the material
  255. material.specularColor = BABYLON.Color3.FromArray(color);
  256. }
  257. else if (key === "ke") {
  258. // Emissive color using RGB values
  259. color = value.split(delimiter_pattern, 3);
  260. material.emissiveColor = BABYLON.Color3.FromArray(color);
  261. }
  262. else if (key === "ns") {
  263. //value = "Integer"
  264. material.specularPower = value;
  265. }
  266. else if (key === "d") {
  267. //d is dissolve for current material. It mean alpha for BABYLON
  268. material.alpha = value;
  269. //Texture
  270. //This part can be improved by adding the possible options of texture
  271. }
  272. else if (key === "map_ka") {
  273. // ambient texture map with a loaded image
  274. //We must first get the folder of the image
  275. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  276. }
  277. else if (key === "map_kd") {
  278. // Diffuse texture map with a loaded image
  279. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  280. }
  281. else if (key === "map_ks") {
  282. // Specular texture map with a loaded image
  283. //We must first get the folder of the image
  284. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  285. }
  286. else if (key === "map_ns") {
  287. //Specular
  288. //Specular highlight component
  289. //We must first get the folder of the image
  290. //
  291. //Not supported by BABYLON
  292. //
  293. // continue;
  294. }
  295. else if (key === "map_bump") {
  296. //The bump texture
  297. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  298. }
  299. else if (key === "map_d") {
  300. // The dissolve of the material
  301. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  302. //Options for illumination
  303. }
  304. else if (key === "illum") {
  305. //Illumination
  306. if (value === "0") {
  307. //That mean Kd == Kd
  308. }
  309. else if (value === "1") {
  310. //Color on and Ambient on
  311. }
  312. else if (value === "2") {
  313. //Highlight on
  314. }
  315. else if (value === "3") {
  316. //Reflection on and Ray trace on
  317. }
  318. else if (value === "4") {
  319. //Transparency: Glass on, Reflection: Ray trace on
  320. }
  321. else if (value === "5") {
  322. //Reflection: Fresnel on and Ray trace on
  323. }
  324. else if (value === "6") {
  325. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  326. }
  327. else if (value === "7") {
  328. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  329. }
  330. else if (value === "8") {
  331. //Reflection on and Ray trace off
  332. }
  333. else if (value === "9") {
  334. //Transparency: Glass on, Reflection: Ray trace off
  335. }
  336. else if (value === "10") {
  337. //Casts shadows onto invisible surfaces
  338. }
  339. }
  340. else {
  341. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  342. }
  343. }
  344. //At the end of the file, add the last material
  345. this.materials.push(material);
  346. };
  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 = [];
  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. return OBJFileLoader;
  956. }());
  957. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  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. if (data instanceof ArrayBuffer) {
  1020. return GLTFFileLoader._parseBinary(data, onError);
  1021. }
  1022. try {
  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. if (!version) {
  1151. return null;
  1152. }
  1153. var parts = version.split(".");
  1154. if (parts.length != 2) {
  1155. return null;
  1156. }
  1157. var major = +parts[0];
  1158. if (isNaN(major)) {
  1159. return null;
  1160. }
  1161. var minor = +parts[1];
  1162. if (isNaN(minor)) {
  1163. return null;
  1164. }
  1165. return {
  1166. major: major,
  1167. minor: minor
  1168. };
  1169. };
  1170. GLTFFileLoader._compareVersion = function (a, b) {
  1171. if (a.major > b.major)
  1172. return 1;
  1173. if (a.major < b.major)
  1174. return -1;
  1175. if (a.minor > b.minor)
  1176. return 1;
  1177. if (a.minor < b.minor)
  1178. return -1;
  1179. return 0;
  1180. };
  1181. GLTFFileLoader._decodeBufferToText = function (view) {
  1182. var result = "";
  1183. var length = view.byteLength;
  1184. for (var i = 0; i < length; ++i) {
  1185. result += String.fromCharCode(view[i]);
  1186. }
  1187. return result;
  1188. };
  1189. return GLTFFileLoader;
  1190. }());
  1191. // V1 options
  1192. GLTFFileLoader.HomogeneousCoordinates = false;
  1193. GLTFFileLoader.IncrementalLoading = true;
  1194. BABYLON.GLTFFileLoader = GLTFFileLoader;
  1195. var BinaryReader = (function () {
  1196. function BinaryReader(arrayBuffer) {
  1197. this._arrayBuffer = arrayBuffer;
  1198. this._dataView = new DataView(arrayBuffer);
  1199. this._byteOffset = 0;
  1200. }
  1201. BinaryReader.prototype.getPosition = function () {
  1202. return this._byteOffset;
  1203. };
  1204. BinaryReader.prototype.getLength = function () {
  1205. return this._arrayBuffer.byteLength;
  1206. };
  1207. BinaryReader.prototype.readUint32 = function () {
  1208. var value = this._dataView.getUint32(this._byteOffset, true);
  1209. this._byteOffset += 4;
  1210. return value;
  1211. };
  1212. BinaryReader.prototype.readUint8Array = function (length) {
  1213. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  1214. this._byteOffset += length;
  1215. return value;
  1216. };
  1217. BinaryReader.prototype.skipBytes = function (length) {
  1218. this._byteOffset += length;
  1219. };
  1220. return BinaryReader;
  1221. }());
  1222. if (BABYLON.SceneLoader) {
  1223. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  1224. }
  1225. })(BABYLON || (BABYLON = {}));
  1226. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  1227. var BABYLON;
  1228. (function (BABYLON) {
  1229. var GLTF1;
  1230. (function (GLTF1) {
  1231. /**
  1232. * Enums
  1233. */
  1234. var EComponentType;
  1235. (function (EComponentType) {
  1236. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  1237. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  1238. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  1239. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  1240. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  1241. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  1242. var EShaderType;
  1243. (function (EShaderType) {
  1244. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  1245. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  1246. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  1247. var EParameterType;
  1248. (function (EParameterType) {
  1249. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  1250. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  1251. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  1252. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  1253. EParameterType[EParameterType["INT"] = 5124] = "INT";
  1254. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  1255. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  1256. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  1257. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  1258. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  1259. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  1260. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  1261. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  1262. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  1263. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  1264. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  1265. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  1266. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  1267. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  1268. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  1269. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  1270. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  1271. var ETextureWrapMode;
  1272. (function (ETextureWrapMode) {
  1273. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  1274. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  1275. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  1276. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  1277. var ETextureFilterType;
  1278. (function (ETextureFilterType) {
  1279. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  1280. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  1281. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  1282. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  1283. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  1284. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  1285. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  1286. var ETextureFormat;
  1287. (function (ETextureFormat) {
  1288. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  1289. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  1290. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  1291. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  1292. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  1293. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  1294. var ECullingType;
  1295. (function (ECullingType) {
  1296. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  1297. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  1298. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  1299. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  1300. var EBlendingFunction;
  1301. (function (EBlendingFunction) {
  1302. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  1303. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  1304. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  1305. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  1306. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  1307. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  1308. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  1309. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  1310. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  1311. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  1312. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  1313. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  1314. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  1315. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  1316. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  1317. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  1318. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  1319. })(BABYLON || (BABYLON = {}));
  1320. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  1321. var BABYLON;
  1322. (function (BABYLON) {
  1323. var GLTF1;
  1324. (function (GLTF1) {
  1325. /**
  1326. * Tokenizer. Used for shaders compatibility
  1327. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  1328. */
  1329. var ETokenType;
  1330. (function (ETokenType) {
  1331. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  1332. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  1333. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  1334. })(ETokenType || (ETokenType = {}));
  1335. var Tokenizer = (function () {
  1336. function Tokenizer(toParse) {
  1337. this._pos = 0;
  1338. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  1339. this._toParse = toParse;
  1340. this._maxPos = toParse.length;
  1341. }
  1342. Tokenizer.prototype.getNextToken = function () {
  1343. if (this.isEnd())
  1344. return ETokenType.END_OF_INPUT;
  1345. this.currentString = this.read();
  1346. this.currentToken = ETokenType.UNKNOWN;
  1347. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  1348. this.currentToken = ETokenType.IDENTIFIER;
  1349. this.currentIdentifier = this.currentString;
  1350. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  1351. this.currentIdentifier += this.currentString;
  1352. this.forward();
  1353. }
  1354. }
  1355. return this.currentToken;
  1356. };
  1357. Tokenizer.prototype.peek = function () {
  1358. return this._toParse[this._pos];
  1359. };
  1360. Tokenizer.prototype.read = function () {
  1361. return this._toParse[this._pos++];
  1362. };
  1363. Tokenizer.prototype.forward = function () {
  1364. this._pos++;
  1365. };
  1366. Tokenizer.prototype.isEnd = function () {
  1367. return this._pos >= this._maxPos;
  1368. };
  1369. return Tokenizer;
  1370. }());
  1371. /**
  1372. * Values
  1373. */
  1374. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  1375. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  1376. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  1377. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  1378. /**
  1379. * Parse
  1380. */
  1381. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  1382. for (var buf in parsedBuffers) {
  1383. var parsedBuffer = parsedBuffers[buf];
  1384. gltfRuntime.buffers[buf] = parsedBuffer;
  1385. gltfRuntime.buffersCount++;
  1386. }
  1387. };
  1388. var parseShaders = function (parsedShaders, gltfRuntime) {
  1389. for (var sha in parsedShaders) {
  1390. var parsedShader = parsedShaders[sha];
  1391. gltfRuntime.shaders[sha] = parsedShader;
  1392. gltfRuntime.shaderscount++;
  1393. }
  1394. };
  1395. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  1396. for (var object in parsedObjects) {
  1397. var parsedObject = parsedObjects[object];
  1398. gltfRuntime[runtimeProperty][object] = parsedObject;
  1399. }
  1400. };
  1401. /**
  1402. * Utils
  1403. */
  1404. var normalizeUVs = function (buffer) {
  1405. if (!buffer) {
  1406. return;
  1407. }
  1408. for (var i = 0; i < buffer.length / 2; i++) {
  1409. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  1410. }
  1411. };
  1412. var replaceInString = function (str, searchValue, replaceValue) {
  1413. while (str.indexOf(searchValue) !== -1) {
  1414. str = str.replace(searchValue, replaceValue);
  1415. }
  1416. return str;
  1417. };
  1418. var getAttribute = function (attributeParameter) {
  1419. if (attributeParameter.semantic === "NORMAL") {
  1420. return "normal";
  1421. }
  1422. else if (attributeParameter.semantic === "POSITION") {
  1423. return "position";
  1424. }
  1425. else if (attributeParameter.semantic === "JOINT") {
  1426. return "matricesIndices";
  1427. }
  1428. else if (attributeParameter.semantic === "WEIGHT") {
  1429. return "matricesWeights";
  1430. }
  1431. else if (attributeParameter.semantic === "COLOR") {
  1432. return "color";
  1433. }
  1434. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  1435. var channel = Number(attributeParameter.semantic.split("_")[1]);
  1436. return "uv" + (channel === 0 ? "" : channel + 1);
  1437. }
  1438. };
  1439. /**
  1440. * Returns the animation path (glTF -> Babylon)
  1441. */
  1442. var getAnimationPath = function (path) {
  1443. var index = glTFAnimationPaths.indexOf(path);
  1444. if (index !== -1) {
  1445. return babylonAnimationPaths[index];
  1446. }
  1447. return path;
  1448. };
  1449. /**
  1450. * Loads and creates animations
  1451. */
  1452. var loadAnimations = function (gltfRuntime) {
  1453. for (var anim in gltfRuntime.animations) {
  1454. var animation = gltfRuntime.animations[anim];
  1455. var lastAnimation = null;
  1456. for (var i = 0; i < animation.channels.length; i++) {
  1457. // Get parameters and load buffers
  1458. var channel = animation.channels[i];
  1459. var sampler = animation.samplers[channel.sampler];
  1460. if (!sampler) {
  1461. continue;
  1462. }
  1463. var inputData = null;
  1464. var outputData = null;
  1465. if (animation.parameters) {
  1466. inputData = animation.parameters[sampler.input];
  1467. outputData = animation.parameters[sampler.output];
  1468. }
  1469. else {
  1470. inputData = sampler.input;
  1471. outputData = sampler.output;
  1472. }
  1473. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  1474. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  1475. var targetID = channel.target.id;
  1476. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  1477. if (targetNode === null) {
  1478. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  1479. }
  1480. if (targetNode === null) {
  1481. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  1482. continue;
  1483. }
  1484. var isBone = targetNode instanceof BABYLON.Bone;
  1485. // Get target path (position, rotation or scaling)
  1486. var targetPath = channel.target.path;
  1487. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  1488. if (targetPathIndex !== -1) {
  1489. targetPath = babylonAnimationPaths[targetPathIndex];
  1490. }
  1491. // Determine animation type
  1492. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  1493. if (!isBone) {
  1494. if (targetPath === "rotationQuaternion") {
  1495. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  1496. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  1497. }
  1498. else {
  1499. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  1500. }
  1501. }
  1502. // Create animation and key frames
  1503. var babylonAnimation = null;
  1504. var keys = [];
  1505. var arrayOffset = 0;
  1506. var modifyKey = false;
  1507. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  1508. babylonAnimation = lastAnimation;
  1509. modifyKey = true;
  1510. }
  1511. if (!modifyKey) {
  1512. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  1513. }
  1514. // For each frame
  1515. for (var j = 0; j < bufferInput.length; j++) {
  1516. var value = null;
  1517. if (targetPath === "rotationQuaternion") {
  1518. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  1519. arrayOffset += 4;
  1520. }
  1521. else {
  1522. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  1523. arrayOffset += 3;
  1524. }
  1525. if (isBone) {
  1526. var bone = targetNode;
  1527. var translation = BABYLON.Vector3.Zero();
  1528. var rotationQuaternion = new BABYLON.Quaternion();
  1529. var scaling = BABYLON.Vector3.Zero();
  1530. // Warning on decompose
  1531. var mat = bone.getBaseMatrix();
  1532. if (modifyKey) {
  1533. mat = lastAnimation.getKeys()[j].value;
  1534. }
  1535. mat.decompose(scaling, rotationQuaternion, translation);
  1536. if (targetPath === "position") {
  1537. translation = value;
  1538. }
  1539. else if (targetPath === "rotationQuaternion") {
  1540. rotationQuaternion = value;
  1541. }
  1542. else {
  1543. scaling = value;
  1544. }
  1545. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  1546. }
  1547. if (!modifyKey) {
  1548. keys.push({
  1549. frame: bufferInput[j],
  1550. value: value
  1551. });
  1552. }
  1553. else {
  1554. lastAnimation.getKeys()[j].value = value;
  1555. }
  1556. }
  1557. // Finish
  1558. if (!modifyKey) {
  1559. babylonAnimation.setKeys(keys);
  1560. targetNode.animations.push(babylonAnimation);
  1561. }
  1562. lastAnimation = babylonAnimation;
  1563. gltfRuntime.scene.stopAnimation(targetNode);
  1564. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  1565. }
  1566. }
  1567. };
  1568. /**
  1569. * Returns the bones transformation matrix
  1570. */
  1571. var configureBoneTransformation = function (node) {
  1572. var mat = null;
  1573. if (node.translation || node.rotation || node.scale) {
  1574. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  1575. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  1576. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  1577. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  1578. }
  1579. else {
  1580. mat = BABYLON.Matrix.FromArray(node.matrix);
  1581. }
  1582. return mat;
  1583. };
  1584. /**
  1585. * Returns the parent bone
  1586. */
  1587. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  1588. // Try to find
  1589. for (var i = 0; i < newSkeleton.bones.length; i++) {
  1590. if (newSkeleton.bones[i].name === jointName) {
  1591. return newSkeleton.bones[i];
  1592. }
  1593. }
  1594. // Not found, search in gltf nodes
  1595. var nodes = gltfRuntime.nodes;
  1596. for (var nde in nodes) {
  1597. var node = nodes[nde];
  1598. if (!node.jointName) {
  1599. continue;
  1600. }
  1601. var children = node.children;
  1602. for (var i = 0; i < children.length; i++) {
  1603. var child = gltfRuntime.nodes[children[i]];
  1604. if (!child.jointName) {
  1605. continue;
  1606. }
  1607. if (child.jointName === jointName) {
  1608. var mat = configureBoneTransformation(node);
  1609. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  1610. bone.id = nde;
  1611. return bone;
  1612. }
  1613. }
  1614. }
  1615. return null;
  1616. };
  1617. /**
  1618. * Returns the appropriate root node
  1619. */
  1620. var getNodeToRoot = function (nodesToRoot, id) {
  1621. for (var i = 0; i < nodesToRoot.length; i++) {
  1622. var nodeToRoot = nodesToRoot[i];
  1623. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  1624. var child = nodeToRoot.node.children[j];
  1625. if (child === id) {
  1626. return nodeToRoot.bone;
  1627. }
  1628. }
  1629. }
  1630. return null;
  1631. };
  1632. /**
  1633. * Returns the node with the joint name
  1634. */
  1635. var getJointNode = function (gltfRuntime, jointName) {
  1636. var nodes = gltfRuntime.nodes;
  1637. var node = nodes[jointName];
  1638. if (node) {
  1639. return {
  1640. node: node,
  1641. id: jointName
  1642. };
  1643. }
  1644. for (var nde in nodes) {
  1645. node = nodes[nde];
  1646. if (node.jointName === jointName) {
  1647. return {
  1648. node: node,
  1649. id: nde
  1650. };
  1651. }
  1652. }
  1653. return null;
  1654. };
  1655. /**
  1656. * Checks if a nodes is in joints
  1657. */
  1658. var nodeIsInJoints = function (skins, id) {
  1659. for (var i = 0; i < skins.jointNames.length; i++) {
  1660. if (skins.jointNames[i] === id) {
  1661. return true;
  1662. }
  1663. }
  1664. return false;
  1665. };
  1666. /**
  1667. * Fills the nodes to root for bones and builds hierarchy
  1668. */
  1669. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  1670. // Creates nodes for root
  1671. for (var nde in gltfRuntime.nodes) {
  1672. var node = gltfRuntime.nodes[nde];
  1673. var id = nde;
  1674. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  1675. continue;
  1676. }
  1677. // Create node to root bone
  1678. var mat = configureBoneTransformation(node);
  1679. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  1680. bone.id = id;
  1681. nodesToRoot.push({ bone: bone, node: node, id: id });
  1682. }
  1683. // Parenting
  1684. for (var i = 0; i < nodesToRoot.length; i++) {
  1685. var nodeToRoot = nodesToRoot[i];
  1686. var children = nodeToRoot.node.children;
  1687. for (var j = 0; j < children.length; j++) {
  1688. var child = null;
  1689. for (var k = 0; k < nodesToRoot.length; k++) {
  1690. if (nodesToRoot[k].id === children[j]) {
  1691. child = nodesToRoot[k];
  1692. break;
  1693. }
  1694. }
  1695. if (child) {
  1696. child.bone._parent = nodeToRoot.bone;
  1697. nodeToRoot.bone.children.push(child.bone);
  1698. }
  1699. }
  1700. }
  1701. };
  1702. var printMat = function (m) {
  1703. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  1704. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  1705. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  1706. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  1707. };
  1708. /**
  1709. * Imports a skeleton
  1710. */
  1711. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  1712. if (!newSkeleton) {
  1713. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  1714. }
  1715. if (!skins.babylonSkeleton) {
  1716. return newSkeleton;
  1717. }
  1718. // Matrices
  1719. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  1720. var buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1721. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  1722. // Find the root bones
  1723. var nodesToRoot = [];
  1724. var nodesToRootToAdd = [];
  1725. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  1726. newSkeleton.bones = [];
  1727. // Joints
  1728. for (var i = 0; i < skins.jointNames.length; i++) {
  1729. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1730. var node = jointNode.node;
  1731. if (!node) {
  1732. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  1733. continue;
  1734. }
  1735. var id = jointNode.id;
  1736. // Optimize, if the bone already exists...
  1737. var existingBone = gltfRuntime.scene.getBoneByID(id);
  1738. if (existingBone) {
  1739. newSkeleton.bones.push(existingBone);
  1740. continue;
  1741. }
  1742. // Search for parent bone
  1743. var foundBone = false;
  1744. var parentBone = null;
  1745. for (var j = 0; j < i; j++) {
  1746. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  1747. if (!joint) {
  1748. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  1749. continue;
  1750. }
  1751. var children = joint.children;
  1752. if (!children) {
  1753. continue;
  1754. }
  1755. foundBone = false;
  1756. for (var k = 0; k < children.length; k++) {
  1757. if (children[k] === id) {
  1758. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  1759. foundBone = true;
  1760. break;
  1761. }
  1762. }
  1763. if (foundBone) {
  1764. break;
  1765. }
  1766. }
  1767. // Create bone
  1768. var mat = configureBoneTransformation(node);
  1769. if (!parentBone && nodesToRoot.length > 0) {
  1770. parentBone = getNodeToRoot(nodesToRoot, id);
  1771. if (parentBone) {
  1772. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  1773. nodesToRootToAdd.push(parentBone);
  1774. }
  1775. }
  1776. }
  1777. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  1778. bone.id = id;
  1779. }
  1780. // Polish
  1781. var bones = newSkeleton.bones;
  1782. newSkeleton.bones = [];
  1783. for (var i = 0; i < skins.jointNames.length; i++) {
  1784. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  1785. if (!jointNode) {
  1786. continue;
  1787. }
  1788. for (var j = 0; j < bones.length; j++) {
  1789. if (bones[j].id === jointNode.id) {
  1790. newSkeleton.bones.push(bones[j]);
  1791. break;
  1792. }
  1793. }
  1794. }
  1795. newSkeleton.prepare();
  1796. // Finish
  1797. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  1798. newSkeleton.bones.push(nodesToRootToAdd[i]);
  1799. }
  1800. return newSkeleton;
  1801. };
  1802. /**
  1803. * Imports a mesh and its geometries
  1804. */
  1805. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  1806. if (!newMesh) {
  1807. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  1808. newMesh.id = id;
  1809. }
  1810. if (!node.babylonNode) {
  1811. return newMesh;
  1812. }
  1813. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  1814. if (!newMesh.material) {
  1815. newMesh.material = multiMat;
  1816. }
  1817. var vertexData = new BABYLON.VertexData();
  1818. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  1819. var verticesStarts = [];
  1820. var verticesCounts = [];
  1821. var indexStarts = [];
  1822. var indexCounts = [];
  1823. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1824. var meshID = meshes[meshIndex];
  1825. var mesh = gltfRuntime.meshes[meshID];
  1826. if (!mesh) {
  1827. continue;
  1828. }
  1829. // Positions, normals and UVs
  1830. for (var i = 0; i < mesh.primitives.length; i++) {
  1831. // Temporary vertex data
  1832. var tempVertexData = new BABYLON.VertexData();
  1833. var primitive = mesh.primitives[i];
  1834. if (primitive.mode !== 4) {
  1835. // continue;
  1836. }
  1837. var attributes = primitive.attributes;
  1838. var accessor = null;
  1839. var buffer = null;
  1840. // Set positions, normal and uvs
  1841. for (var semantic in attributes) {
  1842. // Link accessor and buffer view
  1843. accessor = gltfRuntime.accessors[attributes[semantic]];
  1844. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1845. if (semantic === "NORMAL") {
  1846. tempVertexData.normals = new Float32Array(buffer.length);
  1847. tempVertexData.normals.set(buffer);
  1848. }
  1849. else if (semantic === "POSITION") {
  1850. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  1851. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  1852. for (var j = 0; j < buffer.length; j += 4) {
  1853. tempVertexData.positions[j] = buffer[j];
  1854. tempVertexData.positions[j + 1] = buffer[j + 1];
  1855. tempVertexData.positions[j + 2] = buffer[j + 2];
  1856. }
  1857. }
  1858. else {
  1859. tempVertexData.positions = new Float32Array(buffer.length);
  1860. tempVertexData.positions.set(buffer);
  1861. }
  1862. verticesCounts.push(tempVertexData.positions.length);
  1863. }
  1864. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  1865. var channel = Number(semantic.split("_")[1]);
  1866. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  1867. var uvs = new Float32Array(buffer.length);
  1868. uvs.set(buffer);
  1869. normalizeUVs(uvs);
  1870. tempVertexData.set(uvs, uvKind);
  1871. }
  1872. else if (semantic === "JOINT") {
  1873. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  1874. tempVertexData.matricesIndices.set(buffer);
  1875. }
  1876. else if (semantic === "WEIGHT") {
  1877. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  1878. tempVertexData.matricesWeights.set(buffer);
  1879. }
  1880. else if (semantic === "COLOR") {
  1881. tempVertexData.colors = new Float32Array(buffer.length);
  1882. tempVertexData.colors.set(buffer);
  1883. }
  1884. }
  1885. // Indices
  1886. accessor = gltfRuntime.accessors[primitive.indices];
  1887. if (accessor) {
  1888. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1889. tempVertexData.indices = new Int32Array(buffer.length);
  1890. tempVertexData.indices.set(buffer);
  1891. indexCounts.push(tempVertexData.indices.length);
  1892. }
  1893. else {
  1894. // Set indices on the fly
  1895. var indices = [];
  1896. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  1897. indices.push(j);
  1898. }
  1899. tempVertexData.indices = new Int32Array(indices);
  1900. indexCounts.push(tempVertexData.indices.length);
  1901. }
  1902. vertexData.merge(tempVertexData);
  1903. tempVertexData = undefined;
  1904. // Sub material
  1905. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  1906. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  1907. // Update vertices start and index start
  1908. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  1909. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  1910. }
  1911. }
  1912. // Apply geometry
  1913. geometry.setAllVerticesData(vertexData, false);
  1914. newMesh.computeWorldMatrix(true);
  1915. // Apply submeshes
  1916. newMesh.subMeshes = [];
  1917. var index = 0;
  1918. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1919. var meshID = meshes[meshIndex];
  1920. var mesh = gltfRuntime.meshes[meshID];
  1921. if (!mesh) {
  1922. continue;
  1923. }
  1924. for (var i = 0; i < mesh.primitives.length; i++) {
  1925. if (mesh.primitives[i].mode !== 4) {
  1926. //continue;
  1927. }
  1928. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  1929. index++;
  1930. }
  1931. }
  1932. // Finish
  1933. return newMesh;
  1934. };
  1935. /**
  1936. * Configure node transformation from position, rotation and scaling
  1937. */
  1938. var configureNode = function (newNode, position, rotation, scaling) {
  1939. if (newNode.position) {
  1940. newNode.position = position;
  1941. }
  1942. if (newNode.rotationQuaternion || newNode.rotation) {
  1943. newNode.rotationQuaternion = rotation;
  1944. }
  1945. if (newNode.scaling) {
  1946. newNode.scaling = scaling;
  1947. }
  1948. };
  1949. /**
  1950. * Configures node from transformation matrix
  1951. */
  1952. var configureNodeFromMatrix = function (newNode, node, parent) {
  1953. if (node.matrix) {
  1954. var position = new BABYLON.Vector3(0, 0, 0);
  1955. var rotation = new BABYLON.Quaternion();
  1956. var scaling = new BABYLON.Vector3(0, 0, 0);
  1957. var mat = BABYLON.Matrix.FromArray(node.matrix);
  1958. mat.decompose(scaling, rotation, position);
  1959. configureNode(newNode, position, rotation, scaling);
  1960. }
  1961. else {
  1962. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  1963. }
  1964. newNode.computeWorldMatrix(true);
  1965. };
  1966. /**
  1967. * Imports a node
  1968. */
  1969. var importNode = function (gltfRuntime, node, id, parent) {
  1970. var lastNode = null;
  1971. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  1972. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  1973. return null;
  1974. }
  1975. }
  1976. // Meshes
  1977. if (node.skin) {
  1978. if (node.meshes) {
  1979. var skin = gltfRuntime.skins[node.skin];
  1980. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  1981. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  1982. if (newMesh.skeleton === null) {
  1983. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  1984. if (!skin.babylonSkeleton) {
  1985. skin.babylonSkeleton = newMesh.skeleton;
  1986. }
  1987. }
  1988. lastNode = newMesh;
  1989. }
  1990. }
  1991. else if (node.meshes) {
  1992. /**
  1993. * Improve meshes property
  1994. */
  1995. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  1996. lastNode = newMesh;
  1997. }
  1998. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1999. var light = gltfRuntime.lights[node.light];
  2000. if (light) {
  2001. if (light.type === "ambient") {
  2002. var ambienLight = light[light.type];
  2003. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2004. hemiLight.name = node.name;
  2005. if (ambienLight.color) {
  2006. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  2007. }
  2008. lastNode = hemiLight;
  2009. }
  2010. else if (light.type === "directional") {
  2011. var directionalLight = light[light.type];
  2012. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2013. dirLight.name = node.name;
  2014. if (directionalLight.color) {
  2015. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  2016. }
  2017. lastNode = dirLight;
  2018. }
  2019. else if (light.type === "point") {
  2020. var pointLight = light[light.type];
  2021. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2022. ptLight.name = node.name;
  2023. if (pointLight.color) {
  2024. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  2025. }
  2026. lastNode = ptLight;
  2027. }
  2028. else if (light.type === "spot") {
  2029. var spotLight = light[light.type];
  2030. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  2031. spLight.name = node.name;
  2032. if (spotLight.color) {
  2033. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  2034. }
  2035. if (spotLight.fallOfAngle) {
  2036. spLight.angle = spotLight.fallOfAngle;
  2037. }
  2038. if (spotLight.fallOffExponent) {
  2039. spLight.exponent = spotLight.fallOffExponent;
  2040. }
  2041. lastNode = spLight;
  2042. }
  2043. }
  2044. }
  2045. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  2046. var camera = gltfRuntime.cameras[node.camera];
  2047. if (camera) {
  2048. if (camera.type === "orthographic") {
  2049. var orthographicCamera = camera[camera.type];
  2050. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2051. orthoCamera.name = node.name;
  2052. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  2053. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  2054. lastNode = orthoCamera;
  2055. }
  2056. else if (camera.type === "perspective") {
  2057. var perspectiveCamera = camera[camera.type];
  2058. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  2059. persCamera.name = node.name;
  2060. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  2061. if (!perspectiveCamera.aspectRatio) {
  2062. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  2063. }
  2064. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  2065. persCamera.maxZ = perspectiveCamera.zfar;
  2066. persCamera.minZ = perspectiveCamera.znear;
  2067. }
  2068. lastNode = persCamera;
  2069. }
  2070. }
  2071. }
  2072. // Empty node
  2073. if (!node.jointName) {
  2074. if (node.babylonNode) {
  2075. return node.babylonNode;
  2076. }
  2077. else if (lastNode === null) {
  2078. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  2079. node.babylonNode = dummy;
  2080. lastNode = dummy;
  2081. }
  2082. }
  2083. if (lastNode !== null) {
  2084. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  2085. configureNodeFromMatrix(lastNode, node, parent);
  2086. }
  2087. else {
  2088. var translation = node.translation || [0, 0, 0];
  2089. var rotation = node.rotation || [0, 0, 0, 1];
  2090. var scale = node.scale || [1, 1, 1];
  2091. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  2092. }
  2093. lastNode.updateCache(true);
  2094. node.babylonNode = lastNode;
  2095. }
  2096. return lastNode;
  2097. };
  2098. /**
  2099. * Traverses nodes and creates them
  2100. */
  2101. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  2102. var node = gltfRuntime.nodes[id];
  2103. var newNode = null;
  2104. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  2105. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  2106. meshIncluded = true;
  2107. }
  2108. else {
  2109. meshIncluded = false;
  2110. }
  2111. }
  2112. else {
  2113. meshIncluded = true;
  2114. }
  2115. if (!node.jointName && meshIncluded) {
  2116. newNode = importNode(gltfRuntime, node, id, parent);
  2117. if (newNode !== null) {
  2118. newNode.id = id;
  2119. newNode.parent = parent;
  2120. }
  2121. }
  2122. if (node.children) {
  2123. for (var i = 0; i < node.children.length; i++) {
  2124. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  2125. }
  2126. }
  2127. };
  2128. /**
  2129. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  2130. */
  2131. var postLoad = function (gltfRuntime) {
  2132. // Nodes
  2133. var currentScene = gltfRuntime.currentScene;
  2134. if (currentScene) {
  2135. for (var i = 0; i < currentScene.nodes.length; i++) {
  2136. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2137. }
  2138. }
  2139. else {
  2140. for (var thing in gltfRuntime.scenes) {
  2141. currentScene = gltfRuntime.scenes[thing];
  2142. for (var i = 0; i < currentScene.nodes.length; i++) {
  2143. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2144. }
  2145. }
  2146. }
  2147. // Set animations
  2148. loadAnimations(gltfRuntime);
  2149. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  2150. var skeleton = gltfRuntime.scene.skeletons[i];
  2151. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  2152. }
  2153. };
  2154. /**
  2155. * onBind shaderrs callback to set uniforms and matrices
  2156. */
  2157. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  2158. var materialValues = material.values || technique.parameters;
  2159. for (var unif in unTreatedUniforms) {
  2160. var uniform = unTreatedUniforms[unif];
  2161. var type = uniform.type;
  2162. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  2163. if (uniform.semantic && !uniform.source && !uniform.node) {
  2164. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  2165. }
  2166. else if (uniform.semantic && (uniform.source || uniform.node)) {
  2167. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  2168. if (source === null) {
  2169. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  2170. }
  2171. if (source === null) {
  2172. continue;
  2173. }
  2174. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  2175. }
  2176. }
  2177. else {
  2178. var value = materialValues[technique.uniforms[unif]];
  2179. if (!value) {
  2180. continue;
  2181. }
  2182. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  2183. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  2184. if (texture === null || texture === undefined) {
  2185. continue;
  2186. }
  2187. shaderMaterial.getEffect().setTexture(unif, texture);
  2188. }
  2189. else {
  2190. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  2191. }
  2192. }
  2193. }
  2194. onSuccess(shaderMaterial);
  2195. };
  2196. /**
  2197. * Prepare uniforms to send the only one time
  2198. * Loads the appropriate textures
  2199. */
  2200. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  2201. var materialValues = material.values || technique.parameters;
  2202. var techniqueUniforms = technique.uniforms;
  2203. /**
  2204. * Prepare values here (not matrices)
  2205. */
  2206. for (var unif in unTreatedUniforms) {
  2207. var uniform = unTreatedUniforms[unif];
  2208. var type = uniform.type;
  2209. var value = materialValues[techniqueUniforms[unif]];
  2210. if (value === undefined) {
  2211. // In case the value is the same for all materials
  2212. value = uniform.value;
  2213. }
  2214. if (!value) {
  2215. continue;
  2216. }
  2217. var onLoadTexture = function (uniformName) {
  2218. return function (texture) {
  2219. if (uniform.value) {
  2220. // Static uniform
  2221. shaderMaterial.setTexture(uniformName, texture);
  2222. delete unTreatedUniforms[uniformName];
  2223. }
  2224. };
  2225. };
  2226. // Texture (sampler2D)
  2227. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  2228. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  2229. }
  2230. else {
  2231. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  2232. // Static uniform
  2233. delete unTreatedUniforms[unif];
  2234. }
  2235. }
  2236. }
  2237. };
  2238. /**
  2239. * Shader compilation failed
  2240. */
  2241. var onShaderCompileError = function (program, shaderMaterial, onError) {
  2242. return function (effect, error) {
  2243. shaderMaterial.dispose(true);
  2244. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  2245. };
  2246. };
  2247. /**
  2248. * Shader compilation success
  2249. */
  2250. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  2251. return function (_) {
  2252. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  2253. shaderMaterial.onBind = function (mesh) {
  2254. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  2255. };
  2256. };
  2257. };
  2258. /**
  2259. * Returns the appropriate uniform if already handled by babylon
  2260. */
  2261. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  2262. for (var unif in technique.uniforms) {
  2263. var uniform = technique.uniforms[unif];
  2264. var uniformParameter = technique.parameters[uniform];
  2265. if (tokenizer.currentIdentifier === unif) {
  2266. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  2267. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  2268. if (transformIndex !== -1) {
  2269. delete unTreatedUniforms[unif];
  2270. return babylonTransforms[transformIndex];
  2271. }
  2272. }
  2273. }
  2274. }
  2275. return tokenizer.currentIdentifier;
  2276. };
  2277. /**
  2278. * All shaders loaded. Create materials one by one
  2279. */
  2280. var importMaterials = function (gltfRuntime) {
  2281. // Create materials
  2282. for (var mat in gltfRuntime.materials) {
  2283. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  2284. }
  2285. };
  2286. /**
  2287. * Implementation of the base glTF spec
  2288. */
  2289. var GLTFLoaderBase = (function () {
  2290. function GLTFLoaderBase() {
  2291. }
  2292. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  2293. var gltfRuntime = {
  2294. extensions: {},
  2295. accessors: {},
  2296. buffers: {},
  2297. bufferViews: {},
  2298. meshes: {},
  2299. lights: {},
  2300. cameras: {},
  2301. nodes: {},
  2302. images: {},
  2303. textures: {},
  2304. shaders: {},
  2305. programs: {},
  2306. samplers: {},
  2307. techniques: {},
  2308. materials: {},
  2309. animations: {},
  2310. skins: {},
  2311. extensionsUsed: [],
  2312. scenes: {},
  2313. buffersCount: 0,
  2314. shaderscount: 0,
  2315. scene: scene,
  2316. rootUrl: rootUrl,
  2317. loadedBufferCount: 0,
  2318. loadedBufferViews: {},
  2319. loadedShaderCount: 0,
  2320. importOnlyMeshes: false,
  2321. dummyNodes: []
  2322. };
  2323. // Parse
  2324. if (parsedData.extensions) {
  2325. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  2326. }
  2327. if (parsedData.extensionsUsed) {
  2328. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  2329. }
  2330. if (parsedData.buffers) {
  2331. parseBuffers(parsedData.buffers, gltfRuntime);
  2332. }
  2333. if (parsedData.bufferViews) {
  2334. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  2335. }
  2336. if (parsedData.accessors) {
  2337. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  2338. }
  2339. if (parsedData.meshes) {
  2340. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  2341. }
  2342. if (parsedData.lights) {
  2343. parseObject(parsedData.lights, "lights", gltfRuntime);
  2344. }
  2345. if (parsedData.cameras) {
  2346. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  2347. }
  2348. if (parsedData.nodes) {
  2349. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  2350. }
  2351. if (parsedData.images) {
  2352. parseObject(parsedData.images, "images", gltfRuntime);
  2353. }
  2354. if (parsedData.textures) {
  2355. parseObject(parsedData.textures, "textures", gltfRuntime);
  2356. }
  2357. if (parsedData.shaders) {
  2358. parseShaders(parsedData.shaders, gltfRuntime);
  2359. }
  2360. if (parsedData.programs) {
  2361. parseObject(parsedData.programs, "programs", gltfRuntime);
  2362. }
  2363. if (parsedData.samplers) {
  2364. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  2365. }
  2366. if (parsedData.techniques) {
  2367. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  2368. }
  2369. if (parsedData.materials) {
  2370. parseObject(parsedData.materials, "materials", gltfRuntime);
  2371. }
  2372. if (parsedData.animations) {
  2373. parseObject(parsedData.animations, "animations", gltfRuntime);
  2374. }
  2375. if (parsedData.skins) {
  2376. parseObject(parsedData.skins, "skins", gltfRuntime);
  2377. }
  2378. if (parsedData.scenes) {
  2379. gltfRuntime.scenes = parsedData.scenes;
  2380. }
  2381. if (parsedData.scene && parsedData.scenes) {
  2382. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  2383. }
  2384. return gltfRuntime;
  2385. };
  2386. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2387. var buffer = gltfRuntime.buffers[id];
  2388. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  2389. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  2390. }
  2391. else {
  2392. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, function (request) {
  2393. onError(request.status + " " + request.statusText);
  2394. });
  2395. }
  2396. };
  2397. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2398. var texture = gltfRuntime.textures[id];
  2399. if (!texture || !texture.source) {
  2400. onError(null);
  2401. return;
  2402. }
  2403. if (texture.babylonTexture) {
  2404. onSuccess(null);
  2405. return;
  2406. }
  2407. var source = gltfRuntime.images[texture.source];
  2408. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  2409. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  2410. }
  2411. else {
  2412. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, function (request) {
  2413. onError(request.status + " " + request.statusText);
  2414. });
  2415. }
  2416. };
  2417. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2418. var texture = gltfRuntime.textures[id];
  2419. if (texture.babylonTexture) {
  2420. onSuccess(texture.babylonTexture);
  2421. return;
  2422. }
  2423. var sampler = gltfRuntime.samplers[texture.sampler];
  2424. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  2425. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  2426. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  2427. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  2428. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2429. var blob = new Blob([buffer]);
  2430. var blobURL = URL.createObjectURL(blob);
  2431. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  2432. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  2433. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  2434. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  2435. newTexture.name = id;
  2436. texture.babylonTexture = newTexture;
  2437. onSuccess(newTexture);
  2438. };
  2439. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2440. var shader = gltfRuntime.shaders[id];
  2441. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  2442. var shaderString = atob(shader.uri.split(",")[1]);
  2443. onSuccess(shaderString);
  2444. }
  2445. else {
  2446. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, function (request) {
  2447. onError(request.status + " " + request.statusText);
  2448. });
  2449. }
  2450. };
  2451. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2452. var material = gltfRuntime.materials[id];
  2453. var technique = gltfRuntime.techniques[material.technique];
  2454. if (!technique) {
  2455. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2456. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  2457. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2458. onSuccess(defaultMaterial);
  2459. return;
  2460. }
  2461. var program = gltfRuntime.programs[technique.program];
  2462. var states = technique.states;
  2463. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  2464. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  2465. var newVertexShader = "";
  2466. var newPixelShader = "";
  2467. var vertexTokenizer = new Tokenizer(vertexShader);
  2468. var pixelTokenizer = new Tokenizer(pixelShader);
  2469. var unTreatedUniforms = {};
  2470. var uniforms = [];
  2471. var attributes = [];
  2472. var samplers = [];
  2473. // Fill uniform, sampler2D and attributes
  2474. for (var unif in technique.uniforms) {
  2475. var uniform = technique.uniforms[unif];
  2476. var uniformParameter = technique.parameters[uniform];
  2477. unTreatedUniforms[unif] = uniformParameter;
  2478. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  2479. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  2480. if (transformIndex !== -1) {
  2481. uniforms.push(babylonTransforms[transformIndex]);
  2482. delete unTreatedUniforms[unif];
  2483. }
  2484. else {
  2485. uniforms.push(unif);
  2486. }
  2487. }
  2488. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  2489. samplers.push(unif);
  2490. }
  2491. else {
  2492. uniforms.push(unif);
  2493. }
  2494. }
  2495. for (var attr in technique.attributes) {
  2496. var attribute = technique.attributes[attr];
  2497. var attributeParameter = technique.parameters[attribute];
  2498. if (attributeParameter.semantic) {
  2499. attributes.push(getAttribute(attributeParameter));
  2500. }
  2501. }
  2502. // Configure vertex shader
  2503. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  2504. var tokenType = vertexTokenizer.currentToken;
  2505. if (tokenType !== ETokenType.IDENTIFIER) {
  2506. newVertexShader += vertexTokenizer.currentString;
  2507. continue;
  2508. }
  2509. var foundAttribute = false;
  2510. for (var attr in technique.attributes) {
  2511. var attribute = technique.attributes[attr];
  2512. var attributeParameter = technique.parameters[attribute];
  2513. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  2514. newVertexShader += getAttribute(attributeParameter);
  2515. foundAttribute = true;
  2516. break;
  2517. }
  2518. }
  2519. if (foundAttribute) {
  2520. continue;
  2521. }
  2522. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  2523. }
  2524. // Configure pixel shader
  2525. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  2526. var tokenType = pixelTokenizer.currentToken;
  2527. if (tokenType !== ETokenType.IDENTIFIER) {
  2528. newPixelShader += pixelTokenizer.currentString;
  2529. continue;
  2530. }
  2531. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  2532. }
  2533. // Create shader material
  2534. var shaderPath = {
  2535. vertex: program.vertexShader + id,
  2536. fragment: program.fragmentShader + id
  2537. };
  2538. var options = {
  2539. attributes: attributes,
  2540. uniforms: uniforms,
  2541. samplers: samplers,
  2542. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  2543. };
  2544. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  2545. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  2546. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  2547. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  2548. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  2549. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2550. if (states && states.functions) {
  2551. var functions = states.functions;
  2552. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  2553. shaderMaterial.backFaceCulling = false;
  2554. }
  2555. var blendFunc = functions.blendFuncSeparate;
  2556. if (blendFunc) {
  2557. 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) {
  2558. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  2559. }
  2560. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2561. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  2562. }
  2563. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2564. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  2565. }
  2566. 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) {
  2567. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  2568. }
  2569. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  2570. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  2571. }
  2572. 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) {
  2573. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  2574. }
  2575. }
  2576. }
  2577. };
  2578. return GLTFLoaderBase;
  2579. }());
  2580. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  2581. /**
  2582. * glTF V1 Loader
  2583. */
  2584. var GLTFLoader = (function () {
  2585. function GLTFLoader() {
  2586. }
  2587. GLTFLoader.RegisterExtension = function (extension) {
  2588. if (GLTFLoader.Extensions[extension.name]) {
  2589. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  2590. return;
  2591. }
  2592. GLTFLoader.Extensions[extension.name] = extension;
  2593. };
  2594. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  2595. var _this = this;
  2596. scene.useRightHandedSystem = true;
  2597. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  2598. gltfRuntime.importOnlyMeshes = true;
  2599. if (meshesNames === "") {
  2600. gltfRuntime.importMeshesNames = [];
  2601. }
  2602. else if (typeof meshesNames === "string") {
  2603. gltfRuntime.importMeshesNames = [meshesNames];
  2604. }
  2605. else if (meshesNames && !(meshesNames instanceof Array)) {
  2606. gltfRuntime.importMeshesNames = [meshesNames];
  2607. }
  2608. else {
  2609. gltfRuntime.importMeshesNames = [];
  2610. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  2611. }
  2612. // Create nodes
  2613. _this._createNodes(gltfRuntime);
  2614. var meshes = [];
  2615. var skeletons = [];
  2616. // Fill arrays of meshes and skeletons
  2617. for (var nde in gltfRuntime.nodes) {
  2618. var node = gltfRuntime.nodes[nde];
  2619. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  2620. meshes.push(node.babylonNode);
  2621. }
  2622. }
  2623. for (var skl in gltfRuntime.skins) {
  2624. var skin = gltfRuntime.skins[skl];
  2625. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  2626. skeletons.push(skin.babylonSkeleton);
  2627. }
  2628. }
  2629. // Load buffers, shaders, materials, etc.
  2630. _this._loadBuffersAsync(gltfRuntime, function () {
  2631. _this._loadShadersAsync(gltfRuntime, function () {
  2632. importMaterials(gltfRuntime);
  2633. postLoad(gltfRuntime);
  2634. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  2635. onSuccess(meshes, null, skeletons);
  2636. }
  2637. });
  2638. }, onProgress);
  2639. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  2640. onSuccess(meshes, null, skeletons);
  2641. }
  2642. }, onError);
  2643. return true;
  2644. };
  2645. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  2646. var _this = this;
  2647. scene.useRightHandedSystem = true;
  2648. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  2649. // Load runtime extensios
  2650. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  2651. // Create nodes
  2652. _this._createNodes(gltfRuntime);
  2653. // Load buffers, shaders, materials, etc.
  2654. _this._loadBuffersAsync(gltfRuntime, function () {
  2655. _this._loadShadersAsync(gltfRuntime, function () {
  2656. importMaterials(gltfRuntime);
  2657. postLoad(gltfRuntime);
  2658. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  2659. onSuccess();
  2660. }
  2661. });
  2662. });
  2663. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  2664. onSuccess();
  2665. }
  2666. }, onError);
  2667. }, onError);
  2668. };
  2669. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  2670. var hasShaders = false;
  2671. var processShader = function (sha, shader) {
  2672. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  2673. gltfRuntime.loadedShaderCount++;
  2674. if (shaderString) {
  2675. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  2676. }
  2677. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  2678. onload();
  2679. }
  2680. }, function () {
  2681. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  2682. });
  2683. };
  2684. for (var sha in gltfRuntime.shaders) {
  2685. hasShaders = true;
  2686. var shader = gltfRuntime.shaders[sha];
  2687. if (shader) {
  2688. processShader.bind(this, sha, shader)();
  2689. }
  2690. else {
  2691. BABYLON.Tools.Error("No shader named: " + sha);
  2692. }
  2693. }
  2694. if (!hasShaders) {
  2695. onload();
  2696. }
  2697. };
  2698. ;
  2699. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  2700. var hasBuffers = false;
  2701. var processBuffer = function (buf, buffer) {
  2702. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  2703. gltfRuntime.loadedBufferCount++;
  2704. if (bufferView) {
  2705. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  2706. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  2707. }
  2708. gltfRuntime.loadedBufferViews[buf] = bufferView;
  2709. }
  2710. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  2711. onLoad();
  2712. }
  2713. }, function () {
  2714. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  2715. });
  2716. };
  2717. for (var buf in gltfRuntime.buffers) {
  2718. hasBuffers = true;
  2719. var buffer = gltfRuntime.buffers[buf];
  2720. if (buffer) {
  2721. processBuffer.bind(this, buf, buffer)();
  2722. }
  2723. else {
  2724. BABYLON.Tools.Error("No buffer named: " + buf);
  2725. }
  2726. }
  2727. if (!hasBuffers) {
  2728. onLoad();
  2729. }
  2730. };
  2731. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  2732. var currentScene = gltfRuntime.currentScene;
  2733. if (currentScene) {
  2734. // Only one scene even if multiple scenes are defined
  2735. for (var i = 0; i < currentScene.nodes.length; i++) {
  2736. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2737. }
  2738. }
  2739. else {
  2740. // Load all scenes
  2741. for (var thing in gltfRuntime.scenes) {
  2742. currentScene = gltfRuntime.scenes[thing];
  2743. for (var i = 0; i < currentScene.nodes.length; i++) {
  2744. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2745. }
  2746. }
  2747. }
  2748. };
  2749. return GLTFLoader;
  2750. }());
  2751. GLTFLoader.Extensions = {};
  2752. GLTF1.GLTFLoader = GLTFLoader;
  2753. ;
  2754. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  2755. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2756. })(BABYLON || (BABYLON = {}));
  2757. //# sourceMappingURL=babylon.glTFLoader.js.map
  2758. var BABYLON;
  2759. (function (BABYLON) {
  2760. var GLTF1;
  2761. (function (GLTF1) {
  2762. /**
  2763. * Utils functions for GLTF
  2764. */
  2765. var GLTFUtils = (function () {
  2766. function GLTFUtils() {
  2767. }
  2768. /**
  2769. * Sets the given "parameter" matrix
  2770. * @param scene: the {BABYLON.Scene} object
  2771. * @param source: the source node where to pick the matrix
  2772. * @param parameter: the GLTF technique parameter
  2773. * @param uniformName: the name of the shader's uniform
  2774. * @param shaderMaterial: the shader material
  2775. */
  2776. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  2777. var mat = null;
  2778. if (parameter.semantic === "MODEL") {
  2779. mat = source.getWorldMatrix();
  2780. }
  2781. else if (parameter.semantic === "PROJECTION") {
  2782. mat = scene.getProjectionMatrix();
  2783. }
  2784. else if (parameter.semantic === "VIEW") {
  2785. mat = scene.getViewMatrix();
  2786. }
  2787. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  2788. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  2789. }
  2790. else if (parameter.semantic === "MODELVIEW") {
  2791. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  2792. }
  2793. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  2794. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  2795. }
  2796. else if (parameter.semantic === "MODELINVERSE") {
  2797. mat = source.getWorldMatrix().invert();
  2798. }
  2799. else if (parameter.semantic === "VIEWINVERSE") {
  2800. mat = scene.getViewMatrix().invert();
  2801. }
  2802. else if (parameter.semantic === "PROJECTIONINVERSE") {
  2803. mat = scene.getProjectionMatrix().invert();
  2804. }
  2805. else if (parameter.semantic === "MODELVIEWINVERSE") {
  2806. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  2807. }
  2808. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  2809. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  2810. }
  2811. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  2812. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  2813. }
  2814. else {
  2815. debugger;
  2816. }
  2817. switch (parameter.type) {
  2818. case GLTF1.EParameterType.FLOAT_MAT2:
  2819. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  2820. break;
  2821. case GLTF1.EParameterType.FLOAT_MAT3:
  2822. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  2823. break;
  2824. case GLTF1.EParameterType.FLOAT_MAT4:
  2825. shaderMaterial.setMatrix(uniformName, mat);
  2826. break;
  2827. default: break;
  2828. }
  2829. };
  2830. /**
  2831. * Sets the given "parameter" matrix
  2832. * @param shaderMaterial: the shader material
  2833. * @param uniform: the name of the shader's uniform
  2834. * @param value: the value of the uniform
  2835. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  2836. */
  2837. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  2838. switch (type) {
  2839. case GLTF1.EParameterType.FLOAT:
  2840. shaderMaterial.setFloat(uniform, value);
  2841. return true;
  2842. case GLTF1.EParameterType.FLOAT_VEC2:
  2843. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  2844. return true;
  2845. case GLTF1.EParameterType.FLOAT_VEC3:
  2846. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  2847. return true;
  2848. case GLTF1.EParameterType.FLOAT_VEC4:
  2849. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  2850. return true;
  2851. default: return false;
  2852. }
  2853. };
  2854. /**
  2855. * If the uri is a base64 string
  2856. * @param uri: the uri to test
  2857. */
  2858. GLTFUtils.IsBase64 = function (uri) {
  2859. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  2860. };
  2861. /**
  2862. * Decode the base64 uri
  2863. * @param uri: the uri to decode
  2864. */
  2865. GLTFUtils.DecodeBase64 = function (uri) {
  2866. var decodedString = atob(uri.split(",")[1]);
  2867. var bufferLength = decodedString.length;
  2868. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  2869. for (var i = 0; i < bufferLength; i++) {
  2870. bufferView[i] = decodedString.charCodeAt(i);
  2871. }
  2872. return bufferView.buffer;
  2873. };
  2874. /**
  2875. * Returns the wrap mode of the texture
  2876. * @param mode: the mode value
  2877. */
  2878. GLTFUtils.GetWrapMode = function (mode) {
  2879. switch (mode) {
  2880. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2881. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2882. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2883. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2884. }
  2885. };
  2886. /**
  2887. * Returns the byte stride giving an accessor
  2888. * @param accessor: the GLTF accessor objet
  2889. */
  2890. GLTFUtils.GetByteStrideFromType = function (accessor) {
  2891. // Needs this function since "byteStride" isn't requiered in glTF format
  2892. var type = accessor.type;
  2893. switch (type) {
  2894. case "VEC2": return 2;
  2895. case "VEC3": return 3;
  2896. case "VEC4": return 4;
  2897. case "MAT2": return 4;
  2898. case "MAT3": return 9;
  2899. case "MAT4": return 16;
  2900. default: return 1;
  2901. }
  2902. };
  2903. /**
  2904. * Returns the texture filter mode giving a mode value
  2905. * @param mode: the filter mode value
  2906. */
  2907. GLTFUtils.GetTextureFilterMode = function (mode) {
  2908. switch (mode) {
  2909. case GLTF1.ETextureFilterType.LINEAR:
  2910. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  2911. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  2912. case GLTF1.ETextureFilterType.NEAREST:
  2913. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  2914. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2915. }
  2916. };
  2917. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  2918. var byteOffset = bufferView.byteOffset + byteOffset;
  2919. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  2920. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  2921. throw new Error("Buffer access is out of range");
  2922. }
  2923. var buffer = loadedBufferView.buffer;
  2924. byteOffset += loadedBufferView.byteOffset;
  2925. switch (componentType) {
  2926. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  2927. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  2928. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  2929. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  2930. default: return new Float32Array(buffer, byteOffset, byteLength);
  2931. }
  2932. };
  2933. /**
  2934. * Returns a buffer from its accessor
  2935. * @param gltfRuntime: the GLTF runtime
  2936. * @param accessor: the GLTF accessor
  2937. */
  2938. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  2939. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  2940. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  2941. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  2942. };
  2943. /**
  2944. * Decodes a buffer view into a string
  2945. * @param view: the buffer view
  2946. */
  2947. GLTFUtils.DecodeBufferToText = function (view) {
  2948. var result = "";
  2949. var length = view.byteLength;
  2950. for (var i = 0; i < length; ++i) {
  2951. result += String.fromCharCode(view[i]);
  2952. }
  2953. return result;
  2954. };
  2955. /**
  2956. * Returns the default material of gltf. Related to
  2957. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  2958. * @param scene: the Babylon.js scene
  2959. */
  2960. GLTFUtils.GetDefaultMaterial = function (scene) {
  2961. if (!GLTFUtils._DefaultMaterial) {
  2962. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2963. "precision highp float;",
  2964. "",
  2965. "uniform mat4 worldView;",
  2966. "uniform mat4 projection;",
  2967. "",
  2968. "attribute vec3 position;",
  2969. "",
  2970. "void main(void)",
  2971. "{",
  2972. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2973. "}"
  2974. ].join("\n");
  2975. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2976. "precision highp float;",
  2977. "",
  2978. "uniform vec4 u_emission;",
  2979. "",
  2980. "void main(void)",
  2981. "{",
  2982. " gl_FragColor = u_emission;",
  2983. "}"
  2984. ].join("\n");
  2985. var shaderPath = {
  2986. vertex: "GLTFDefaultMaterial",
  2987. fragment: "GLTFDefaultMaterial"
  2988. };
  2989. var options = {
  2990. attributes: ["position"],
  2991. uniforms: ["worldView", "projection", "u_emission"],
  2992. samplers: [],
  2993. needAlphaBlending: false
  2994. };
  2995. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2996. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  2997. }
  2998. return GLTFUtils._DefaultMaterial;
  2999. };
  3000. return GLTFUtils;
  3001. }());
  3002. // The GLTF default material
  3003. GLTFUtils._DefaultMaterial = null;
  3004. GLTF1.GLTFUtils = GLTFUtils;
  3005. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3006. })(BABYLON || (BABYLON = {}));
  3007. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  3008. var BABYLON;
  3009. (function (BABYLON) {
  3010. var GLTF1;
  3011. (function (GLTF1) {
  3012. var GLTFLoaderExtension = (function () {
  3013. function GLTFLoaderExtension(name) {
  3014. this._name = name;
  3015. }
  3016. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  3017. get: function () {
  3018. return this._name;
  3019. },
  3020. enumerable: true,
  3021. configurable: true
  3022. });
  3023. /**
  3024. * Defines an override for loading the runtime
  3025. * Return true to stop further extensions from loading the runtime
  3026. */
  3027. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3028. return false;
  3029. };
  3030. /**
  3031. * Defines an onverride for creating gltf runtime
  3032. * Return true to stop further extensions from creating the runtime
  3033. */
  3034. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3035. return false;
  3036. };
  3037. /**
  3038. * Defines an override for loading buffers
  3039. * Return true to stop further extensions from loading this buffer
  3040. */
  3041. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  3042. return false;
  3043. };
  3044. /**
  3045. * Defines an override for loading texture buffers
  3046. * Return true to stop further extensions from loading this texture data
  3047. */
  3048. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3049. return false;
  3050. };
  3051. /**
  3052. * Defines an override for creating textures
  3053. * Return true to stop further extensions from loading this texture
  3054. */
  3055. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  3056. return false;
  3057. };
  3058. /**
  3059. * Defines an override for loading shader strings
  3060. * Return true to stop further extensions from loading this shader data
  3061. */
  3062. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3063. return false;
  3064. };
  3065. /**
  3066. * Defines an override for loading materials
  3067. * Return true to stop further extensions from loading this material
  3068. */
  3069. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3070. return false;
  3071. };
  3072. // ---------
  3073. // Utilities
  3074. // ---------
  3075. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3076. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3077. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  3078. }, function () {
  3079. setTimeout(function () {
  3080. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  3081. });
  3082. });
  3083. };
  3084. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3085. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3086. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  3087. }, function () {
  3088. setTimeout(function () {
  3089. onSuccess();
  3090. });
  3091. });
  3092. };
  3093. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  3094. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3095. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  3096. }, function () {
  3097. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  3098. });
  3099. };
  3100. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  3101. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  3102. };
  3103. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3104. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3105. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  3106. }, function () {
  3107. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  3108. });
  3109. };
  3110. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3111. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3112. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  3113. }, function () {
  3114. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  3115. });
  3116. };
  3117. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3118. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3119. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  3120. }, function () {
  3121. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  3122. });
  3123. };
  3124. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  3125. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  3126. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  3127. }, function () {
  3128. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  3129. });
  3130. };
  3131. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  3132. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  3133. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  3134. if (func(loaderExtension)) {
  3135. return;
  3136. }
  3137. }
  3138. defaultFunc();
  3139. };
  3140. return GLTFLoaderExtension;
  3141. }());
  3142. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  3143. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3144. })(BABYLON || (BABYLON = {}));
  3145. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  3146. var BABYLON;
  3147. (function (BABYLON) {
  3148. var GLTF1;
  3149. (function (GLTF1) {
  3150. var BinaryExtensionBufferName = "binary_glTF";
  3151. var EContentFormat;
  3152. (function (EContentFormat) {
  3153. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  3154. })(EContentFormat || (EContentFormat = {}));
  3155. ;
  3156. ;
  3157. ;
  3158. var GLTFBinaryExtension = (function (_super) {
  3159. __extends(GLTFBinaryExtension, _super);
  3160. function GLTFBinaryExtension() {
  3161. return _super.call(this, "KHR_binary_glTF") || this;
  3162. }
  3163. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3164. var extensionsUsed = data.json.extensionsUsed;
  3165. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  3166. return false;
  3167. }
  3168. this._bin = data.bin;
  3169. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  3170. return true;
  3171. };
  3172. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3173. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  3174. return false;
  3175. }
  3176. if (id !== BinaryExtensionBufferName) {
  3177. return false;
  3178. }
  3179. onSuccess(this._bin);
  3180. return true;
  3181. };
  3182. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  3183. var texture = gltfRuntime.textures[id];
  3184. var source = gltfRuntime.images[texture.source];
  3185. if (!source.extensions || !(this.name in source.extensions)) {
  3186. return false;
  3187. }
  3188. var sourceExt = source.extensions[this.name];
  3189. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  3190. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  3191. onSuccess(buffer);
  3192. return true;
  3193. };
  3194. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  3195. var shader = gltfRuntime.shaders[id];
  3196. if (!shader.extensions || !(this.name in shader.extensions)) {
  3197. return false;
  3198. }
  3199. var binaryExtensionShader = shader.extensions[this.name];
  3200. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  3201. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  3202. setTimeout(function () {
  3203. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  3204. onSuccess(shaderString);
  3205. });
  3206. return true;
  3207. };
  3208. return GLTFBinaryExtension;
  3209. }(GLTF1.GLTFLoaderExtension));
  3210. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  3211. var BinaryReader = (function () {
  3212. function BinaryReader(arrayBuffer) {
  3213. this._arrayBuffer = arrayBuffer;
  3214. this._dataView = new DataView(arrayBuffer);
  3215. this._byteOffset = 0;
  3216. }
  3217. BinaryReader.prototype.getUint32 = function () {
  3218. var value = this._dataView.getUint32(this._byteOffset, true);
  3219. this._byteOffset += 4;
  3220. return value;
  3221. };
  3222. BinaryReader.prototype.getUint8Array = function (length) {
  3223. if (!length) {
  3224. length = this._arrayBuffer.byteLength - this._byteOffset;
  3225. }
  3226. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  3227. this._byteOffset += length;
  3228. return value;
  3229. };
  3230. return BinaryReader;
  3231. }());
  3232. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  3233. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3234. })(BABYLON || (BABYLON = {}));
  3235. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  3236. var BABYLON;
  3237. (function (BABYLON) {
  3238. var GLTF1;
  3239. (function (GLTF1) {
  3240. ;
  3241. ;
  3242. ;
  3243. var GLTFMaterialsCommonExtension = (function (_super) {
  3244. __extends(GLTFMaterialsCommonExtension, _super);
  3245. function GLTFMaterialsCommonExtension() {
  3246. return _super.call(this, "KHR_materials_common") || this;
  3247. }
  3248. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  3249. if (!gltfRuntime.extensions)
  3250. return false;
  3251. var extension = gltfRuntime.extensions[this.name];
  3252. if (!extension)
  3253. return false;
  3254. // Create lights
  3255. var lights = extension.lights;
  3256. if (lights) {
  3257. for (var thing in lights) {
  3258. var light = lights[thing];
  3259. switch (light.type) {
  3260. case "ambient":
  3261. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  3262. var ambient = light.ambient;
  3263. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  3264. break;
  3265. case "point":
  3266. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  3267. var point = light.point;
  3268. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  3269. break;
  3270. case "directional":
  3271. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  3272. var directional = light.directional;
  3273. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  3274. break;
  3275. case "spot":
  3276. var spot = light.spot;
  3277. 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);
  3278. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  3279. break;
  3280. default:
  3281. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  3282. break;
  3283. }
  3284. }
  3285. }
  3286. return false;
  3287. };
  3288. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  3289. var material = gltfRuntime.materials[id];
  3290. if (!material || !material.extensions)
  3291. return false;
  3292. var extension = material.extensions[this.name];
  3293. if (!extension)
  3294. return false;
  3295. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  3296. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  3297. if (extension.technique === "CONSTANT") {
  3298. standardMaterial.disableLighting = true;
  3299. }
  3300. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  3301. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  3302. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  3303. // Ambient
  3304. if (typeof extension.values.ambient === "string") {
  3305. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  3306. }
  3307. else {
  3308. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  3309. }
  3310. // Diffuse
  3311. if (typeof extension.values.diffuse === "string") {
  3312. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  3313. }
  3314. else {
  3315. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  3316. }
  3317. // Emission
  3318. if (typeof extension.values.emission === "string") {
  3319. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  3320. }
  3321. else {
  3322. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  3323. }
  3324. // Specular
  3325. if (typeof extension.values.specular === "string") {
  3326. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  3327. }
  3328. else {
  3329. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  3330. }
  3331. return true;
  3332. };
  3333. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  3334. // Create buffer from texture url
  3335. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  3336. // Create texture from buffer
  3337. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  3338. }, onError);
  3339. };
  3340. return GLTFMaterialsCommonExtension;
  3341. }(GLTF1.GLTFLoaderExtension));
  3342. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  3343. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  3344. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  3345. })(BABYLON || (BABYLON = {}));
  3346. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  3347. var BABYLON;
  3348. (function (BABYLON) {
  3349. var GLTF2;
  3350. (function (GLTF2) {
  3351. /**
  3352. * Enums
  3353. */
  3354. var EComponentType;
  3355. (function (EComponentType) {
  3356. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  3357. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  3358. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  3359. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  3360. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  3361. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  3362. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  3363. var EMeshPrimitiveMode;
  3364. (function (EMeshPrimitiveMode) {
  3365. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  3366. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  3367. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  3368. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  3369. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  3370. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  3371. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  3372. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  3373. var ETextureMagFilter;
  3374. (function (ETextureMagFilter) {
  3375. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  3376. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  3377. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  3378. var ETextureMinFilter;
  3379. (function (ETextureMinFilter) {
  3380. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  3381. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  3382. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  3383. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  3384. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  3385. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  3386. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  3387. var ETextureWrapMode;
  3388. (function (ETextureWrapMode) {
  3389. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  3390. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  3391. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  3392. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  3393. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3394. })(BABYLON || (BABYLON = {}));
  3395. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  3396. var BABYLON;
  3397. (function (BABYLON) {
  3398. var GLTF2;
  3399. (function (GLTF2) {
  3400. var GLTFLoader = (function () {
  3401. function GLTFLoader(parent) {
  3402. this._renderReady = false;
  3403. this._disposed = false;
  3404. this._blockPendingTracking = false;
  3405. // Observable with boolean indicating success or error.
  3406. this._renderReadyObservable = new BABYLON.Observable();
  3407. // Count of pending work that needs to complete before the asset is rendered.
  3408. this._renderPendingCount = 0;
  3409. // Count of pending work that needs to complete before the loader is cleared.
  3410. this._loaderPendingCount = 0;
  3411. this._parent = parent;
  3412. }
  3413. GLTFLoader.RegisterExtension = function (extension) {
  3414. if (GLTFLoader.Extensions[extension.name]) {
  3415. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  3416. return;
  3417. }
  3418. GLTFLoader.Extensions[extension.name] = extension;
  3419. // Keep the order of registration so that extensions registered first are called first.
  3420. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  3421. };
  3422. Object.defineProperty(GLTFLoader.prototype, "gltf", {
  3423. get: function () {
  3424. return this._gltf;
  3425. },
  3426. enumerable: true,
  3427. configurable: true
  3428. });
  3429. Object.defineProperty(GLTFLoader.prototype, "babylonScene", {
  3430. get: function () {
  3431. return this._babylonScene;
  3432. },
  3433. enumerable: true,
  3434. configurable: true
  3435. });
  3436. GLTFLoader.prototype.executeWhenRenderReady = function (func) {
  3437. if (this._renderReady) {
  3438. func();
  3439. }
  3440. else {
  3441. this._renderReadyObservable.add(func);
  3442. }
  3443. };
  3444. GLTFLoader.prototype.dispose = function () {
  3445. if (this._disposed) {
  3446. return;
  3447. }
  3448. this._disposed = true;
  3449. // Revoke object urls created during load
  3450. if (this._gltf.textures) {
  3451. this._gltf.textures.forEach(function (texture) {
  3452. if (texture.url) {
  3453. URL.revokeObjectURL(texture.url);
  3454. }
  3455. });
  3456. }
  3457. this._gltf = undefined;
  3458. this._babylonScene = undefined;
  3459. this._rootUrl = undefined;
  3460. this._defaultMaterial = undefined;
  3461. this._successCallback = undefined;
  3462. this._errorCallback = undefined;
  3463. this._renderReady = false;
  3464. this._renderReadyObservable.clear();
  3465. this._renderPendingCount = 0;
  3466. this._loaderPendingCount = 0;
  3467. };
  3468. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  3469. var _this = this;
  3470. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  3471. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  3472. }, onProgress, onError);
  3473. };
  3474. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  3475. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  3476. };
  3477. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  3478. this._loadData(data);
  3479. this._babylonScene = scene;
  3480. this._rootUrl = rootUrl;
  3481. this._successCallback = onSuccess;
  3482. this._progressCallback = onProgress;
  3483. this._errorCallback = onError;
  3484. this.addPendingData(this);
  3485. this._loadScene(nodeNames);
  3486. this._loadAnimations();
  3487. this.removePendingData(this);
  3488. };
  3489. GLTFLoader.prototype._onError = function (message) {
  3490. this._errorCallback(message);
  3491. this.dispose();
  3492. };
  3493. GLTFLoader.prototype._onProgress = function (event) {
  3494. this._progressCallback(event);
  3495. };
  3496. GLTFLoader.prototype._onRenderReady = function () {
  3497. switch (this._parent.coordinateSystemMode) {
  3498. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  3499. if (!this._babylonScene.useRightHandedSystem) {
  3500. this._addRightHandToLeftHandRootTransform();
  3501. }
  3502. break;
  3503. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  3504. // do nothing
  3505. break;
  3506. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  3507. this._babylonScene.useRightHandedSystem = true;
  3508. break;
  3509. default:
  3510. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  3511. break;
  3512. }
  3513. this._showMeshes();
  3514. this._startAnimations();
  3515. this._successCallback();
  3516. this._renderReadyObservable.notifyObservers(this);
  3517. };
  3518. GLTFLoader.prototype._onLoaderComplete = function () {
  3519. if (this._parent.onComplete) {
  3520. this._parent.onComplete();
  3521. }
  3522. };
  3523. GLTFLoader.prototype._onLoaderFirstLODComplete = function () {
  3524. if (this._parent.onFirstLODComplete) {
  3525. this._parent.onFirstLODComplete();
  3526. }
  3527. };
  3528. GLTFLoader.prototype._loadData = function (data) {
  3529. this._gltf = data.json;
  3530. var binaryBuffer;
  3531. var buffers = this._gltf.buffers;
  3532. if (buffers && buffers[0].uri === undefined) {
  3533. binaryBuffer = buffers[0];
  3534. }
  3535. if (data.bin) {
  3536. if (binaryBuffer) {
  3537. if (binaryBuffer.byteLength != data.bin.byteLength) {
  3538. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  3539. }
  3540. }
  3541. else {
  3542. BABYLON.Tools.Warn("Unexpected BIN chunk");
  3543. }
  3544. binaryBuffer.loadedData = data.bin;
  3545. }
  3546. };
  3547. GLTFLoader.prototype._addRightHandToLeftHandRootTransform = function () {
  3548. this._rootMesh = new BABYLON.Mesh("root", this._babylonScene);
  3549. this._rootMesh.isVisible = false;
  3550. this._rootMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  3551. this._rootMesh.rotation.y = Math.PI;
  3552. var nodes = this._gltf.nodes;
  3553. if (nodes) {
  3554. for (var i = 0; i < nodes.length; i++) {
  3555. var mesh = nodes[i].babylonMesh;
  3556. if (mesh && !mesh.parent) {
  3557. mesh.parent = this._rootMesh;
  3558. }
  3559. }
  3560. }
  3561. };
  3562. GLTFLoader.prototype._getMeshes = function () {
  3563. var meshes = [];
  3564. if (this._rootMesh) {
  3565. meshes.push(this._rootMesh);
  3566. }
  3567. var nodes = this._gltf.nodes;
  3568. if (nodes) {
  3569. nodes.forEach(function (node) {
  3570. if (node.babylonMesh) {
  3571. meshes.push(node.babylonMesh);
  3572. }
  3573. });
  3574. }
  3575. return meshes;
  3576. };
  3577. GLTFLoader.prototype._getSkeletons = function () {
  3578. var skeletons = [];
  3579. var skins = this._gltf.skins;
  3580. if (skins) {
  3581. skins.forEach(function (skin) {
  3582. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  3583. skeletons.push(skin.babylonSkeleton);
  3584. }
  3585. });
  3586. }
  3587. return skeletons;
  3588. };
  3589. GLTFLoader.prototype._getAnimationTargets = function () {
  3590. var targets = [];
  3591. var animations = this._gltf.animations;
  3592. if (animations) {
  3593. animations.forEach(function (animation) {
  3594. targets.push.apply(targets, animation.targets);
  3595. });
  3596. }
  3597. return targets;
  3598. };
  3599. GLTFLoader.prototype._showMeshes = function () {
  3600. this._getMeshes().forEach(function (mesh) { return mesh.isVisible = true; });
  3601. };
  3602. GLTFLoader.prototype._startAnimations = function () {
  3603. var _this = this;
  3604. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  3605. };
  3606. GLTFLoader.prototype._loadScene = function (nodeNames) {
  3607. var _this = this;
  3608. var scene = this._gltf.scenes[this._gltf.scene || 0];
  3609. var nodeIndices = scene.nodes;
  3610. this._traverseNodes(nodeIndices, function (node, index, parentNode) {
  3611. node.index = index;
  3612. node.parent = parentNode;
  3613. return true;
  3614. });
  3615. var materials = this._gltf.materials;
  3616. if (materials) {
  3617. materials.forEach(function (material, index) { return material.index = index; });
  3618. }
  3619. if (nodeNames) {
  3620. if (!(nodeNames instanceof Array)) {
  3621. nodeNames = [nodeNames];
  3622. }
  3623. var filteredNodeIndices = new Array();
  3624. this._traverseNodes(nodeIndices, function (node) {
  3625. if (nodeNames.indexOf(node.name) === -1) {
  3626. return true;
  3627. }
  3628. filteredNodeIndices.push(node.index);
  3629. return false;
  3630. });
  3631. nodeIndices = filteredNodeIndices;
  3632. }
  3633. this._traverseNodes(nodeIndices, function (node) { return _this._loadNode(node); });
  3634. };
  3635. GLTFLoader.prototype._loadNode = function (node) {
  3636. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  3637. node.babylonMesh.isVisible = false;
  3638. this._loadTransform(node);
  3639. if (node.mesh !== undefined) {
  3640. var mesh = this._gltf.meshes[node.mesh];
  3641. this._loadMesh(node, mesh);
  3642. }
  3643. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  3644. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  3645. node.babylonAnimationTargets.push(node.babylonMesh);
  3646. if (node.skin !== undefined) {
  3647. var skin = this._gltf.skins[node.skin];
  3648. skin.index = node.skin;
  3649. node.babylonMesh.skeleton = this._loadSkin(skin);
  3650. }
  3651. if (node.camera !== undefined) {
  3652. // TODO: handle cameras
  3653. }
  3654. return true;
  3655. };
  3656. GLTFLoader.prototype._loadMesh = function (node, mesh) {
  3657. var _this = this;
  3658. node.babylonMesh.name = mesh.name || node.babylonMesh.name;
  3659. var babylonMultiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  3660. node.babylonMesh.material = babylonMultiMaterial;
  3661. var geometry = new BABYLON.Geometry(node.babylonMesh.name, this._babylonScene, null, false, node.babylonMesh);
  3662. var vertexData = new BABYLON.VertexData();
  3663. vertexData.positions = [];
  3664. vertexData.indices = [];
  3665. var subMeshInfos = [];
  3666. var loadedPrimitives = 0;
  3667. var totalPrimitives = mesh.primitives.length;
  3668. var _loop_1 = function (i) {
  3669. var primitive = mesh.primitives[i];
  3670. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  3671. // TODO: handle other primitive modes
  3672. throw new Error("Not implemented");
  3673. }
  3674. this_1._createMorphTargets(node, mesh, primitive, node.babylonMesh);
  3675. this_1._loadVertexDataAsync(primitive, function (subVertexData) {
  3676. _this._loadMorphTargetsData(mesh, primitive, subVertexData, node.babylonMesh);
  3677. subMeshInfos.push({
  3678. materialIndex: i,
  3679. verticesStart: vertexData.positions.length,
  3680. verticesCount: subVertexData.positions.length,
  3681. indicesStart: vertexData.indices.length,
  3682. indicesCount: subVertexData.indices.length,
  3683. loadMaterial: function () {
  3684. if (primitive.material === undefined) {
  3685. babylonMultiMaterial.subMaterials[i] = _this._getDefaultMaterial();
  3686. }
  3687. else {
  3688. var material = _this._gltf.materials[primitive.material];
  3689. _this.loadMaterial(material, function (babylonMaterial, isNew) {
  3690. if (isNew && _this._parent.onMaterialLoaded) {
  3691. _this._parent.onMaterialLoaded(babylonMaterial);
  3692. }
  3693. if (_this._parent.onBeforeMaterialReadyAsync) {
  3694. _this.addLoaderPendingData(material);
  3695. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, babylonMultiMaterial.subMaterials[i] != null, function () {
  3696. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  3697. _this.removeLoaderPendingData(material);
  3698. });
  3699. }
  3700. else {
  3701. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  3702. }
  3703. });
  3704. }
  3705. }
  3706. });
  3707. vertexData.merge(subVertexData);
  3708. if (++loadedPrimitives === totalPrimitives) {
  3709. geometry.setAllVerticesData(vertexData, false);
  3710. subMeshInfos.forEach(function (info) { return info.loadMaterial(); });
  3711. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  3712. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  3713. node.babylonMesh.subMeshes = [];
  3714. subMeshInfos.forEach(function (info) { return new BABYLON.SubMesh(info.materialIndex, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, node.babylonMesh); });
  3715. }
  3716. });
  3717. };
  3718. var this_1 = this;
  3719. for (var i = 0; i < totalPrimitives; i++) {
  3720. _loop_1(i);
  3721. }
  3722. };
  3723. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  3724. var _this = this;
  3725. var attributes = primitive.attributes;
  3726. if (!attributes) {
  3727. this._onError("Primitive has no attributes");
  3728. return;
  3729. }
  3730. var vertexData = new BABYLON.VertexData();
  3731. var loadedAttributes = 0;
  3732. var totalAttributes = Object.keys(attributes).length;
  3733. var _loop_2 = function (semantic) {
  3734. accessor = this_2._gltf.accessors[attributes[semantic]];
  3735. this_2._loadAccessorAsync(accessor, function (data) {
  3736. switch (semantic) {
  3737. case "NORMAL":
  3738. vertexData.normals = data;
  3739. break;
  3740. case "POSITION":
  3741. vertexData.positions = data;
  3742. break;
  3743. case "TANGENT":
  3744. vertexData.tangents = data;
  3745. break;
  3746. case "TEXCOORD_0":
  3747. vertexData.uvs = data;
  3748. break;
  3749. case "TEXCOORD_1":
  3750. vertexData.uvs2 = data;
  3751. break;
  3752. case "JOINTS_0":
  3753. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  3754. break;
  3755. case "WEIGHTS_0":
  3756. vertexData.matricesWeights = data;
  3757. break;
  3758. case "COLOR_0":
  3759. vertexData.colors = data;
  3760. break;
  3761. default:
  3762. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  3763. break;
  3764. }
  3765. if (++loadedAttributes === totalAttributes) {
  3766. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  3767. if (indicesAccessor) {
  3768. _this._loadAccessorAsync(indicesAccessor, function (data) {
  3769. vertexData.indices = data;
  3770. onSuccess(vertexData);
  3771. });
  3772. }
  3773. else {
  3774. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  3775. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  3776. onSuccess(vertexData);
  3777. }
  3778. }
  3779. });
  3780. };
  3781. var this_2 = this, accessor;
  3782. for (var semantic in attributes) {
  3783. _loop_2(semantic);
  3784. }
  3785. };
  3786. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  3787. var targets = primitive.targets;
  3788. if (!targets) {
  3789. return;
  3790. }
  3791. if (!babylonMesh.morphTargetManager) {
  3792. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  3793. }
  3794. for (var index = 0; index < targets.length; index++) {
  3795. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  3796. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  3797. }
  3798. };
  3799. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  3800. var targets = primitive.targets;
  3801. if (!targets) {
  3802. return;
  3803. }
  3804. var _loop_3 = function () {
  3805. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  3806. attributes = targets[index];
  3807. var _loop_4 = function (semantic) {
  3808. accessor = this_3._gltf.accessors[attributes[semantic]];
  3809. this_3._loadAccessorAsync(accessor, function (data) {
  3810. if (accessor.name) {
  3811. babylonMorphTarget.name = accessor.name;
  3812. }
  3813. // glTF stores morph target information as deltas while babylon.js expects the final data.
  3814. // As a result we have to add the original data to the delta to calculate the final data.
  3815. var values = data;
  3816. switch (semantic) {
  3817. case "NORMAL":
  3818. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  3819. babylonMorphTarget.setNormals(values);
  3820. break;
  3821. case "POSITION":
  3822. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  3823. babylonMorphTarget.setPositions(values);
  3824. break;
  3825. case "TANGENT":
  3826. // Tangent data for morph targets is stored as xyz delta.
  3827. // The vertexData.tangent is stored as xyzw.
  3828. // So we need to skip every fourth vertexData.tangent.
  3829. for (var i = 0, j = 0; i < values.length; i++, j++) {
  3830. values[i] += vertexData.tangents[j];
  3831. if ((i + 1) % 3 == 0) {
  3832. j++;
  3833. }
  3834. }
  3835. babylonMorphTarget.setTangents(values);
  3836. break;
  3837. default:
  3838. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  3839. break;
  3840. }
  3841. });
  3842. };
  3843. for (var semantic in attributes) {
  3844. _loop_4(semantic);
  3845. }
  3846. };
  3847. var this_3 = this, attributes, accessor;
  3848. for (var index = 0; index < targets.length; index++) {
  3849. _loop_3();
  3850. }
  3851. };
  3852. GLTFLoader.prototype._loadTransform = function (node) {
  3853. var position = BABYLON.Vector3.Zero();
  3854. var rotation = BABYLON.Quaternion.Identity();
  3855. var scaling = BABYLON.Vector3.One();
  3856. if (node.matrix) {
  3857. var mat = BABYLON.Matrix.FromArray(node.matrix);
  3858. mat.decompose(scaling, rotation, position);
  3859. }
  3860. else {
  3861. if (node.translation)
  3862. position = BABYLON.Vector3.FromArray(node.translation);
  3863. if (node.rotation)
  3864. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  3865. if (node.scale)
  3866. scaling = BABYLON.Vector3.FromArray(node.scale);
  3867. }
  3868. node.babylonMesh.position = position;
  3869. node.babylonMesh.rotationQuaternion = rotation;
  3870. node.babylonMesh.scaling = scaling;
  3871. };
  3872. GLTFLoader.prototype._loadSkin = function (skin) {
  3873. var _this = this;
  3874. var skeletonId = "skeleton" + skin.index;
  3875. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  3876. if (skin.inverseBindMatrices === undefined) {
  3877. this._loadBones(skin, null);
  3878. }
  3879. else {
  3880. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  3881. this._loadAccessorAsync(accessor, function (data) {
  3882. _this._loadBones(skin, data);
  3883. });
  3884. }
  3885. return skin.babylonSkeleton;
  3886. };
  3887. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  3888. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  3889. node.babylonBones = node.babylonBones || {};
  3890. node.babylonBones[skin.index] = babylonBone;
  3891. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  3892. node.babylonAnimationTargets.push(babylonBone);
  3893. return babylonBone;
  3894. };
  3895. GLTFLoader.prototype._loadBones = function (skin, inverseBindMatrixData) {
  3896. var babylonBones = {};
  3897. for (var i = 0; i < skin.joints.length; i++) {
  3898. var node = this._gltf.nodes[skin.joints[i]];
  3899. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  3900. }
  3901. };
  3902. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  3903. var babylonBone = babylonBones[node.index];
  3904. if (babylonBone) {
  3905. return babylonBone;
  3906. }
  3907. var boneIndex = skin.joints.indexOf(node.index);
  3908. var baseMatrix = BABYLON.Matrix.Identity();
  3909. if (inverseBindMatrixData && boneIndex !== -1) {
  3910. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  3911. baseMatrix.invertToRef(baseMatrix);
  3912. }
  3913. var babylonParentBone;
  3914. if (node.index != skin.skeleton && node.parent) {
  3915. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  3916. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  3917. }
  3918. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  3919. babylonBones[node.index] = babylonBone;
  3920. return babylonBone;
  3921. };
  3922. GLTFLoader.prototype._getNodeMatrix = function (node) {
  3923. return node.matrix ?
  3924. BABYLON.Matrix.FromArray(node.matrix) :
  3925. 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());
  3926. };
  3927. GLTFLoader.prototype._traverseNodes = function (indices, action, parentNode) {
  3928. if (parentNode === void 0) { parentNode = null; }
  3929. for (var i = 0; i < indices.length; i++) {
  3930. this._traverseNode(indices[i], action, parentNode);
  3931. }
  3932. };
  3933. GLTFLoader.prototype._traverseNode = function (index, action, parentNode) {
  3934. if (parentNode === void 0) { parentNode = null; }
  3935. var node = this._gltf.nodes[index];
  3936. if (!action(node, index, parentNode)) {
  3937. return;
  3938. }
  3939. if (node.children) {
  3940. for (var i = 0; i < node.children.length; i++) {
  3941. this._traverseNode(node.children[i], action, node);
  3942. }
  3943. }
  3944. };
  3945. GLTFLoader.prototype._loadAnimations = function () {
  3946. var animations = this._gltf.animations;
  3947. if (!animations || animations.length === 0) {
  3948. return;
  3949. }
  3950. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  3951. var animation = animations[animationIndex];
  3952. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  3953. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  3954. }
  3955. }
  3956. };
  3957. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  3958. var channel = animation.channels[channelIndex];
  3959. var samplerIndex = channel.sampler;
  3960. var sampler = animation.samplers[samplerIndex];
  3961. var targetNode = this._gltf.nodes[channel.target.node];
  3962. if (!targetNode) {
  3963. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  3964. return;
  3965. }
  3966. var targetPath = {
  3967. "translation": "position",
  3968. "rotation": "rotationQuaternion",
  3969. "scale": "scaling",
  3970. "weights": "influence"
  3971. }[channel.target.path];
  3972. if (!targetPath) {
  3973. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  3974. return;
  3975. }
  3976. var animationType = {
  3977. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  3978. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  3979. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  3980. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  3981. }[targetPath];
  3982. var inputData;
  3983. var outputData;
  3984. var checkSuccess = function () {
  3985. if (!inputData || !outputData) {
  3986. return;
  3987. }
  3988. var outputBufferOffset = 0;
  3989. var getNextOutputValue = {
  3990. "position": function () {
  3991. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  3992. outputBufferOffset += 3;
  3993. return value;
  3994. },
  3995. "rotationQuaternion": function () {
  3996. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  3997. outputBufferOffset += 4;
  3998. return value;
  3999. },
  4000. "scaling": function () {
  4001. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  4002. outputBufferOffset += 3;
  4003. return value;
  4004. },
  4005. "influence": function () {
  4006. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  4007. var value = new Array(numTargets);
  4008. for (var i = 0; i < numTargets; i++) {
  4009. value[i] = outputData[outputBufferOffset++];
  4010. }
  4011. return value;
  4012. },
  4013. }[targetPath];
  4014. var getNextKey = {
  4015. "LINEAR": function (frameIndex) { return ({
  4016. frame: inputData[frameIndex],
  4017. value: getNextOutputValue()
  4018. }); },
  4019. "CUBICSPLINE": function (frameIndex) { return ({
  4020. frame: inputData[frameIndex],
  4021. inTangent: getNextOutputValue(),
  4022. value: getNextOutputValue(),
  4023. outTangent: getNextOutputValue()
  4024. }); },
  4025. }[sampler.interpolation];
  4026. var keys = new Array(inputData.length);
  4027. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  4028. keys[frameIndex] = getNextKey(frameIndex);
  4029. }
  4030. animation.targets = animation.targets || [];
  4031. if (targetPath === "influence") {
  4032. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  4033. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  4034. var morphTarget = morphTargetManager.getTarget(targetIndex);
  4035. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  4036. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  4037. babylonAnimation.setKeys(keys.map(function (key) { return ({
  4038. frame: key.frame,
  4039. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  4040. value: key.value[targetIndex],
  4041. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  4042. }); }));
  4043. morphTarget.animations.push(babylonAnimation);
  4044. animation.targets.push(morphTarget);
  4045. }
  4046. }
  4047. else {
  4048. var animationName = animation.name || "anim" + animationIndex;
  4049. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  4050. babylonAnimation.setKeys(keys);
  4051. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  4052. var target = targetNode.babylonAnimationTargets[i];
  4053. target.animations.push(babylonAnimation.clone());
  4054. animation.targets.push(target);
  4055. }
  4056. }
  4057. };
  4058. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  4059. inputData = data;
  4060. checkSuccess();
  4061. });
  4062. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  4063. outputData = data;
  4064. checkSuccess();
  4065. });
  4066. };
  4067. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  4068. var _this = this;
  4069. var buffer = this._gltf.buffers[index];
  4070. this.addPendingData(buffer);
  4071. if (buffer.loadedData) {
  4072. setTimeout(function () {
  4073. onSuccess(buffer.loadedData);
  4074. _this.removePendingData(buffer);
  4075. });
  4076. }
  4077. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  4078. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  4079. buffer.loadedData = new Uint8Array(data);
  4080. setTimeout(function () {
  4081. onSuccess(buffer.loadedData);
  4082. _this.removePendingData(buffer);
  4083. });
  4084. }
  4085. else if (buffer.loadedObservable) {
  4086. buffer.loadedObservable.add(function (buffer) {
  4087. onSuccess(buffer.loadedData);
  4088. _this.removePendingData(buffer);
  4089. });
  4090. }
  4091. else {
  4092. buffer.loadedObservable = new BABYLON.Observable();
  4093. buffer.loadedObservable.add(function (buffer) {
  4094. onSuccess(buffer.loadedData);
  4095. _this.removePendingData(buffer);
  4096. });
  4097. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  4098. buffer.loadedData = new Uint8Array(data);
  4099. buffer.loadedObservable.notifyObservers(buffer);
  4100. buffer.loadedObservable = null;
  4101. }, function (event) {
  4102. if (!_this._disposed) {
  4103. _this._onProgress(event);
  4104. }
  4105. }, this._babylonScene.database, true, function (request) {
  4106. if (!_this._disposed) {
  4107. _this._onError("Failed to load file '" + buffer.uri + "': " + request.status + " " + request.statusText);
  4108. _this.removePendingData(buffer);
  4109. }
  4110. });
  4111. }
  4112. };
  4113. GLTFLoader.prototype._buildInt8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  4114. if (!byteStride) {
  4115. return new Int8Array(buffer, byteOffset, byteLength);
  4116. }
  4117. var sourceBuffer = new Int8Array(buffer, byteOffset);
  4118. var targetBuffer = new Int8Array(byteLength);
  4119. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  4120. return targetBuffer;
  4121. };
  4122. GLTFLoader.prototype._buildUint8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  4123. if (!byteStride) {
  4124. return new Uint8Array(buffer, byteOffset, byteLength);
  4125. }
  4126. var sourceBuffer = new Uint8Array(buffer, byteOffset);
  4127. var targetBuffer = new Uint8Array(byteLength);
  4128. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  4129. return targetBuffer;
  4130. };
  4131. GLTFLoader.prototype._buildInt16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  4132. if (!byteStride) {
  4133. return new Int16Array(buffer, byteOffset, byteLength);
  4134. }
  4135. var sourceBuffer = new Int16Array(buffer, byteOffset);
  4136. var targetBuffer = new Int16Array(byteLength);
  4137. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  4138. return targetBuffer;
  4139. };
  4140. GLTFLoader.prototype._buildUint16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  4141. if (!byteStride) {
  4142. return new Uint16Array(buffer, byteOffset, byteLength);
  4143. }
  4144. var sourceBuffer = new Uint16Array(buffer, byteOffset);
  4145. var targetBuffer = new Uint16Array(byteLength);
  4146. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  4147. return targetBuffer;
  4148. };
  4149. GLTFLoader.prototype._buildUint32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  4150. if (!byteStride) {
  4151. return new Uint32Array(buffer, byteOffset, byteLength);
  4152. }
  4153. var sourceBuffer = new Uint32Array(buffer, byteOffset);
  4154. var targetBuffer = new Uint32Array(byteLength);
  4155. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  4156. return targetBuffer;
  4157. };
  4158. GLTFLoader.prototype._buildFloat32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  4159. if (!byteStride) {
  4160. return new Float32Array(buffer, byteOffset, byteLength);
  4161. }
  4162. var sourceBuffer = new Float32Array(buffer, byteOffset);
  4163. var targetBuffer = new Float32Array(byteLength);
  4164. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  4165. return targetBuffer;
  4166. };
  4167. GLTFLoader.prototype._extractInterleavedData = function (sourceBuffer, targetBuffer, bytePerComponent, stride, length) {
  4168. var tempIndex = 0;
  4169. var sourceIndex = 0;
  4170. var storageSize = bytePerComponent;
  4171. while (tempIndex < length) {
  4172. for (var cursor = 0; cursor < storageSize; cursor++) {
  4173. targetBuffer[tempIndex] = sourceBuffer[sourceIndex + cursor];
  4174. tempIndex++;
  4175. }
  4176. sourceIndex += stride;
  4177. }
  4178. };
  4179. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, bytePerComponent, componentType, onSuccess) {
  4180. var _this = this;
  4181. byteOffset += (bufferView.byteOffset || 0);
  4182. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  4183. if (byteOffset + byteLength > bufferData.byteLength) {
  4184. _this._onError("Buffer access is out of range");
  4185. return;
  4186. }
  4187. var buffer = bufferData.buffer;
  4188. byteOffset += bufferData.byteOffset;
  4189. var bufferViewData;
  4190. switch (componentType) {
  4191. case GLTF2.EComponentType.BYTE:
  4192. bufferViewData = _this._buildInt8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  4193. break;
  4194. case GLTF2.EComponentType.UNSIGNED_BYTE:
  4195. bufferViewData = _this._buildUint8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  4196. break;
  4197. case GLTF2.EComponentType.SHORT:
  4198. bufferViewData = _this._buildInt16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  4199. break;
  4200. case GLTF2.EComponentType.UNSIGNED_SHORT:
  4201. bufferViewData = _this._buildUint16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  4202. break;
  4203. case GLTF2.EComponentType.UNSIGNED_INT:
  4204. bufferViewData = _this._buildUint32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  4205. break;
  4206. case GLTF2.EComponentType.FLOAT:
  4207. bufferViewData = _this._buildFloat32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  4208. break;
  4209. default:
  4210. _this._onError("Invalid component type (" + componentType + ")");
  4211. return;
  4212. }
  4213. onSuccess(bufferViewData);
  4214. });
  4215. };
  4216. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  4217. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  4218. var byteOffset = accessor.byteOffset || 0;
  4219. var bytePerComponent = this._getByteStrideFromType(accessor);
  4220. var byteLength = accessor.count * bytePerComponent;
  4221. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, bytePerComponent, accessor.componentType, onSuccess);
  4222. };
  4223. GLTFLoader.prototype._getByteStrideFromType = function (accessor) {
  4224. switch (accessor.type) {
  4225. case "SCALAR": return 1;
  4226. case "VEC2": return 2;
  4227. case "VEC3": return 3;
  4228. case "VEC4": return 4;
  4229. case "MAT2": return 4;
  4230. case "MAT3": return 9;
  4231. case "MAT4": return 16;
  4232. default:
  4233. this._onError("Invalid accessor type (" + accessor.type + ")");
  4234. return 0;
  4235. }
  4236. };
  4237. Object.defineProperty(GLTFLoader.prototype, "blockPendingTracking", {
  4238. set: function (value) {
  4239. this._blockPendingTracking = value;
  4240. },
  4241. enumerable: true,
  4242. configurable: true
  4243. });
  4244. GLTFLoader.prototype.addPendingData = function (data) {
  4245. if (!this._renderReady) {
  4246. this._renderPendingCount++;
  4247. }
  4248. this.addLoaderPendingData(data);
  4249. };
  4250. GLTFLoader.prototype.removePendingData = function (data) {
  4251. if (!this._renderReady) {
  4252. if (--this._renderPendingCount === 0) {
  4253. this._renderReady = true;
  4254. this._onRenderReady();
  4255. }
  4256. }
  4257. this.removeLoaderPendingData(data);
  4258. };
  4259. GLTFLoader.prototype.addLoaderNonBlockingPendingData = function (data) {
  4260. if (!this._nonBlockingData) {
  4261. this._nonBlockingData = new Array();
  4262. }
  4263. this._nonBlockingData.push(data);
  4264. };
  4265. GLTFLoader.prototype.addLoaderPendingData = function (data) {
  4266. if (this._blockPendingTracking) {
  4267. this.addLoaderNonBlockingPendingData(data);
  4268. return;
  4269. }
  4270. this._loaderPendingCount++;
  4271. };
  4272. GLTFLoader.prototype.removeLoaderPendingData = function (data) {
  4273. var indexInPending = this._nonBlockingData ? this._nonBlockingData.indexOf(data) : -1;
  4274. if (indexInPending !== -1) {
  4275. this._nonBlockingData.splice(indexInPending, 1);
  4276. }
  4277. else if (--this._loaderPendingCount === 0) {
  4278. this._onLoaderFirstLODComplete();
  4279. }
  4280. if ((!this._nonBlockingData || this._nonBlockingData.length === 0) && this._loaderPendingCount === 0) {
  4281. this._onLoaderComplete();
  4282. this.dispose();
  4283. }
  4284. };
  4285. GLTFLoader.prototype._getDefaultMaterial = function () {
  4286. if (!this._defaultMaterial) {
  4287. var id = "__gltf_default";
  4288. var material = this._babylonScene.getMaterialByName(id);
  4289. if (!material) {
  4290. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  4291. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  4292. material.metallic = 1;
  4293. material.roughness = 1;
  4294. }
  4295. this._defaultMaterial = material;
  4296. }
  4297. return this._defaultMaterial;
  4298. };
  4299. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (material) {
  4300. var babylonMaterial = material.babylonMaterial;
  4301. // Ensure metallic workflow
  4302. babylonMaterial.metallic = 1;
  4303. babylonMaterial.roughness = 1;
  4304. var properties = material.pbrMetallicRoughness;
  4305. if (!properties) {
  4306. return;
  4307. }
  4308. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  4309. babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  4310. babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  4311. if (properties.baseColorTexture) {
  4312. babylonMaterial.albedoTexture = this.loadTexture(properties.baseColorTexture);
  4313. }
  4314. if (properties.metallicRoughnessTexture) {
  4315. babylonMaterial.metallicTexture = this.loadTexture(properties.metallicRoughnessTexture);
  4316. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  4317. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  4318. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  4319. }
  4320. this.loadMaterialAlphaProperties(material, properties.baseColorFactor);
  4321. };
  4322. GLTFLoader.prototype.loadMaterial = function (material, assign) {
  4323. if (material.babylonMaterial) {
  4324. assign(material.babylonMaterial, false);
  4325. return;
  4326. }
  4327. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, material, assign)) {
  4328. return;
  4329. }
  4330. this.createPbrMaterial(material);
  4331. this.loadMaterialBaseProperties(material);
  4332. this._loadMaterialMetallicRoughnessProperties(material);
  4333. assign(material.babylonMaterial, true);
  4334. };
  4335. GLTFLoader.prototype.createPbrMaterial = function (material) {
  4336. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  4337. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  4338. material.babylonMaterial = babylonMaterial;
  4339. };
  4340. GLTFLoader.prototype.loadMaterialBaseProperties = function (material) {
  4341. var babylonMaterial = material.babylonMaterial;
  4342. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  4343. if (material.doubleSided) {
  4344. babylonMaterial.backFaceCulling = false;
  4345. babylonMaterial.twoSidedLighting = true;
  4346. }
  4347. if (material.normalTexture) {
  4348. babylonMaterial.bumpTexture = this.loadTexture(material.normalTexture);
  4349. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  4350. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  4351. if (material.normalTexture.scale !== undefined) {
  4352. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  4353. }
  4354. }
  4355. if (material.occlusionTexture) {
  4356. babylonMaterial.ambientTexture = this.loadTexture(material.occlusionTexture);
  4357. babylonMaterial.useAmbientInGrayScale = true;
  4358. if (material.occlusionTexture.strength !== undefined) {
  4359. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  4360. }
  4361. }
  4362. if (material.emissiveTexture) {
  4363. babylonMaterial.emissiveTexture = this.loadTexture(material.emissiveTexture);
  4364. }
  4365. };
  4366. GLTFLoader.prototype.loadMaterialAlphaProperties = function (material, colorFactor) {
  4367. var babylonMaterial = material.babylonMaterial;
  4368. var alphaMode = material.alphaMode || "OPAQUE";
  4369. switch (alphaMode) {
  4370. case "OPAQUE":
  4371. // default is opaque
  4372. break;
  4373. case "MASK":
  4374. case "BLEND":
  4375. if (colorFactor) {
  4376. babylonMaterial.alpha = colorFactor[3];
  4377. }
  4378. if (babylonMaterial.albedoTexture) {
  4379. babylonMaterial.albedoTexture.hasAlpha = true;
  4380. babylonMaterial.useAlphaFromAlbedoTexture = (alphaMode === "BLEND");
  4381. }
  4382. break;
  4383. default:
  4384. BABYLON.Tools.Warn("Invalid alpha mode '" + material.alphaMode + "'");
  4385. break;
  4386. }
  4387. babylonMaterial.alphaCutOff = material.alphaCutoff === undefined ? 0.5 : material.alphaCutoff;
  4388. };
  4389. GLTFLoader.prototype.loadTexture = function (textureInfo) {
  4390. var _this = this;
  4391. var texture = this._gltf.textures[textureInfo.index];
  4392. var texCoord = textureInfo.texCoord || 0;
  4393. if (!texture || texture.source === undefined) {
  4394. return null;
  4395. }
  4396. var source = this._gltf.images[texture.source];
  4397. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  4398. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  4399. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  4400. this.addPendingData(texture);
  4401. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  4402. if (!_this._disposed) {
  4403. _this.removePendingData(texture);
  4404. }
  4405. }, function () {
  4406. if (!_this._disposed) {
  4407. _this._onError("Failed to load texture '" + source.uri + "'");
  4408. _this.removePendingData(texture);
  4409. }
  4410. });
  4411. if (texture.url) {
  4412. babylonTexture.updateURL(texture.url);
  4413. }
  4414. else if (texture.dataReadyObservable) {
  4415. texture.dataReadyObservable.add(function (texture) {
  4416. babylonTexture.updateURL(texture.url);
  4417. });
  4418. }
  4419. else {
  4420. texture.dataReadyObservable = new BABYLON.Observable();
  4421. texture.dataReadyObservable.add(function (texture) {
  4422. babylonTexture.updateURL(texture.url);
  4423. });
  4424. var setTextureData = function (data) {
  4425. texture.url = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  4426. texture.dataReadyObservable.notifyObservers(texture);
  4427. };
  4428. if (!source.uri) {
  4429. var bufferView = this._gltf.bufferViews[source.bufferView];
  4430. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, 1, GLTF2.EComponentType.UNSIGNED_BYTE, setTextureData);
  4431. }
  4432. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  4433. setTextureData(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri)));
  4434. }
  4435. else {
  4436. BABYLON.Tools.LoadFile(this._rootUrl + source.uri, setTextureData, function (event) {
  4437. if (!_this._disposed) {
  4438. _this._onProgress(event);
  4439. }
  4440. }, this._babylonScene.database, true, function (request) {
  4441. _this._onError("Failed to load file '" + source.uri + "': " + request.status + " " + request.statusText);
  4442. });
  4443. }
  4444. }
  4445. babylonTexture.coordinatesIndex = texCoord;
  4446. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  4447. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  4448. babylonTexture.name = texture.name || "texture" + textureInfo.index;
  4449. if (this._parent.onTextureLoaded) {
  4450. this._parent.onTextureLoaded(babylonTexture);
  4451. }
  4452. return babylonTexture;
  4453. };
  4454. return GLTFLoader;
  4455. }());
  4456. GLTFLoader.Extensions = {};
  4457. GLTF2.GLTFLoader = GLTFLoader;
  4458. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  4459. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4460. })(BABYLON || (BABYLON = {}));
  4461. //# sourceMappingURL=babylon.glTFLoader.js.map
  4462. var BABYLON;
  4463. (function (BABYLON) {
  4464. var GLTF2;
  4465. (function (GLTF2) {
  4466. /**
  4467. * Utils functions for GLTF
  4468. */
  4469. var GLTFUtils = (function () {
  4470. function GLTFUtils() {
  4471. }
  4472. /**
  4473. * If the uri is a base64 string
  4474. * @param uri: the uri to test
  4475. */
  4476. GLTFUtils.IsBase64 = function (uri) {
  4477. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  4478. };
  4479. /**
  4480. * Decode the base64 uri
  4481. * @param uri: the uri to decode
  4482. */
  4483. GLTFUtils.DecodeBase64 = function (uri) {
  4484. var decodedString = atob(uri.split(",")[1]);
  4485. var bufferLength = decodedString.length;
  4486. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  4487. for (var i = 0; i < bufferLength; i++) {
  4488. bufferView[i] = decodedString.charCodeAt(i);
  4489. }
  4490. return bufferView.buffer;
  4491. };
  4492. GLTFUtils.ForEach = function (view, func) {
  4493. for (var index = 0; index < view.length; index++) {
  4494. func(view[index], index);
  4495. }
  4496. };
  4497. GLTFUtils.GetTextureWrapMode = function (mode) {
  4498. // Set defaults if undefined
  4499. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  4500. switch (mode) {
  4501. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  4502. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  4503. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  4504. default:
  4505. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  4506. return BABYLON.Texture.WRAP_ADDRESSMODE;
  4507. }
  4508. };
  4509. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  4510. // Set defaults if undefined
  4511. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  4512. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  4513. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  4514. switch (minFilter) {
  4515. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  4516. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  4517. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  4518. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  4519. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  4520. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  4521. default:
  4522. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  4523. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  4524. }
  4525. }
  4526. else {
  4527. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  4528. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  4529. }
  4530. switch (minFilter) {
  4531. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  4532. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  4533. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  4534. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  4535. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  4536. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  4537. default:
  4538. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  4539. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  4540. }
  4541. }
  4542. };
  4543. /**
  4544. * Decodes a buffer view into a string
  4545. * @param view: the buffer view
  4546. */
  4547. GLTFUtils.DecodeBufferToText = function (view) {
  4548. var result = "";
  4549. var length = view.byteLength;
  4550. for (var i = 0; i < length; ++i) {
  4551. result += String.fromCharCode(view[i]);
  4552. }
  4553. return result;
  4554. };
  4555. return GLTFUtils;
  4556. }());
  4557. GLTF2.GLTFUtils = GLTFUtils;
  4558. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4559. })(BABYLON || (BABYLON = {}));
  4560. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  4561. var BABYLON;
  4562. (function (BABYLON) {
  4563. var GLTF2;
  4564. (function (GLTF2) {
  4565. var GLTFLoaderExtension = (function () {
  4566. function GLTFLoaderExtension() {
  4567. this.enabled = true;
  4568. }
  4569. GLTFLoaderExtension.prototype.loadMaterial = function (loader, material, assign) { return false; };
  4570. GLTFLoaderExtension.LoadMaterial = function (loader, material, assign) {
  4571. return this._ApplyExtensions(function (extension) { return extension.loadMaterial(loader, material, assign); });
  4572. };
  4573. GLTFLoaderExtension._ApplyExtensions = function (action) {
  4574. var extensions = GLTFLoaderExtension._Extensions;
  4575. if (!extensions) {
  4576. return;
  4577. }
  4578. for (var i = 0; i < extensions.length; i++) {
  4579. var extension = extensions[i];
  4580. if (extension.enabled && action(extension)) {
  4581. return true;
  4582. }
  4583. }
  4584. return false;
  4585. };
  4586. return GLTFLoaderExtension;
  4587. }());
  4588. //
  4589. // Utilities
  4590. //
  4591. GLTFLoaderExtension._Extensions = [];
  4592. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  4593. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4594. })(BABYLON || (BABYLON = {}));
  4595. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  4596. var BABYLON;
  4597. (function (BABYLON) {
  4598. var GLTF2;
  4599. (function (GLTF2) {
  4600. var Extensions;
  4601. (function (Extensions) {
  4602. var MSFTLOD = (function (_super) {
  4603. __extends(MSFTLOD, _super);
  4604. function MSFTLOD() {
  4605. return _super !== null && _super.apply(this, arguments) || this;
  4606. }
  4607. Object.defineProperty(MSFTLOD.prototype, "name", {
  4608. get: function () {
  4609. return "MSFT_lod";
  4610. },
  4611. enumerable: true,
  4612. configurable: true
  4613. });
  4614. MSFTLOD.prototype.loadMaterial = function (loader, material, assign) {
  4615. if (!material.extensions) {
  4616. return false;
  4617. }
  4618. var properties = material.extensions[this.name];
  4619. if (!properties) {
  4620. return false;
  4621. }
  4622. // Clear out the extension so that it won't get loaded again.
  4623. material.extensions[this.name] = undefined;
  4624. // Tell the loader not to clear its state until the highest LOD is loaded.
  4625. var materialLODs = [material.index].concat(properties.ids);
  4626. loader.addLoaderPendingData(material);
  4627. for (var index = 0; index < materialLODs.length; index++) {
  4628. loader.addLoaderNonBlockingPendingData(index);
  4629. }
  4630. // Start with the lowest quality LOD.
  4631. this.loadMaterialLOD(loader, material, materialLODs, materialLODs.length - 1, assign);
  4632. return true;
  4633. };
  4634. MSFTLOD.prototype.loadMaterialLOD = function (loader, material, materialLODs, lod, assign) {
  4635. var _this = this;
  4636. var materialLOD = loader.gltf.materials[materialLODs[lod]];
  4637. if (lod !== materialLODs.length - 1) {
  4638. loader.blockPendingTracking = true;
  4639. }
  4640. loader.loadMaterial(materialLOD, function (babylonMaterial, isNew) {
  4641. assign(babylonMaterial, isNew);
  4642. loader.removeLoaderPendingData(lod);
  4643. // Loading is considered complete if this is the lowest quality LOD.
  4644. if (lod === materialLODs.length - 1) {
  4645. loader.removeLoaderPendingData(material);
  4646. }
  4647. if (lod === 0) {
  4648. loader.blockPendingTracking = false;
  4649. return;
  4650. }
  4651. // Load the next LOD when the loader is ready to render and
  4652. // all active material textures of the current LOD are loaded.
  4653. loader.executeWhenRenderReady(function () {
  4654. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  4655. setTimeout(function () {
  4656. _this.loadMaterialLOD(loader, material, materialLODs, lod - 1, assign);
  4657. }, MSFTLOD.MinimalLODDelay);
  4658. });
  4659. });
  4660. });
  4661. };
  4662. return MSFTLOD;
  4663. }(GLTF2.GLTFLoaderExtension));
  4664. /**
  4665. * Specify the minimal delay between LODs in ms (default = 250)
  4666. */
  4667. MSFTLOD.MinimalLODDelay = 250;
  4668. Extensions.MSFTLOD = MSFTLOD;
  4669. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  4670. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4671. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4672. })(BABYLON || (BABYLON = {}));
  4673. //# sourceMappingURL=MSFT_lod.js.map
  4674. var BABYLON;
  4675. (function (BABYLON) {
  4676. var GLTF2;
  4677. (function (GLTF2) {
  4678. var Extensions;
  4679. (function (Extensions) {
  4680. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  4681. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  4682. function KHRMaterialsPbrSpecularGlossiness() {
  4683. return _super !== null && _super.apply(this, arguments) || this;
  4684. }
  4685. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  4686. get: function () {
  4687. return "KHR_materials_pbrSpecularGlossiness";
  4688. },
  4689. enumerable: true,
  4690. configurable: true
  4691. });
  4692. KHRMaterialsPbrSpecularGlossiness.prototype.loadMaterial = function (loader, material, assign) {
  4693. if (!material.extensions) {
  4694. return false;
  4695. }
  4696. var properties = material.extensions[this.name];
  4697. if (!properties) {
  4698. return false;
  4699. }
  4700. loader.createPbrMaterial(material);
  4701. loader.loadMaterialBaseProperties(material);
  4702. this._loadSpecularGlossinessProperties(loader, material, properties);
  4703. assign(material.babylonMaterial, true);
  4704. return true;
  4705. };
  4706. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, material, properties) {
  4707. var babylonMaterial = material.babylonMaterial;
  4708. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  4709. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  4710. babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  4711. if (properties.diffuseTexture) {
  4712. babylonMaterial.albedoTexture = loader.loadTexture(properties.diffuseTexture);
  4713. }
  4714. if (properties.specularGlossinessTexture) {
  4715. babylonMaterial.reflectivityTexture = loader.loadTexture(properties.specularGlossinessTexture);
  4716. babylonMaterial.reflectivityTexture.hasAlpha = true;
  4717. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  4718. }
  4719. loader.loadMaterialAlphaProperties(material, properties.diffuseFactor);
  4720. };
  4721. return KHRMaterialsPbrSpecularGlossiness;
  4722. }(GLTF2.GLTFLoaderExtension));
  4723. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  4724. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  4725. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4726. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4727. })(BABYLON || (BABYLON = {}));
  4728. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  4729. (function universalModuleDefinition(root, factory) {
  4730. if (root && root["BABYLON"]) {
  4731. return;
  4732. }
  4733. if(typeof exports === 'object' && typeof module === 'object')
  4734. module.exports = factory();
  4735. else if(typeof define === 'function' && define.amd)
  4736. define([], factory);
  4737. else if(typeof exports === 'object')
  4738. exports["BJSLoaders"] = factory();
  4739. else {
  4740. root["BABYLON"] = factory();
  4741. }
  4742. })(this, function() {
  4743. return BABYLON;
  4744. });