babylonjs.loaders.js 257 KB

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