babylonjs.loaders.js 338 KB

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