babylonjs.loaders.js 315 KB

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