babylon.glTFFileLoader.js 301 KB

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