babylonjs.loaders.js 282 KB

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