babylonjs.loaders.js 251 KB

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