babylon.glTFFileLoader.js 311 KB

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