babylonjs.loaders.js 349 KB

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