babylonjs.loaders.js 247 KB

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