babylon.2.0-beta.debug.js 1.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. };
  29. Color3.prototype.toColor4 = function (alpha) {
  30. if (alpha === void 0) { alpha = 1; }
  31. return new Color4(this.r, this.g, this.b, alpha);
  32. };
  33. Color3.prototype.asArray = function () {
  34. var result = [];
  35. this.toArray(result, 0);
  36. return result;
  37. };
  38. Color3.prototype.toLuminance = function () {
  39. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  40. };
  41. Color3.prototype.multiply = function (otherColor) {
  42. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  43. };
  44. Color3.prototype.multiplyToRef = function (otherColor, result) {
  45. result.r = this.r * otherColor.r;
  46. result.g = this.g * otherColor.g;
  47. result.b = this.b * otherColor.b;
  48. };
  49. Color3.prototype.equals = function (otherColor) {
  50. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  51. };
  52. Color3.prototype.scale = function (scale) {
  53. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  54. };
  55. Color3.prototype.scaleToRef = function (scale, result) {
  56. result.r = this.r * scale;
  57. result.g = this.g * scale;
  58. result.b = this.b * scale;
  59. };
  60. Color3.prototype.add = function (otherColor) {
  61. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  62. };
  63. Color3.prototype.addToRef = function (otherColor, result) {
  64. result.r = this.r + otherColor.r;
  65. result.g = this.g + otherColor.g;
  66. result.b = this.b + otherColor.b;
  67. };
  68. Color3.prototype.subtract = function (otherColor) {
  69. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  70. };
  71. Color3.prototype.subtractToRef = function (otherColor, result) {
  72. result.r = this.r - otherColor.r;
  73. result.g = this.g - otherColor.g;
  74. result.b = this.b - otherColor.b;
  75. };
  76. Color3.prototype.clone = function () {
  77. return new Color3(this.r, this.g, this.b);
  78. };
  79. Color3.prototype.copyFrom = function (source) {
  80. this.r = source.r;
  81. this.g = source.g;
  82. this.b = source.b;
  83. };
  84. Color3.prototype.copyFromFloats = function (r, g, b) {
  85. this.r = r;
  86. this.g = g;
  87. this.b = b;
  88. };
  89. // Statics
  90. Color3.FromArray = function (array, offset) {
  91. if (offset === void 0) { offset = 0; }
  92. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  93. };
  94. Color3.FromInts = function (r, g, b) {
  95. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  96. };
  97. Color3.Lerp = function (start, end, amount) {
  98. var r = start.r + ((end.r - start.r) * amount);
  99. var g = start.g + ((end.g - start.g) * amount);
  100. var b = start.b + ((end.b - start.b) * amount);
  101. return new Color3(r, g, b);
  102. };
  103. Color3.Red = function () {
  104. return new Color3(1, 0, 0);
  105. };
  106. Color3.Green = function () {
  107. return new Color3(0, 1, 0);
  108. };
  109. Color3.Blue = function () {
  110. return new Color3(0, 0, 1);
  111. };
  112. Color3.Black = function () {
  113. return new Color3(0, 0, 0);
  114. };
  115. Color3.White = function () {
  116. return new Color3(1, 1, 1);
  117. };
  118. Color3.Purple = function () {
  119. return new Color3(0.5, 0, 0.5);
  120. };
  121. Color3.Magenta = function () {
  122. return new Color3(1, 0, 1);
  123. };
  124. Color3.Yellow = function () {
  125. return new Color3(1, 1, 0);
  126. };
  127. Color3.Gray = function () {
  128. return new Color3(0.5, 0.5, 0.5);
  129. };
  130. return Color3;
  131. })();
  132. BABYLON.Color3 = Color3;
  133. var Color4 = (function () {
  134. function Color4(r, g, b, a) {
  135. this.r = r;
  136. this.g = g;
  137. this.b = b;
  138. this.a = a;
  139. }
  140. // Operators
  141. Color4.prototype.addInPlace = function (right) {
  142. this.r += right.r;
  143. this.g += right.g;
  144. this.b += right.b;
  145. this.a += right.a;
  146. };
  147. Color4.prototype.asArray = function () {
  148. var result = [];
  149. this.toArray(result, 0);
  150. return result;
  151. };
  152. Color4.prototype.toArray = function (array, index) {
  153. if (index === undefined) {
  154. index = 0;
  155. }
  156. array[index] = this.r;
  157. array[index + 1] = this.g;
  158. array[index + 2] = this.b;
  159. array[index + 3] = this.a;
  160. };
  161. Color4.prototype.add = function (right) {
  162. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  163. };
  164. Color4.prototype.subtract = function (right) {
  165. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  166. };
  167. Color4.prototype.subtractToRef = function (right, result) {
  168. result.r = this.r - right.r;
  169. result.g = this.g - right.g;
  170. result.b = this.b - right.b;
  171. result.a = this.a - right.a;
  172. };
  173. Color4.prototype.scale = function (scale) {
  174. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  175. };
  176. Color4.prototype.scaleToRef = function (scale, result) {
  177. result.r = this.r * scale;
  178. result.g = this.g * scale;
  179. result.b = this.b * scale;
  180. result.a = this.a * scale;
  181. };
  182. Color4.prototype.toString = function () {
  183. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  184. };
  185. Color4.prototype.clone = function () {
  186. return new Color4(this.r, this.g, this.b, this.a);
  187. };
  188. Color4.prototype.copyFrom = function (source) {
  189. this.r = source.r;
  190. this.g = source.g;
  191. this.b = source.b;
  192. this.a = source.a;
  193. };
  194. // Statics
  195. Color4.Lerp = function (left, right, amount) {
  196. var result = new Color4(0, 0, 0, 0);
  197. Color4.LerpToRef(left, right, amount, result);
  198. return result;
  199. };
  200. Color4.LerpToRef = function (left, right, amount, result) {
  201. result.r = left.r + (right.r - left.r) * amount;
  202. result.g = left.g + (right.g - left.g) * amount;
  203. result.b = left.b + (right.b - left.b) * amount;
  204. result.a = left.a + (right.a - left.a) * amount;
  205. };
  206. Color4.FromArray = function (array, offset) {
  207. if (offset === void 0) { offset = 0; }
  208. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  209. };
  210. Color4.FromInts = function (r, g, b, a) {
  211. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  212. };
  213. return Color4;
  214. })();
  215. BABYLON.Color4 = Color4;
  216. var Vector2 = (function () {
  217. function Vector2(x, y) {
  218. this.x = x;
  219. this.y = y;
  220. }
  221. Vector2.prototype.toString = function () {
  222. return "{X: " + this.x + " Y:" + this.y + "}";
  223. };
  224. // Operators
  225. Vector2.prototype.toArray = function (array, index) {
  226. if (index === undefined) {
  227. index = 0;
  228. }
  229. array[index] = this.x;
  230. array[index + 1] = this.y;
  231. };
  232. Vector2.prototype.asArray = function () {
  233. var result = [];
  234. this.toArray(result, 0);
  235. return result;
  236. };
  237. Vector2.prototype.copyFrom = function (source) {
  238. this.x = source.x;
  239. this.y = source.y;
  240. };
  241. Vector2.prototype.copyFromFloats = function (x, y) {
  242. this.x = x;
  243. this.y = y;
  244. };
  245. Vector2.prototype.add = function (otherVector) {
  246. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  247. };
  248. Vector2.prototype.addVector3 = function (otherVector) {
  249. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  250. };
  251. Vector2.prototype.subtract = function (otherVector) {
  252. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  253. };
  254. Vector2.prototype.subtractInPlace = function (otherVector) {
  255. this.x -= otherVector.x;
  256. this.y -= otherVector.y;
  257. };
  258. Vector2.prototype.multiplyInPlace = function (otherVector) {
  259. this.x *= otherVector.x;
  260. this.y *= otherVector.y;
  261. };
  262. Vector2.prototype.multiply = function (otherVector) {
  263. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  264. };
  265. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  266. result.x = this.x * otherVector.x;
  267. result.y = this.y * otherVector.y;
  268. };
  269. Vector2.prototype.multiplyByFloats = function (x, y) {
  270. return new Vector2(this.x * x, this.y * y);
  271. };
  272. Vector2.prototype.divide = function (otherVector) {
  273. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  274. };
  275. Vector2.prototype.divideToRef = function (otherVector, result) {
  276. result.x = this.x / otherVector.x;
  277. result.y = this.y / otherVector.y;
  278. };
  279. Vector2.prototype.negate = function () {
  280. return new Vector2(-this.x, -this.y);
  281. };
  282. Vector2.prototype.scaleInPlace = function (scale) {
  283. this.x *= scale;
  284. this.y *= scale;
  285. return this;
  286. };
  287. Vector2.prototype.scale = function (scale) {
  288. return new Vector2(this.x * scale, this.y * scale);
  289. };
  290. Vector2.prototype.equals = function (otherVector) {
  291. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  292. };
  293. // Properties
  294. Vector2.prototype.length = function () {
  295. return Math.sqrt(this.x * this.x + this.y * this.y);
  296. };
  297. Vector2.prototype.lengthSquared = function () {
  298. return (this.x * this.x + this.y * this.y);
  299. };
  300. // Methods
  301. Vector2.prototype.normalize = function () {
  302. var len = this.length();
  303. if (len === 0)
  304. return this;
  305. var num = 1.0 / len;
  306. this.x *= num;
  307. this.y *= num;
  308. return this;
  309. };
  310. Vector2.prototype.clone = function () {
  311. return new Vector2(this.x, this.y);
  312. };
  313. // Statics
  314. Vector2.Zero = function () {
  315. return new Vector2(0, 0);
  316. };
  317. Vector2.FromArray = function (array, offset) {
  318. if (offset === void 0) { offset = 0; }
  319. return new Vector2(array[offset], array[offset + 1]);
  320. };
  321. Vector2.FromArrayToRef = function (array, offset, result) {
  322. result.x = array[offset];
  323. result.y = array[offset + 1];
  324. };
  325. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  326. var squared = amount * amount;
  327. var cubed = amount * squared;
  328. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  329. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  330. return new Vector2(x, y);
  331. };
  332. Vector2.Clamp = function (value, min, max) {
  333. var x = value.x;
  334. x = (x > max.x) ? max.x : x;
  335. x = (x < min.x) ? min.x : x;
  336. var y = value.y;
  337. y = (y > max.y) ? max.y : y;
  338. y = (y < min.y) ? min.y : y;
  339. return new Vector2(x, y);
  340. };
  341. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  342. var squared = amount * amount;
  343. var cubed = amount * squared;
  344. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  345. var part2 = (-2.0 * cubed) + (3.0 * squared);
  346. var part3 = (cubed - (2.0 * squared)) + amount;
  347. var part4 = cubed - squared;
  348. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  349. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  350. return new Vector2(x, y);
  351. };
  352. Vector2.Lerp = function (start, end, amount) {
  353. var x = start.x + ((end.x - start.x) * amount);
  354. var y = start.y + ((end.y - start.y) * amount);
  355. return new Vector2(x, y);
  356. };
  357. Vector2.Dot = function (left, right) {
  358. return left.x * right.x + left.y * right.y;
  359. };
  360. Vector2.Normalize = function (vector) {
  361. var newVector = vector.clone();
  362. newVector.normalize();
  363. return newVector;
  364. };
  365. Vector2.Minimize = function (left, right) {
  366. var x = (left.x < right.x) ? left.x : right.x;
  367. var y = (left.y < right.y) ? left.y : right.y;
  368. return new Vector2(x, y);
  369. };
  370. Vector2.Maximize = function (left, right) {
  371. var x = (left.x > right.x) ? left.x : right.x;
  372. var y = (left.y > right.y) ? left.y : right.y;
  373. return new Vector2(x, y);
  374. };
  375. Vector2.Transform = function (vector, transformation) {
  376. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  377. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  378. return new Vector2(x, y);
  379. };
  380. Vector2.Distance = function (value1, value2) {
  381. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  382. };
  383. Vector2.DistanceSquared = function (value1, value2) {
  384. var x = value1.x - value2.x;
  385. var y = value1.y - value2.y;
  386. return (x * x) + (y * y);
  387. };
  388. return Vector2;
  389. })();
  390. BABYLON.Vector2 = Vector2;
  391. var Vector3 = (function () {
  392. function Vector3(x, y, z) {
  393. this.x = x;
  394. this.y = y;
  395. this.z = z;
  396. }
  397. Vector3.prototype.toString = function () {
  398. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  399. };
  400. // Operators
  401. Vector3.prototype.asArray = function () {
  402. var result = [];
  403. this.toArray(result, 0);
  404. return result;
  405. };
  406. Vector3.prototype.toArray = function (array, index) {
  407. if (index === undefined) {
  408. index = 0;
  409. }
  410. array[index] = this.x;
  411. array[index + 1] = this.y;
  412. array[index + 2] = this.z;
  413. };
  414. Vector3.prototype.addInPlace = function (otherVector) {
  415. this.x += otherVector.x;
  416. this.y += otherVector.y;
  417. this.z += otherVector.z;
  418. };
  419. Vector3.prototype.add = function (otherVector) {
  420. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  421. };
  422. Vector3.prototype.addToRef = function (otherVector, result) {
  423. result.x = this.x + otherVector.x;
  424. result.y = this.y + otherVector.y;
  425. result.z = this.z + otherVector.z;
  426. };
  427. Vector3.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. this.z -= otherVector.z;
  431. };
  432. Vector3.prototype.subtract = function (otherVector) {
  433. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  434. };
  435. Vector3.prototype.subtractToRef = function (otherVector, result) {
  436. result.x = this.x - otherVector.x;
  437. result.y = this.y - otherVector.y;
  438. result.z = this.z - otherVector.z;
  439. };
  440. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  441. return new Vector3(this.x - x, this.y - y, this.z - z);
  442. };
  443. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  444. result.x = this.x - x;
  445. result.y = this.y - y;
  446. result.z = this.z - z;
  447. };
  448. Vector3.prototype.negate = function () {
  449. return new Vector3(-this.x, -this.y, -this.z);
  450. };
  451. Vector3.prototype.scaleInPlace = function (scale) {
  452. this.x *= scale;
  453. this.y *= scale;
  454. this.z *= scale;
  455. return this;
  456. };
  457. Vector3.prototype.scale = function (scale) {
  458. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  459. };
  460. Vector3.prototype.scaleToRef = function (scale, result) {
  461. result.x = this.x * scale;
  462. result.y = this.y * scale;
  463. result.z = this.z * scale;
  464. };
  465. Vector3.prototype.equals = function (otherVector) {
  466. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  467. };
  468. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  469. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  470. };
  471. Vector3.prototype.equalsToFloats = function (x, y, z) {
  472. return this.x === x && this.y === y && this.z === z;
  473. };
  474. Vector3.prototype.multiplyInPlace = function (otherVector) {
  475. this.x *= otherVector.x;
  476. this.y *= otherVector.y;
  477. this.z *= otherVector.z;
  478. };
  479. Vector3.prototype.multiply = function (otherVector) {
  480. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  481. };
  482. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  483. result.x = this.x * otherVector.x;
  484. result.y = this.y * otherVector.y;
  485. result.z = this.z * otherVector.z;
  486. };
  487. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  488. return new Vector3(this.x * x, this.y * y, this.z * z);
  489. };
  490. Vector3.prototype.divide = function (otherVector) {
  491. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  492. };
  493. Vector3.prototype.divideToRef = function (otherVector, result) {
  494. result.x = this.x / otherVector.x;
  495. result.y = this.y / otherVector.y;
  496. result.z = this.z / otherVector.z;
  497. };
  498. Vector3.prototype.MinimizeInPlace = function (other) {
  499. if (other.x < this.x)
  500. this.x = other.x;
  501. if (other.y < this.y)
  502. this.y = other.y;
  503. if (other.z < this.z)
  504. this.z = other.z;
  505. };
  506. Vector3.prototype.MaximizeInPlace = function (other) {
  507. if (other.x > this.x)
  508. this.x = other.x;
  509. if (other.y > this.y)
  510. this.y = other.y;
  511. if (other.z > this.z)
  512. this.z = other.z;
  513. };
  514. // Properties
  515. Vector3.prototype.length = function () {
  516. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  517. };
  518. Vector3.prototype.lengthSquared = function () {
  519. return (this.x * this.x + this.y * this.y + this.z * this.z);
  520. };
  521. // Methods
  522. Vector3.prototype.normalize = function () {
  523. var len = this.length();
  524. if (len === 0)
  525. return this;
  526. var num = 1.0 / len;
  527. this.x *= num;
  528. this.y *= num;
  529. this.z *= num;
  530. return this;
  531. };
  532. Vector3.prototype.clone = function () {
  533. return new Vector3(this.x, this.y, this.z);
  534. };
  535. Vector3.prototype.copyFrom = function (source) {
  536. this.x = source.x;
  537. this.y = source.y;
  538. this.z = source.z;
  539. };
  540. Vector3.prototype.copyFromFloats = function (x, y, z) {
  541. this.x = x;
  542. this.y = y;
  543. this.z = z;
  544. };
  545. // Statics
  546. Vector3.FromArray = function (array, offset) {
  547. if (!offset) {
  548. offset = 0;
  549. }
  550. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  551. };
  552. Vector3.FromArrayToRef = function (array, offset, result) {
  553. result.x = array[offset];
  554. result.y = array[offset + 1];
  555. result.z = array[offset + 2];
  556. };
  557. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  558. result.x = array[offset];
  559. result.y = array[offset + 1];
  560. result.z = array[offset + 2];
  561. };
  562. Vector3.FromFloatsToRef = function (x, y, z, result) {
  563. result.x = x;
  564. result.y = y;
  565. result.z = z;
  566. };
  567. Vector3.Zero = function () {
  568. return new Vector3(0, 0, 0);
  569. };
  570. Vector3.Up = function () {
  571. return new Vector3(0, 1.0, 0);
  572. };
  573. Vector3.TransformCoordinates = function (vector, transformation) {
  574. var result = Vector3.Zero();
  575. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  576. return result;
  577. };
  578. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  579. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  580. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  581. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  582. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  583. result.x = x / w;
  584. result.y = y / w;
  585. result.z = z / w;
  586. };
  587. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  588. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  589. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  590. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  591. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  592. result.x = rx / rw;
  593. result.y = ry / rw;
  594. result.z = rz / rw;
  595. };
  596. Vector3.TransformNormal = function (vector, transformation) {
  597. var result = Vector3.Zero();
  598. Vector3.TransformNormalToRef(vector, transformation, result);
  599. return result;
  600. };
  601. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  602. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  603. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  604. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  605. };
  606. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  607. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  608. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  609. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  610. };
  611. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  612. var squared = amount * amount;
  613. var cubed = amount * squared;
  614. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  615. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  616. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  617. return new Vector3(x, y, z);
  618. };
  619. Vector3.Clamp = function (value, min, max) {
  620. var x = value.x;
  621. x = (x > max.x) ? max.x : x;
  622. x = (x < min.x) ? min.x : x;
  623. var y = value.y;
  624. y = (y > max.y) ? max.y : y;
  625. y = (y < min.y) ? min.y : y;
  626. var z = value.z;
  627. z = (z > max.z) ? max.z : z;
  628. z = (z < min.z) ? min.z : z;
  629. return new Vector3(x, y, z);
  630. };
  631. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  632. var squared = amount * amount;
  633. var cubed = amount * squared;
  634. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  635. var part2 = (-2.0 * cubed) + (3.0 * squared);
  636. var part3 = (cubed - (2.0 * squared)) + amount;
  637. var part4 = cubed - squared;
  638. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  639. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  640. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  641. return new Vector3(x, y, z);
  642. };
  643. Vector3.Lerp = function (start, end, amount) {
  644. var x = start.x + ((end.x - start.x) * amount);
  645. var y = start.y + ((end.y - start.y) * amount);
  646. var z = start.z + ((end.z - start.z) * amount);
  647. return new Vector3(x, y, z);
  648. };
  649. Vector3.Dot = function (left, right) {
  650. return (left.x * right.x + left.y * right.y + left.z * right.z);
  651. };
  652. Vector3.Cross = function (left, right) {
  653. var result = Vector3.Zero();
  654. Vector3.CrossToRef(left, right, result);
  655. return result;
  656. };
  657. Vector3.CrossToRef = function (left, right, result) {
  658. result.x = left.y * right.z - left.z * right.y;
  659. result.y = left.z * right.x - left.x * right.z;
  660. result.z = left.x * right.y - left.y * right.x;
  661. };
  662. Vector3.Normalize = function (vector) {
  663. var result = Vector3.Zero();
  664. Vector3.NormalizeToRef(vector, result);
  665. return result;
  666. };
  667. Vector3.NormalizeToRef = function (vector, result) {
  668. result.copyFrom(vector);
  669. result.normalize();
  670. };
  671. Vector3.Project = function (vector, world, transform, viewport) {
  672. var cw = viewport.width;
  673. var ch = viewport.height;
  674. var cx = viewport.x;
  675. var cy = viewport.y;
  676. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  677. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  678. return Vector3.TransformCoordinates(vector, finalMatrix);
  679. };
  680. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  681. var matrix = world.multiply(transform);
  682. matrix.invert();
  683. source.x = source.x / viewportWidth * 2 - 1;
  684. source.y = -(source.y / viewportHeight * 2 - 1);
  685. var vector = Vector3.TransformCoordinates(source, matrix);
  686. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  687. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  688. vector = vector.scale(1.0 / num);
  689. }
  690. return vector;
  691. };
  692. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  693. var matrix = world.multiply(view).multiply(projection);
  694. matrix.invert();
  695. source.x = source.x / viewportWidth * 2 - 1;
  696. source.y = -(source.y / viewportHeight * 2 - 1);
  697. var vector = Vector3.TransformCoordinates(source, matrix);
  698. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  699. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  700. vector = vector.scale(1.0 / num);
  701. }
  702. return vector;
  703. };
  704. Vector3.Minimize = function (left, right) {
  705. var min = left.clone();
  706. min.MinimizeInPlace(right);
  707. return min;
  708. };
  709. Vector3.Maximize = function (left, right) {
  710. var max = left.clone();
  711. max.MaximizeInPlace(right);
  712. return max;
  713. };
  714. Vector3.Distance = function (value1, value2) {
  715. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  716. };
  717. Vector3.DistanceSquared = function (value1, value2) {
  718. var x = value1.x - value2.x;
  719. var y = value1.y - value2.y;
  720. var z = value1.z - value2.z;
  721. return (x * x) + (y * y) + (z * z);
  722. };
  723. Vector3.Center = function (value1, value2) {
  724. var center = value1.add(value2);
  725. center.scaleInPlace(0.5);
  726. return center;
  727. };
  728. return Vector3;
  729. })();
  730. BABYLON.Vector3 = Vector3;
  731. //Vector4 class created for EulerAngle class conversion to Quaternion
  732. var Vector4 = (function () {
  733. function Vector4(x, y, z, w) {
  734. this.x = x;
  735. this.y = y;
  736. this.z = z;
  737. this.w = w;
  738. }
  739. Vector4.prototype.toString = function () {
  740. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  741. };
  742. // Operators
  743. Vector4.prototype.asArray = function () {
  744. var result = [];
  745. this.toArray(result, 0);
  746. return result;
  747. };
  748. Vector4.prototype.toArray = function (array, index) {
  749. if (index === undefined) {
  750. index = 0;
  751. }
  752. array[index] = this.x;
  753. array[index + 1] = this.y;
  754. array[index + 2] = this.z;
  755. array[index + 3] = this.w;
  756. };
  757. Vector4.prototype.addInPlace = function (otherVector) {
  758. this.x += otherVector.x;
  759. this.y += otherVector.y;
  760. this.z += otherVector.z;
  761. this.w += otherVector.w;
  762. };
  763. Vector4.prototype.add = function (otherVector) {
  764. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  765. };
  766. Vector4.prototype.addToRef = function (otherVector, result) {
  767. result.x = this.x + otherVector.x;
  768. result.y = this.y + otherVector.y;
  769. result.z = this.z + otherVector.z;
  770. result.w = this.w + otherVector.w;
  771. };
  772. Vector4.prototype.subtractInPlace = function (otherVector) {
  773. this.x -= otherVector.x;
  774. this.y -= otherVector.y;
  775. this.z -= otherVector.z;
  776. this.w -= otherVector.w;
  777. };
  778. Vector4.prototype.subtract = function (otherVector) {
  779. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  780. };
  781. Vector4.prototype.subtractToRef = function (otherVector, result) {
  782. result.x = this.x - otherVector.x;
  783. result.y = this.y - otherVector.y;
  784. result.z = this.z - otherVector.z;
  785. result.w = this.w - otherVector.w;
  786. };
  787. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  788. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  789. };
  790. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  791. result.x = this.x - x;
  792. result.y = this.y - y;
  793. result.z = this.z - z;
  794. result.w = this.w - w;
  795. };
  796. Vector4.prototype.negate = function () {
  797. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  798. };
  799. Vector4.prototype.scaleInPlace = function (scale) {
  800. this.x *= scale;
  801. this.y *= scale;
  802. this.z *= scale;
  803. this.w *= scale;
  804. return this;
  805. };
  806. Vector4.prototype.scale = function (scale) {
  807. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  808. };
  809. Vector4.prototype.scaleToRef = function (scale, result) {
  810. result.x = this.x * scale;
  811. result.y = this.y * scale;
  812. result.z = this.z * scale;
  813. result.w = this.w * scale;
  814. };
  815. Vector4.prototype.equals = function (otherVector) {
  816. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  817. };
  818. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  819. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  820. };
  821. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  822. return this.x === x && this.y === y && this.z === z && this.w === w;
  823. };
  824. Vector4.prototype.multiplyInPlace = function (otherVector) {
  825. this.x *= otherVector.x;
  826. this.y *= otherVector.y;
  827. this.z *= otherVector.z;
  828. this.w *= otherVector.w;
  829. };
  830. Vector4.prototype.multiply = function (otherVector) {
  831. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  832. };
  833. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  834. result.x = this.x * otherVector.x;
  835. result.y = this.y * otherVector.y;
  836. result.z = this.z * otherVector.z;
  837. result.w = this.w * otherVector.w;
  838. };
  839. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  840. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  841. };
  842. Vector4.prototype.divide = function (otherVector) {
  843. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  844. };
  845. Vector4.prototype.divideToRef = function (otherVector, result) {
  846. result.x = this.x / otherVector.x;
  847. result.y = this.y / otherVector.y;
  848. result.z = this.z / otherVector.z;
  849. result.w = this.w / otherVector.w;
  850. };
  851. Vector4.prototype.MinimizeInPlace = function (other) {
  852. if (other.x < this.x)
  853. this.x = other.x;
  854. if (other.y < this.y)
  855. this.y = other.y;
  856. if (other.z < this.z)
  857. this.z = other.z;
  858. if (other.w < this.w)
  859. this.w = other.w;
  860. };
  861. Vector4.prototype.MaximizeInPlace = function (other) {
  862. if (other.x > this.x)
  863. this.x = other.x;
  864. if (other.y > this.y)
  865. this.y = other.y;
  866. if (other.z > this.z)
  867. this.z = other.z;
  868. if (other.w > this.w)
  869. this.w = other.w;
  870. };
  871. // Properties
  872. Vector4.prototype.length = function () {
  873. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  874. };
  875. Vector4.prototype.lengthSquared = function () {
  876. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  877. };
  878. // Methods
  879. Vector4.prototype.normalize = function () {
  880. var len = this.length();
  881. if (len === 0)
  882. return this;
  883. var num = 1.0 / len;
  884. this.x *= num;
  885. this.y *= num;
  886. this.z *= num;
  887. this.w *= num;
  888. return this;
  889. };
  890. Vector4.prototype.clone = function () {
  891. return new Vector4(this.x, this.y, this.z, this.w);
  892. };
  893. Vector4.prototype.copyFrom = function (source) {
  894. this.x = source.x;
  895. this.y = source.y;
  896. this.z = source.z;
  897. this.w = source.w;
  898. };
  899. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  900. this.x = x;
  901. this.y = y;
  902. this.z = z;
  903. this.w = w;
  904. };
  905. // Statics
  906. Vector4.FromArray = function (array, offset) {
  907. if (!offset) {
  908. offset = 0;
  909. }
  910. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  911. };
  912. Vector4.FromArrayToRef = function (array, offset, result) {
  913. result.x = array[offset];
  914. result.y = array[offset + 1];
  915. result.z = array[offset + 2];
  916. result.w = array[offset + 3];
  917. };
  918. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  919. result.x = array[offset];
  920. result.y = array[offset + 1];
  921. result.z = array[offset + 2];
  922. result.w = array[offset + 3];
  923. };
  924. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  925. result.x = x;
  926. result.y = y;
  927. result.z = z;
  928. result.w = w;
  929. };
  930. Vector4.Zero = function () {
  931. return new Vector4(0, 0, 0, 0);
  932. };
  933. Vector4.Normalize = function (vector) {
  934. var result = Vector4.Zero();
  935. Vector4.NormalizeToRef(vector, result);
  936. return result;
  937. };
  938. Vector4.NormalizeToRef = function (vector, result) {
  939. result.copyFrom(vector);
  940. result.normalize();
  941. };
  942. Vector4.Minimize = function (left, right) {
  943. var min = left.clone();
  944. min.MinimizeInPlace(right);
  945. return min;
  946. };
  947. Vector4.Maximize = function (left, right) {
  948. var max = left.clone();
  949. max.MaximizeInPlace(right);
  950. return max;
  951. };
  952. Vector4.Distance = function (value1, value2) {
  953. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  954. };
  955. Vector4.DistanceSquared = function (value1, value2) {
  956. var x = value1.x - value2.x;
  957. var y = value1.y - value2.y;
  958. var z = value1.z - value2.z;
  959. var w = value1.w - value2.w;
  960. return (x * x) + (y * y) + (z * z) + (w * w);
  961. };
  962. Vector4.Center = function (value1, value2) {
  963. var center = value1.add(value2);
  964. center.scaleInPlace(0.5);
  965. return center;
  966. };
  967. return Vector4;
  968. })();
  969. BABYLON.Vector4 = Vector4;
  970. var Quaternion = (function () {
  971. function Quaternion(x, y, z, w) {
  972. if (x === void 0) { x = 0; }
  973. if (y === void 0) { y = 0; }
  974. if (z === void 0) { z = 0; }
  975. if (w === void 0) { w = 1; }
  976. this.x = x;
  977. this.y = y;
  978. this.z = z;
  979. this.w = w;
  980. }
  981. Quaternion.prototype.toString = function () {
  982. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  983. };
  984. Quaternion.prototype.asArray = function () {
  985. return [this.x, this.y, this.z, this.w];
  986. };
  987. Quaternion.prototype.equals = function (otherQuaternion) {
  988. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  989. };
  990. Quaternion.prototype.clone = function () {
  991. return new Quaternion(this.x, this.y, this.z, this.w);
  992. };
  993. Quaternion.prototype.copyFrom = function (other) {
  994. this.x = other.x;
  995. this.y = other.y;
  996. this.z = other.z;
  997. this.w = other.w;
  998. };
  999. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1000. this.x = x;
  1001. this.y = y;
  1002. this.z = z;
  1003. this.w = w;
  1004. };
  1005. Quaternion.prototype.add = function (other) {
  1006. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1007. };
  1008. Quaternion.prototype.subtract = function (other) {
  1009. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1010. };
  1011. Quaternion.prototype.scale = function (value) {
  1012. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1013. };
  1014. Quaternion.prototype.multiply = function (q1) {
  1015. var result = new Quaternion(0, 0, 0, 1.0);
  1016. this.multiplyToRef(q1, result);
  1017. return result;
  1018. };
  1019. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1020. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1021. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1022. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1023. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1024. };
  1025. Quaternion.prototype.length = function () {
  1026. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1027. };
  1028. Quaternion.prototype.normalize = function () {
  1029. var length = 1.0 / this.length();
  1030. this.x *= length;
  1031. this.y *= length;
  1032. this.z *= length;
  1033. this.w *= length;
  1034. };
  1035. Quaternion.prototype.toEulerAngles = function () {
  1036. var result = Vector3.Zero();
  1037. this.toEulerAnglesToRef(result);
  1038. return result;
  1039. };
  1040. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1041. //result is an EulerAngles in the in the z-x-z convention
  1042. var qx = this.x;
  1043. var qy = this.y;
  1044. var qz = this.z;
  1045. var qw = this.w;
  1046. var qxy = qx * qy;
  1047. var qxz = qx * qz;
  1048. var qwy = qw * qy;
  1049. var qwz = qw * qz;
  1050. var qwx = qw * qx;
  1051. var qyz = qy * qz;
  1052. var sqx = qx * qx;
  1053. var sqy = qy * qy;
  1054. var determinant = sqx + sqy;
  1055. if (determinant !== 0.000 && determinant !== 1.000) {
  1056. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1057. result.y = Math.acos(1 - 2 * determinant);
  1058. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1059. }
  1060. else {
  1061. if (determinant === 0.0) {
  1062. result.x = 0.0;
  1063. result.y = 0.0;
  1064. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1065. }
  1066. else {
  1067. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1068. result.y = Math.PI;
  1069. result.z = 0.0;
  1070. }
  1071. }
  1072. };
  1073. Quaternion.prototype.toRotationMatrix = function (result) {
  1074. var xx = this.x * this.x;
  1075. var yy = this.y * this.y;
  1076. var zz = this.z * this.z;
  1077. var xy = this.x * this.y;
  1078. var zw = this.z * this.w;
  1079. var zx = this.z * this.x;
  1080. var yw = this.y * this.w;
  1081. var yz = this.y * this.z;
  1082. var xw = this.x * this.w;
  1083. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1084. result.m[1] = 2.0 * (xy + zw);
  1085. result.m[2] = 2.0 * (zx - yw);
  1086. result.m[3] = 0;
  1087. result.m[4] = 2.0 * (xy - zw);
  1088. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1089. result.m[6] = 2.0 * (yz + xw);
  1090. result.m[7] = 0;
  1091. result.m[8] = 2.0 * (zx + yw);
  1092. result.m[9] = 2.0 * (yz - xw);
  1093. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1094. result.m[11] = 0;
  1095. result.m[12] = 0;
  1096. result.m[13] = 0;
  1097. result.m[14] = 0;
  1098. result.m[15] = 1.0;
  1099. };
  1100. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1101. var data = matrix.m;
  1102. var m11 = data[0], m12 = data[4], m13 = data[8];
  1103. var m21 = data[1], m22 = data[5], m23 = data[9];
  1104. var m31 = data[2], m32 = data[6], m33 = data[10];
  1105. var trace = m11 + m22 + m33;
  1106. var s;
  1107. if (trace > 0) {
  1108. s = 0.5 / Math.sqrt(trace + 1.0);
  1109. this.w = 0.25 / s;
  1110. this.x = (m32 - m23) * s;
  1111. this.y = (m13 - m31) * s;
  1112. this.z = (m21 - m12) * s;
  1113. return;
  1114. }
  1115. if (m11 > m22 && m11 > m33) {
  1116. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1117. this.w = (m32 - m23) / s;
  1118. this.x = 0.25 * s;
  1119. this.y = (m12 + m21) / s;
  1120. this.z = (m13 + m31) / s;
  1121. return;
  1122. }
  1123. if (m22 > m33) {
  1124. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1125. this.w = (m13 - m31) / s;
  1126. this.x = (m12 + m21) / s;
  1127. this.y = 0.25 * s;
  1128. this.z = (m23 + m32) / s;
  1129. return;
  1130. }
  1131. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1132. this.w = (m21 - m12) / s;
  1133. this.x = (m13 + m31) / s;
  1134. this.y = (m23 + m32) / s;
  1135. this.z = 0.25 * s;
  1136. };
  1137. // Statics
  1138. Quaternion.Inverse = function (q) {
  1139. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1140. };
  1141. Quaternion.Identity = function () {
  1142. return new Quaternion(0, 0, 0, 1);
  1143. };
  1144. Quaternion.RotationAxis = function (axis, angle) {
  1145. var result = new Quaternion();
  1146. var sin = Math.sin(angle / 2);
  1147. result.w = Math.cos(angle / 2);
  1148. result.x = axis.x * sin;
  1149. result.y = axis.y * sin;
  1150. result.z = axis.z * sin;
  1151. return result;
  1152. };
  1153. Quaternion.FromArray = function (array, offset) {
  1154. if (!offset) {
  1155. offset = 0;
  1156. }
  1157. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1158. };
  1159. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1160. var result = new Quaternion();
  1161. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1162. return result;
  1163. };
  1164. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1165. var halfRoll = roll * 0.5;
  1166. var halfPitch = pitch * 0.5;
  1167. var halfYaw = yaw * 0.5;
  1168. var sinRoll = Math.sin(halfRoll);
  1169. var cosRoll = Math.cos(halfRoll);
  1170. var sinPitch = Math.sin(halfPitch);
  1171. var cosPitch = Math.cos(halfPitch);
  1172. var sinYaw = Math.sin(halfYaw);
  1173. var cosYaw = Math.cos(halfYaw);
  1174. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1175. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1176. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1177. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1178. };
  1179. Quaternion.Slerp = function (left, right, amount) {
  1180. var num2;
  1181. var num3;
  1182. var num = amount;
  1183. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1184. var flag = false;
  1185. if (num4 < 0) {
  1186. flag = true;
  1187. num4 = -num4;
  1188. }
  1189. if (num4 > 0.999999) {
  1190. num3 = 1 - num;
  1191. num2 = flag ? -num : num;
  1192. }
  1193. else {
  1194. var num5 = Math.acos(num4);
  1195. var num6 = (1.0 / Math.sin(num5));
  1196. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1197. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1198. }
  1199. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1200. };
  1201. return Quaternion;
  1202. })();
  1203. BABYLON.Quaternion = Quaternion;
  1204. var Matrix = (function () {
  1205. function Matrix() {
  1206. this.m = new Float32Array(16);
  1207. }
  1208. // Properties
  1209. Matrix.prototype.isIdentity = function () {
  1210. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1211. return false;
  1212. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1213. return false;
  1214. return true;
  1215. };
  1216. Matrix.prototype.determinant = function () {
  1217. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1218. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1219. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1220. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1221. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1222. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1223. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1224. };
  1225. // Methods
  1226. Matrix.prototype.toArray = function () {
  1227. return this.m;
  1228. };
  1229. Matrix.prototype.asArray = function () {
  1230. return this.toArray();
  1231. };
  1232. Matrix.prototype.invert = function () {
  1233. this.invertToRef(this);
  1234. };
  1235. Matrix.prototype.invertToRef = function (other) {
  1236. var l1 = this.m[0];
  1237. var l2 = this.m[1];
  1238. var l3 = this.m[2];
  1239. var l4 = this.m[3];
  1240. var l5 = this.m[4];
  1241. var l6 = this.m[5];
  1242. var l7 = this.m[6];
  1243. var l8 = this.m[7];
  1244. var l9 = this.m[8];
  1245. var l10 = this.m[9];
  1246. var l11 = this.m[10];
  1247. var l12 = this.m[11];
  1248. var l13 = this.m[12];
  1249. var l14 = this.m[13];
  1250. var l15 = this.m[14];
  1251. var l16 = this.m[15];
  1252. var l17 = (l11 * l16) - (l12 * l15);
  1253. var l18 = (l10 * l16) - (l12 * l14);
  1254. var l19 = (l10 * l15) - (l11 * l14);
  1255. var l20 = (l9 * l16) - (l12 * l13);
  1256. var l21 = (l9 * l15) - (l11 * l13);
  1257. var l22 = (l9 * l14) - (l10 * l13);
  1258. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1259. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1260. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1261. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1262. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1263. var l28 = (l7 * l16) - (l8 * l15);
  1264. var l29 = (l6 * l16) - (l8 * l14);
  1265. var l30 = (l6 * l15) - (l7 * l14);
  1266. var l31 = (l5 * l16) - (l8 * l13);
  1267. var l32 = (l5 * l15) - (l7 * l13);
  1268. var l33 = (l5 * l14) - (l6 * l13);
  1269. var l34 = (l7 * l12) - (l8 * l11);
  1270. var l35 = (l6 * l12) - (l8 * l10);
  1271. var l36 = (l6 * l11) - (l7 * l10);
  1272. var l37 = (l5 * l12) - (l8 * l9);
  1273. var l38 = (l5 * l11) - (l7 * l9);
  1274. var l39 = (l5 * l10) - (l6 * l9);
  1275. other.m[0] = l23 * l27;
  1276. other.m[4] = l24 * l27;
  1277. other.m[8] = l25 * l27;
  1278. other.m[12] = l26 * l27;
  1279. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1280. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1281. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1282. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1283. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1284. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1285. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1286. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1287. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1288. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1289. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1290. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1291. };
  1292. Matrix.prototype.setTranslation = function (vector3) {
  1293. this.m[12] = vector3.x;
  1294. this.m[13] = vector3.y;
  1295. this.m[14] = vector3.z;
  1296. };
  1297. Matrix.prototype.multiply = function (other) {
  1298. var result = new Matrix();
  1299. this.multiplyToRef(other, result);
  1300. return result;
  1301. };
  1302. Matrix.prototype.copyFrom = function (other) {
  1303. for (var index = 0; index < 16; index++) {
  1304. this.m[index] = other.m[index];
  1305. }
  1306. };
  1307. Matrix.prototype.copyToArray = function (array, offset) {
  1308. if (offset === void 0) { offset = 0; }
  1309. for (var index = 0; index < 16; index++) {
  1310. array[offset + index] = this.m[index];
  1311. }
  1312. };
  1313. Matrix.prototype.multiplyToRef = function (other, result) {
  1314. this.multiplyToArray(other, result.m, 0);
  1315. };
  1316. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1317. var tm0 = this.m[0];
  1318. var tm1 = this.m[1];
  1319. var tm2 = this.m[2];
  1320. var tm3 = this.m[3];
  1321. var tm4 = this.m[4];
  1322. var tm5 = this.m[5];
  1323. var tm6 = this.m[6];
  1324. var tm7 = this.m[7];
  1325. var tm8 = this.m[8];
  1326. var tm9 = this.m[9];
  1327. var tm10 = this.m[10];
  1328. var tm11 = this.m[11];
  1329. var tm12 = this.m[12];
  1330. var tm13 = this.m[13];
  1331. var tm14 = this.m[14];
  1332. var tm15 = this.m[15];
  1333. var om0 = other.m[0];
  1334. var om1 = other.m[1];
  1335. var om2 = other.m[2];
  1336. var om3 = other.m[3];
  1337. var om4 = other.m[4];
  1338. var om5 = other.m[5];
  1339. var om6 = other.m[6];
  1340. var om7 = other.m[7];
  1341. var om8 = other.m[8];
  1342. var om9 = other.m[9];
  1343. var om10 = other.m[10];
  1344. var om11 = other.m[11];
  1345. var om12 = other.m[12];
  1346. var om13 = other.m[13];
  1347. var om14 = other.m[14];
  1348. var om15 = other.m[15];
  1349. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1350. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1351. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1352. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1353. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1354. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1355. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1356. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1357. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1358. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1359. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1360. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1361. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1362. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1363. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1364. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1365. };
  1366. Matrix.prototype.equals = function (value) {
  1367. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1368. };
  1369. Matrix.prototype.clone = function () {
  1370. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1371. };
  1372. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1373. translation.x = this.m[12];
  1374. translation.y = this.m[13];
  1375. translation.z = this.m[14];
  1376. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1377. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1378. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1379. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1380. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1381. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1382. if (scale.x == 0 || scale.y == 0 || scale.z == 0) {
  1383. rotation.x = 0;
  1384. rotation.y = 0;
  1385. rotation.z = 0;
  1386. rotation.w = 1;
  1387. return false;
  1388. }
  1389. var rotationMatrix = BABYLON.Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1390. rotation.fromRotationMatrix(rotationMatrix);
  1391. return true;
  1392. };
  1393. // Statics
  1394. Matrix.FromArray = function (array, offset) {
  1395. var result = new Matrix();
  1396. if (!offset) {
  1397. offset = 0;
  1398. }
  1399. Matrix.FromArrayToRef(array, offset, result);
  1400. return result;
  1401. };
  1402. Matrix.FromArrayToRef = function (array, offset, result) {
  1403. for (var index = 0; index < 16; index++) {
  1404. result.m[index] = array[index + offset];
  1405. }
  1406. };
  1407. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1408. result.m[0] = initialM11;
  1409. result.m[1] = initialM12;
  1410. result.m[2] = initialM13;
  1411. result.m[3] = initialM14;
  1412. result.m[4] = initialM21;
  1413. result.m[5] = initialM22;
  1414. result.m[6] = initialM23;
  1415. result.m[7] = initialM24;
  1416. result.m[8] = initialM31;
  1417. result.m[9] = initialM32;
  1418. result.m[10] = initialM33;
  1419. result.m[11] = initialM34;
  1420. result.m[12] = initialM41;
  1421. result.m[13] = initialM42;
  1422. result.m[14] = initialM43;
  1423. result.m[15] = initialM44;
  1424. };
  1425. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1426. var result = new Matrix();
  1427. result.m[0] = initialM11;
  1428. result.m[1] = initialM12;
  1429. result.m[2] = initialM13;
  1430. result.m[3] = initialM14;
  1431. result.m[4] = initialM21;
  1432. result.m[5] = initialM22;
  1433. result.m[6] = initialM23;
  1434. result.m[7] = initialM24;
  1435. result.m[8] = initialM31;
  1436. result.m[9] = initialM32;
  1437. result.m[10] = initialM33;
  1438. result.m[11] = initialM34;
  1439. result.m[12] = initialM41;
  1440. result.m[13] = initialM42;
  1441. result.m[14] = initialM43;
  1442. result.m[15] = initialM44;
  1443. return result;
  1444. };
  1445. Matrix.Compose = function (scale, rotation, translation) {
  1446. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1447. var rotationMatrix = Matrix.Identity();
  1448. rotation.toRotationMatrix(rotationMatrix);
  1449. result = result.multiply(rotationMatrix);
  1450. result.setTranslation(translation);
  1451. return result;
  1452. };
  1453. Matrix.Identity = function () {
  1454. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1455. };
  1456. Matrix.IdentityToRef = function (result) {
  1457. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1458. };
  1459. Matrix.Zero = function () {
  1460. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1461. };
  1462. Matrix.RotationX = function (angle) {
  1463. var result = new Matrix();
  1464. Matrix.RotationXToRef(angle, result);
  1465. return result;
  1466. };
  1467. Matrix.Invert = function (source) {
  1468. var result = new Matrix();
  1469. source.invertToRef(result);
  1470. return result;
  1471. };
  1472. Matrix.RotationXToRef = function (angle, result) {
  1473. var s = Math.sin(angle);
  1474. var c = Math.cos(angle);
  1475. result.m[0] = 1.0;
  1476. result.m[15] = 1.0;
  1477. result.m[5] = c;
  1478. result.m[10] = c;
  1479. result.m[9] = -s;
  1480. result.m[6] = s;
  1481. result.m[1] = 0;
  1482. result.m[2] = 0;
  1483. result.m[3] = 0;
  1484. result.m[4] = 0;
  1485. result.m[7] = 0;
  1486. result.m[8] = 0;
  1487. result.m[11] = 0;
  1488. result.m[12] = 0;
  1489. result.m[13] = 0;
  1490. result.m[14] = 0;
  1491. };
  1492. Matrix.RotationY = function (angle) {
  1493. var result = new Matrix();
  1494. Matrix.RotationYToRef(angle, result);
  1495. return result;
  1496. };
  1497. Matrix.RotationYToRef = function (angle, result) {
  1498. var s = Math.sin(angle);
  1499. var c = Math.cos(angle);
  1500. result.m[5] = 1.0;
  1501. result.m[15] = 1.0;
  1502. result.m[0] = c;
  1503. result.m[2] = -s;
  1504. result.m[8] = s;
  1505. result.m[10] = c;
  1506. result.m[1] = 0;
  1507. result.m[3] = 0;
  1508. result.m[4] = 0;
  1509. result.m[6] = 0;
  1510. result.m[7] = 0;
  1511. result.m[9] = 0;
  1512. result.m[11] = 0;
  1513. result.m[12] = 0;
  1514. result.m[13] = 0;
  1515. result.m[14] = 0;
  1516. };
  1517. Matrix.RotationZ = function (angle) {
  1518. var result = new Matrix();
  1519. Matrix.RotationZToRef(angle, result);
  1520. return result;
  1521. };
  1522. Matrix.RotationZToRef = function (angle, result) {
  1523. var s = Math.sin(angle);
  1524. var c = Math.cos(angle);
  1525. result.m[10] = 1.0;
  1526. result.m[15] = 1.0;
  1527. result.m[0] = c;
  1528. result.m[1] = s;
  1529. result.m[4] = -s;
  1530. result.m[5] = c;
  1531. result.m[2] = 0;
  1532. result.m[3] = 0;
  1533. result.m[6] = 0;
  1534. result.m[7] = 0;
  1535. result.m[8] = 0;
  1536. result.m[9] = 0;
  1537. result.m[11] = 0;
  1538. result.m[12] = 0;
  1539. result.m[13] = 0;
  1540. result.m[14] = 0;
  1541. };
  1542. Matrix.RotationAxis = function (axis, angle) {
  1543. var s = Math.sin(-angle);
  1544. var c = Math.cos(-angle);
  1545. var c1 = 1 - c;
  1546. axis.normalize();
  1547. var result = Matrix.Zero();
  1548. result.m[0] = (axis.x * axis.x) * c1 + c;
  1549. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1550. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1551. result.m[3] = 0.0;
  1552. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1553. result.m[5] = (axis.y * axis.y) * c1 + c;
  1554. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1555. result.m[7] = 0.0;
  1556. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1557. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1558. result.m[10] = (axis.z * axis.z) * c1 + c;
  1559. result.m[11] = 0.0;
  1560. result.m[15] = 1.0;
  1561. return result;
  1562. };
  1563. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1564. var result = new Matrix();
  1565. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1566. return result;
  1567. };
  1568. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1569. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1570. this._tempQuaternion.toRotationMatrix(result);
  1571. };
  1572. Matrix.Scaling = function (x, y, z) {
  1573. var result = Matrix.Zero();
  1574. Matrix.ScalingToRef(x, y, z, result);
  1575. return result;
  1576. };
  1577. Matrix.ScalingToRef = function (x, y, z, result) {
  1578. result.m[0] = x;
  1579. result.m[1] = 0;
  1580. result.m[2] = 0;
  1581. result.m[3] = 0;
  1582. result.m[4] = 0;
  1583. result.m[5] = y;
  1584. result.m[6] = 0;
  1585. result.m[7] = 0;
  1586. result.m[8] = 0;
  1587. result.m[9] = 0;
  1588. result.m[10] = z;
  1589. result.m[11] = 0;
  1590. result.m[12] = 0;
  1591. result.m[13] = 0;
  1592. result.m[14] = 0;
  1593. result.m[15] = 1.0;
  1594. };
  1595. Matrix.Translation = function (x, y, z) {
  1596. var result = Matrix.Identity();
  1597. Matrix.TranslationToRef(x, y, z, result);
  1598. return result;
  1599. };
  1600. Matrix.TranslationToRef = function (x, y, z, result) {
  1601. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1602. };
  1603. Matrix.LookAtLH = function (eye, target, up) {
  1604. var result = Matrix.Zero();
  1605. Matrix.LookAtLHToRef(eye, target, up, result);
  1606. return result;
  1607. };
  1608. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1609. // Z axis
  1610. target.subtractToRef(eye, this._zAxis);
  1611. this._zAxis.normalize();
  1612. // X axis
  1613. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1614. this._xAxis.normalize();
  1615. // Y axis
  1616. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1617. this._yAxis.normalize();
  1618. // Eye angles
  1619. var ex = -Vector3.Dot(this._xAxis, eye);
  1620. var ey = -Vector3.Dot(this._yAxis, eye);
  1621. var ez = -Vector3.Dot(this._zAxis, eye);
  1622. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1623. };
  1624. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1625. var hw = 2.0 / width;
  1626. var hh = 2.0 / height;
  1627. var id = 1.0 / (zfar - znear);
  1628. var nid = znear / (znear - zfar);
  1629. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1630. };
  1631. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1632. var matrix = Matrix.Zero();
  1633. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1634. return matrix;
  1635. };
  1636. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1637. result.m[0] = 2.0 / (right - left);
  1638. result.m[1] = result.m[2] = result.m[3] = 0;
  1639. result.m[5] = 2.0 / (top - bottom);
  1640. result.m[4] = result.m[6] = result.m[7] = 0;
  1641. result.m[10] = -1.0 / (znear - zfar);
  1642. result.m[8] = result.m[9] = result.m[11] = 0;
  1643. result.m[12] = (left + right) / (left - right);
  1644. result.m[13] = (top + bottom) / (bottom - top);
  1645. result.m[14] = znear / (znear - zfar);
  1646. result.m[15] = 1.0;
  1647. };
  1648. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1649. var matrix = Matrix.Zero();
  1650. matrix.m[0] = (2.0 * znear) / width;
  1651. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1652. matrix.m[5] = (2.0 * znear) / height;
  1653. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1654. matrix.m[10] = -zfar / (znear - zfar);
  1655. matrix.m[8] = matrix.m[9] = 0.0;
  1656. matrix.m[11] = 1.0;
  1657. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1658. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1659. return matrix;
  1660. };
  1661. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1662. var matrix = Matrix.Zero();
  1663. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1664. return matrix;
  1665. };
  1666. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1667. var tan = 1.0 / (Math.tan(fov * 0.5));
  1668. result.m[0] = tan / aspect;
  1669. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1670. result.m[5] = tan;
  1671. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1672. result.m[8] = result.m[9] = 0.0;
  1673. result.m[10] = -zfar / (znear - zfar);
  1674. result.m[11] = 1.0;
  1675. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1676. result.m[14] = (znear * zfar) / (znear - zfar);
  1677. };
  1678. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1679. var cw = viewport.width;
  1680. var ch = viewport.height;
  1681. var cx = viewport.x;
  1682. var cy = viewport.y;
  1683. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  1684. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1685. };
  1686. Matrix.Transpose = function (matrix) {
  1687. var result = new Matrix();
  1688. result.m[0] = matrix.m[0];
  1689. result.m[1] = matrix.m[4];
  1690. result.m[2] = matrix.m[8];
  1691. result.m[3] = matrix.m[12];
  1692. result.m[4] = matrix.m[1];
  1693. result.m[5] = matrix.m[5];
  1694. result.m[6] = matrix.m[9];
  1695. result.m[7] = matrix.m[13];
  1696. result.m[8] = matrix.m[2];
  1697. result.m[9] = matrix.m[6];
  1698. result.m[10] = matrix.m[10];
  1699. result.m[11] = matrix.m[14];
  1700. result.m[12] = matrix.m[3];
  1701. result.m[13] = matrix.m[7];
  1702. result.m[14] = matrix.m[11];
  1703. result.m[15] = matrix.m[15];
  1704. return result;
  1705. };
  1706. Matrix.Reflection = function (plane) {
  1707. var matrix = new Matrix();
  1708. Matrix.ReflectionToRef(plane, matrix);
  1709. return matrix;
  1710. };
  1711. Matrix.ReflectionToRef = function (plane, result) {
  1712. plane.normalize();
  1713. var x = plane.normal.x;
  1714. var y = plane.normal.y;
  1715. var z = plane.normal.z;
  1716. var temp = -2 * x;
  1717. var temp2 = -2 * y;
  1718. var temp3 = -2 * z;
  1719. result.m[0] = (temp * x) + 1;
  1720. result.m[1] = temp2 * x;
  1721. result.m[2] = temp3 * x;
  1722. result.m[3] = 0.0;
  1723. result.m[4] = temp * y;
  1724. result.m[5] = (temp2 * y) + 1;
  1725. result.m[6] = temp3 * y;
  1726. result.m[7] = 0.0;
  1727. result.m[8] = temp * z;
  1728. result.m[9] = temp2 * z;
  1729. result.m[10] = (temp3 * z) + 1;
  1730. result.m[11] = 0.0;
  1731. result.m[12] = temp * plane.d;
  1732. result.m[13] = temp2 * plane.d;
  1733. result.m[14] = temp3 * plane.d;
  1734. result.m[15] = 1.0;
  1735. };
  1736. Matrix._tempQuaternion = new Quaternion();
  1737. Matrix._xAxis = Vector3.Zero();
  1738. Matrix._yAxis = Vector3.Zero();
  1739. Matrix._zAxis = Vector3.Zero();
  1740. return Matrix;
  1741. })();
  1742. BABYLON.Matrix = Matrix;
  1743. var Plane = (function () {
  1744. function Plane(a, b, c, d) {
  1745. this.normal = new Vector3(a, b, c);
  1746. this.d = d;
  1747. }
  1748. Plane.prototype.asArray = function () {
  1749. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1750. };
  1751. // Methods
  1752. Plane.prototype.clone = function () {
  1753. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1754. };
  1755. Plane.prototype.normalize = function () {
  1756. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1757. var magnitude = 0;
  1758. if (norm !== 0) {
  1759. magnitude = 1.0 / norm;
  1760. }
  1761. this.normal.x *= magnitude;
  1762. this.normal.y *= magnitude;
  1763. this.normal.z *= magnitude;
  1764. this.d *= magnitude;
  1765. };
  1766. Plane.prototype.transform = function (transformation) {
  1767. var transposedMatrix = Matrix.Transpose(transformation);
  1768. var x = this.normal.x;
  1769. var y = this.normal.y;
  1770. var z = this.normal.z;
  1771. var d = this.d;
  1772. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1773. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1774. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1775. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1776. return new Plane(normalX, normalY, normalZ, finalD);
  1777. };
  1778. Plane.prototype.dotCoordinate = function (point) {
  1779. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1780. };
  1781. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1782. var x1 = point2.x - point1.x;
  1783. var y1 = point2.y - point1.y;
  1784. var z1 = point2.z - point1.z;
  1785. var x2 = point3.x - point1.x;
  1786. var y2 = point3.y - point1.y;
  1787. var z2 = point3.z - point1.z;
  1788. var yz = (y1 * z2) - (z1 * y2);
  1789. var xz = (z1 * x2) - (x1 * z2);
  1790. var xy = (x1 * y2) - (y1 * x2);
  1791. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1792. var invPyth;
  1793. if (pyth !== 0) {
  1794. invPyth = 1.0 / pyth;
  1795. }
  1796. else {
  1797. invPyth = 0;
  1798. }
  1799. this.normal.x = yz * invPyth;
  1800. this.normal.y = xz * invPyth;
  1801. this.normal.z = xy * invPyth;
  1802. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1803. };
  1804. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1805. var dot = Vector3.Dot(this.normal, direction);
  1806. return (dot <= epsilon);
  1807. };
  1808. Plane.prototype.signedDistanceTo = function (point) {
  1809. return Vector3.Dot(point, this.normal) + this.d;
  1810. };
  1811. // Statics
  1812. Plane.FromArray = function (array) {
  1813. return new Plane(array[0], array[1], array[2], array[3]);
  1814. };
  1815. Plane.FromPoints = function (point1, point2, point3) {
  1816. var result = new Plane(0, 0, 0, 0);
  1817. result.copyFromPoints(point1, point2, point3);
  1818. return result;
  1819. };
  1820. Plane.FromPositionAndNormal = function (origin, normal) {
  1821. var result = new Plane(0, 0, 0, 0);
  1822. normal.normalize();
  1823. result.normal = normal;
  1824. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1825. return result;
  1826. };
  1827. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1828. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1829. return Vector3.Dot(point, normal) + d;
  1830. };
  1831. return Plane;
  1832. })();
  1833. BABYLON.Plane = Plane;
  1834. var Viewport = (function () {
  1835. function Viewport(x, y, width, height) {
  1836. this.x = x;
  1837. this.y = y;
  1838. this.width = width;
  1839. this.height = height;
  1840. }
  1841. Viewport.prototype.toGlobal = function (engine) {
  1842. var width = engine.getRenderWidth();
  1843. var height = engine.getRenderHeight();
  1844. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1845. };
  1846. return Viewport;
  1847. })();
  1848. BABYLON.Viewport = Viewport;
  1849. var Frustum = (function () {
  1850. function Frustum() {
  1851. }
  1852. Frustum.GetPlanes = function (transform) {
  1853. var frustumPlanes = [];
  1854. for (var index = 0; index < 6; index++) {
  1855. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1856. }
  1857. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1858. return frustumPlanes;
  1859. };
  1860. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1861. // Near
  1862. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1863. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1864. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1865. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1866. frustumPlanes[0].normalize();
  1867. // Far
  1868. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1869. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1870. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1871. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1872. frustumPlanes[1].normalize();
  1873. // Left
  1874. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1875. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1876. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1877. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1878. frustumPlanes[2].normalize();
  1879. // Right
  1880. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1881. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1882. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1883. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1884. frustumPlanes[3].normalize();
  1885. // Top
  1886. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1887. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1888. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1889. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1890. frustumPlanes[4].normalize();
  1891. // Bottom
  1892. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1893. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1894. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1895. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1896. frustumPlanes[5].normalize();
  1897. };
  1898. return Frustum;
  1899. })();
  1900. BABYLON.Frustum = Frustum;
  1901. var Ray = (function () {
  1902. function Ray(origin, direction, length) {
  1903. if (length === void 0) { length = Number.MAX_VALUE; }
  1904. this.origin = origin;
  1905. this.direction = direction;
  1906. this.length = length;
  1907. }
  1908. // Methods
  1909. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1910. var d = 0.0;
  1911. var maxValue = Number.MAX_VALUE;
  1912. if (Math.abs(this.direction.x) < 0.0000001) {
  1913. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1914. return false;
  1915. }
  1916. }
  1917. else {
  1918. var inv = 1.0 / this.direction.x;
  1919. var min = (minimum.x - this.origin.x) * inv;
  1920. var max = (maximum.x - this.origin.x) * inv;
  1921. if (max === -Infinity) {
  1922. max = Infinity;
  1923. }
  1924. if (min > max) {
  1925. var temp = min;
  1926. min = max;
  1927. max = temp;
  1928. }
  1929. d = Math.max(min, d);
  1930. maxValue = Math.min(max, maxValue);
  1931. if (d > maxValue) {
  1932. return false;
  1933. }
  1934. }
  1935. if (Math.abs(this.direction.y) < 0.0000001) {
  1936. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1937. return false;
  1938. }
  1939. }
  1940. else {
  1941. inv = 1.0 / this.direction.y;
  1942. min = (minimum.y - this.origin.y) * inv;
  1943. max = (maximum.y - this.origin.y) * inv;
  1944. if (max === -Infinity) {
  1945. max = Infinity;
  1946. }
  1947. if (min > max) {
  1948. temp = min;
  1949. min = max;
  1950. max = temp;
  1951. }
  1952. d = Math.max(min, d);
  1953. maxValue = Math.min(max, maxValue);
  1954. if (d > maxValue) {
  1955. return false;
  1956. }
  1957. }
  1958. if (Math.abs(this.direction.z) < 0.0000001) {
  1959. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1960. return false;
  1961. }
  1962. }
  1963. else {
  1964. inv = 1.0 / this.direction.z;
  1965. min = (minimum.z - this.origin.z) * inv;
  1966. max = (maximum.z - this.origin.z) * inv;
  1967. if (max === -Infinity) {
  1968. max = Infinity;
  1969. }
  1970. if (min > max) {
  1971. temp = min;
  1972. min = max;
  1973. max = temp;
  1974. }
  1975. d = Math.max(min, d);
  1976. maxValue = Math.min(max, maxValue);
  1977. if (d > maxValue) {
  1978. return false;
  1979. }
  1980. }
  1981. return true;
  1982. };
  1983. Ray.prototype.intersectsBox = function (box) {
  1984. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1985. };
  1986. Ray.prototype.intersectsSphere = function (sphere) {
  1987. var x = sphere.center.x - this.origin.x;
  1988. var y = sphere.center.y - this.origin.y;
  1989. var z = sphere.center.z - this.origin.z;
  1990. var pyth = (x * x) + (y * y) + (z * z);
  1991. var rr = sphere.radius * sphere.radius;
  1992. if (pyth <= rr) {
  1993. return true;
  1994. }
  1995. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1996. if (dot < 0.0) {
  1997. return false;
  1998. }
  1999. var temp = pyth - (dot * dot);
  2000. return temp <= rr;
  2001. };
  2002. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2003. if (!this._edge1) {
  2004. this._edge1 = Vector3.Zero();
  2005. this._edge2 = Vector3.Zero();
  2006. this._pvec = Vector3.Zero();
  2007. this._tvec = Vector3.Zero();
  2008. this._qvec = Vector3.Zero();
  2009. }
  2010. vertex1.subtractToRef(vertex0, this._edge1);
  2011. vertex2.subtractToRef(vertex0, this._edge2);
  2012. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2013. var det = Vector3.Dot(this._edge1, this._pvec);
  2014. if (det === 0) {
  2015. return null;
  2016. }
  2017. var invdet = 1 / det;
  2018. this.origin.subtractToRef(vertex0, this._tvec);
  2019. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2020. if (bu < 0 || bu > 1.0) {
  2021. return null;
  2022. }
  2023. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2024. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2025. if (bv < 0 || bu + bv > 1.0) {
  2026. return null;
  2027. }
  2028. //check if the distance is longer than the predefined length.
  2029. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2030. if (distance > this.length) {
  2031. return null;
  2032. }
  2033. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2034. };
  2035. // Statics
  2036. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2037. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2038. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2039. var direction = end.subtract(start);
  2040. direction.normalize();
  2041. return new Ray(start, direction);
  2042. };
  2043. /**
  2044. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2045. * transformed to the given world matrix.
  2046. * @param origin The origin point
  2047. * @param end The end point
  2048. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2049. */
  2050. Ray.CreateNewFromTo = function (origin, end, world) {
  2051. if (world === void 0) { world = Matrix.Identity(); }
  2052. var direction = end.subtract(origin);
  2053. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2054. direction.normalize();
  2055. return Ray.Transform(new Ray(origin, direction, length), world);
  2056. };
  2057. Ray.Transform = function (ray, matrix) {
  2058. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2059. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2060. return new Ray(newOrigin, newDirection, ray.length);
  2061. };
  2062. return Ray;
  2063. })();
  2064. BABYLON.Ray = Ray;
  2065. (function (Space) {
  2066. Space[Space["LOCAL"] = 0] = "LOCAL";
  2067. Space[Space["WORLD"] = 1] = "WORLD";
  2068. })(BABYLON.Space || (BABYLON.Space = {}));
  2069. var Space = BABYLON.Space;
  2070. var Axis = (function () {
  2071. function Axis() {
  2072. }
  2073. Axis.X = new Vector3(1, 0, 0);
  2074. Axis.Y = new Vector3(0, 1, 0);
  2075. Axis.Z = new Vector3(0, 0, 1);
  2076. return Axis;
  2077. })();
  2078. BABYLON.Axis = Axis;
  2079. ;
  2080. var BezierCurve = (function () {
  2081. function BezierCurve() {
  2082. }
  2083. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2084. // Extract X (which is equal to time here)
  2085. var f0 = 1 - 3 * x2 + 3 * x1;
  2086. var f1 = 3 * x2 - 6 * x1;
  2087. var f2 = 3 * x1;
  2088. var refinedT = t;
  2089. for (var i = 0; i < 5; i++) {
  2090. var refinedT2 = refinedT * refinedT;
  2091. var refinedT3 = refinedT2 * refinedT;
  2092. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2093. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2094. refinedT -= (x - t) * slope;
  2095. refinedT = Math.min(1, Math.max(0, refinedT));
  2096. }
  2097. // Resolve cubic bezier for the given x
  2098. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2099. };
  2100. return BezierCurve;
  2101. })();
  2102. BABYLON.BezierCurve = BezierCurve;
  2103. (function (Orientation) {
  2104. Orientation[Orientation["CW"] = 0] = "CW";
  2105. Orientation[Orientation["CCW"] = 1] = "CCW";
  2106. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2107. var Orientation = BABYLON.Orientation;
  2108. var Angle = (function () {
  2109. function Angle(radians) {
  2110. var _this = this;
  2111. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2112. this.radians = function () { return _this._radians; };
  2113. this._radians = radians;
  2114. if (this._radians < 0)
  2115. this._radians += (2 * Math.PI);
  2116. }
  2117. Angle.BetweenTwoPoints = function (a, b) {
  2118. var delta = b.subtract(a);
  2119. var theta = Math.atan2(delta.y, delta.x);
  2120. return new Angle(theta);
  2121. };
  2122. Angle.FromRadians = function (radians) {
  2123. return new Angle(radians);
  2124. };
  2125. Angle.FromDegrees = function (degrees) {
  2126. return new Angle(degrees * Math.PI / 180);
  2127. };
  2128. return Angle;
  2129. })();
  2130. BABYLON.Angle = Angle;
  2131. var Arc2 = (function () {
  2132. function Arc2(startPoint, midPoint, endPoint) {
  2133. this.startPoint = startPoint;
  2134. this.midPoint = midPoint;
  2135. this.endPoint = endPoint;
  2136. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2137. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2138. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2139. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2140. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2141. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2142. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2143. var a1 = this.startAngle.degrees();
  2144. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2145. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2146. // angles correction
  2147. if (a2 - a1 > +180.0)
  2148. a2 -= 360.0;
  2149. if (a2 - a1 < -180.0)
  2150. a2 += 360.0;
  2151. if (a3 - a2 > +180.0)
  2152. a3 -= 360.0;
  2153. if (a3 - a2 < -180.0)
  2154. a3 += 360.0;
  2155. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2156. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2157. }
  2158. return Arc2;
  2159. })();
  2160. BABYLON.Arc2 = Arc2;
  2161. var PathCursor = (function () {
  2162. function PathCursor(path) {
  2163. this.path = path;
  2164. this._onchange = new Array();
  2165. this.value = 0;
  2166. this.animations = new Array();
  2167. }
  2168. PathCursor.prototype.getPoint = function () {
  2169. var point = this.path.getPointAtLengthPosition(this.value);
  2170. return new Vector3(point.x, 0, point.y);
  2171. };
  2172. PathCursor.prototype.moveAhead = function (step) {
  2173. if (step === void 0) { step = 0.002; }
  2174. this.move(step);
  2175. };
  2176. PathCursor.prototype.moveBack = function (step) {
  2177. if (step === void 0) { step = 0.002; }
  2178. this.move(-step);
  2179. };
  2180. PathCursor.prototype.move = function (step) {
  2181. if (Math.abs(step) > 1) {
  2182. throw "step size should be less than 1.";
  2183. }
  2184. this.value += step;
  2185. this.ensureLimits();
  2186. this.raiseOnChange();
  2187. };
  2188. PathCursor.prototype.ensureLimits = function () {
  2189. while (this.value > 1) {
  2190. this.value -= 1;
  2191. }
  2192. while (this.value < 0) {
  2193. this.value += 1;
  2194. }
  2195. };
  2196. // used by animation engine
  2197. PathCursor.prototype.markAsDirty = function (propertyName) {
  2198. this.ensureLimits();
  2199. this.raiseOnChange();
  2200. };
  2201. PathCursor.prototype.raiseOnChange = function () {
  2202. var _this = this;
  2203. this._onchange.forEach(function (f) { return f(_this); });
  2204. };
  2205. PathCursor.prototype.onchange = function (f) {
  2206. this._onchange.push(f);
  2207. };
  2208. return PathCursor;
  2209. })();
  2210. BABYLON.PathCursor = PathCursor;
  2211. var Path2 = (function () {
  2212. function Path2(x, y) {
  2213. this._points = [];
  2214. this._length = 0;
  2215. this.closed = false;
  2216. this._points.push(new Vector2(x, y));
  2217. }
  2218. Path2.prototype.addLineTo = function (x, y) {
  2219. if (closed) {
  2220. BABYLON.Tools.Error("cannot add lines to closed paths");
  2221. return this;
  2222. }
  2223. var newPoint = new Vector2(x, y);
  2224. var previousPoint = this._points[this._points.length - 1];
  2225. this._points.push(newPoint);
  2226. this._length += newPoint.subtract(previousPoint).length();
  2227. return this;
  2228. };
  2229. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2230. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2231. if (closed) {
  2232. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2233. return this;
  2234. }
  2235. var startPoint = this._points[this._points.length - 1];
  2236. var midPoint = new Vector2(midX, midY);
  2237. var endPoint = new Vector2(endX, endY);
  2238. var arc = new Arc2(startPoint, midPoint, endPoint);
  2239. var increment = arc.angle.radians() / numberOfSegments;
  2240. if (arc.orientation === 0 /* CW */)
  2241. increment *= -1;
  2242. var currentAngle = arc.startAngle.radians() + increment;
  2243. for (var i = 0; i < numberOfSegments; i++) {
  2244. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2245. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2246. this.addLineTo(x, y);
  2247. currentAngle += increment;
  2248. }
  2249. return this;
  2250. };
  2251. Path2.prototype.close = function () {
  2252. this.closed = true;
  2253. return this;
  2254. };
  2255. Path2.prototype.length = function () {
  2256. var result = this._length;
  2257. if (!this.closed) {
  2258. var lastPoint = this._points[this._points.length - 1];
  2259. var firstPoint = this._points[0];
  2260. result += (firstPoint.subtract(lastPoint).length());
  2261. }
  2262. return result;
  2263. };
  2264. Path2.prototype.getPoints = function () {
  2265. return this._points;
  2266. };
  2267. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2268. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2269. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2270. return;
  2271. }
  2272. var lengthPosition = normalizedLengthPosition * this.length();
  2273. var previousOffset = 0;
  2274. for (var i = 0; i < this._points.length; i++) {
  2275. var j = (i + 1) % this._points.length;
  2276. var a = this._points[i];
  2277. var b = this._points[j];
  2278. var bToA = b.subtract(a);
  2279. var nextOffset = (bToA.length() + previousOffset);
  2280. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2281. var dir = bToA.normalize();
  2282. var localOffset = lengthPosition - previousOffset;
  2283. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2284. }
  2285. previousOffset = nextOffset;
  2286. }
  2287. BABYLON.Tools.Error("internal error");
  2288. };
  2289. Path2.StartingAt = function (x, y) {
  2290. return new Path2(x, y);
  2291. };
  2292. return Path2;
  2293. })();
  2294. BABYLON.Path2 = Path2;
  2295. })(BABYLON || (BABYLON = {}));
  2296. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2297. (function (BABYLON) {
  2298. // Screenshots
  2299. var screenshotCanvas;
  2300. var cloneValue = function (source, destinationObject) {
  2301. if (!source)
  2302. return null;
  2303. if (source instanceof BABYLON.Mesh) {
  2304. return null;
  2305. }
  2306. if (source instanceof BABYLON.SubMesh) {
  2307. return source.clone(destinationObject);
  2308. }
  2309. else if (source.clone) {
  2310. return source.clone();
  2311. }
  2312. return null;
  2313. };
  2314. var Tools = (function () {
  2315. function Tools() {
  2316. }
  2317. Tools.GetFilename = function (path) {
  2318. var index = path.lastIndexOf("/");
  2319. if (index < 0)
  2320. return path;
  2321. return path.substring(index + 1);
  2322. };
  2323. Tools.GetDOMTextContent = function (element) {
  2324. var result = "";
  2325. var child = element.firstChild;
  2326. while (child) {
  2327. if (child.nodeType == 3) {
  2328. result += child.textContent;
  2329. }
  2330. child = child.nextSibling;
  2331. }
  2332. return result;
  2333. };
  2334. Tools.ToDegrees = function (angle) {
  2335. return angle * 180 / Math.PI;
  2336. };
  2337. Tools.ToRadians = function (angle) {
  2338. return angle * Math.PI / 180;
  2339. };
  2340. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2341. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2342. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2343. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2344. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2345. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2346. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2347. }
  2348. return {
  2349. minimum: minimum,
  2350. maximum: maximum
  2351. };
  2352. };
  2353. Tools.ExtractMinAndMax = function (positions, start, count) {
  2354. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2355. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2356. for (var index = start; index < start + count; index++) {
  2357. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2358. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2359. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2360. }
  2361. return {
  2362. minimum: minimum,
  2363. maximum: maximum
  2364. };
  2365. };
  2366. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2367. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2368. return undefined;
  2369. return Array.isArray(obj) ? obj : [obj];
  2370. };
  2371. // Misc.
  2372. Tools.GetPointerPrefix = function () {
  2373. var eventPrefix = "pointer";
  2374. // Check if hand.js is referenced or if the browser natively supports pointer events
  2375. if (!navigator.pointerEnabled) {
  2376. eventPrefix = "mouse";
  2377. }
  2378. return eventPrefix;
  2379. };
  2380. Tools.QueueNewFrame = function (func) {
  2381. if (window.requestAnimationFrame)
  2382. window.requestAnimationFrame(func);
  2383. else if (window.msRequestAnimationFrame)
  2384. window.msRequestAnimationFrame(func);
  2385. else if (window.webkitRequestAnimationFrame)
  2386. window.webkitRequestAnimationFrame(func);
  2387. else if (window.mozRequestAnimationFrame)
  2388. window.mozRequestAnimationFrame(func);
  2389. else if (window.oRequestAnimationFrame)
  2390. window.oRequestAnimationFrame(func);
  2391. else {
  2392. window.setTimeout(func, 16);
  2393. }
  2394. };
  2395. Tools.RequestFullscreen = function (element) {
  2396. if (element.requestFullscreen)
  2397. element.requestFullscreen();
  2398. else if (element.msRequestFullscreen)
  2399. element.msRequestFullscreen();
  2400. else if (element.webkitRequestFullscreen)
  2401. element.webkitRequestFullscreen();
  2402. else if (element.mozRequestFullScreen)
  2403. element.mozRequestFullScreen();
  2404. };
  2405. Tools.ExitFullscreen = function () {
  2406. if (document.exitFullscreen) {
  2407. document.exitFullscreen();
  2408. }
  2409. else if (document.mozCancelFullScreen) {
  2410. document.mozCancelFullScreen();
  2411. }
  2412. else if (document.webkitCancelFullScreen) {
  2413. document.webkitCancelFullScreen();
  2414. }
  2415. else if (document.msCancelFullScreen) {
  2416. document.msCancelFullScreen();
  2417. }
  2418. };
  2419. // External files
  2420. Tools.CleanUrl = function (url) {
  2421. url = url.replace(/#/mg, "%23");
  2422. return url;
  2423. };
  2424. Tools.LoadImage = function (url, onload, onerror, database) {
  2425. url = Tools.CleanUrl(url);
  2426. var img = new Image();
  2427. if (url.substr(0, 5) != "data:")
  2428. img.crossOrigin = 'anonymous';
  2429. img.onload = function () {
  2430. onload(img);
  2431. };
  2432. img.onerror = function (err) {
  2433. onerror(img, err);
  2434. };
  2435. var noIndexedDB = function () {
  2436. img.src = url;
  2437. };
  2438. var loadFromIndexedDB = function () {
  2439. database.loadImageFromDB(url, img);
  2440. };
  2441. //ANY database to do!
  2442. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2443. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2444. }
  2445. else {
  2446. if (url.indexOf("file:") === -1) {
  2447. noIndexedDB();
  2448. }
  2449. else {
  2450. try {
  2451. var textureName = url.substring(5);
  2452. var blobURL;
  2453. try {
  2454. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2455. }
  2456. catch (ex) {
  2457. // Chrome doesn't support oneTimeOnly parameter
  2458. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2459. }
  2460. img.src = blobURL;
  2461. }
  2462. catch (e) {
  2463. Tools.Log("Error while trying to load texture: " + textureName);
  2464. img.src = null;
  2465. }
  2466. }
  2467. }
  2468. return img;
  2469. };
  2470. //ANY
  2471. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2472. url = Tools.CleanUrl(url);
  2473. var noIndexedDB = function () {
  2474. var request = new XMLHttpRequest();
  2475. var loadUrl = Tools.BaseUrl + url;
  2476. request.open('GET', loadUrl, true);
  2477. if (useArrayBuffer) {
  2478. request.responseType = "arraybuffer";
  2479. }
  2480. request.onprogress = progressCallBack;
  2481. request.onreadystatechange = function () {
  2482. if (request.readyState == 4) {
  2483. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2484. callback(!useArrayBuffer ? request.responseText : request.response);
  2485. }
  2486. else {
  2487. if (onError) {
  2488. onError();
  2489. }
  2490. else {
  2491. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2492. }
  2493. }
  2494. }
  2495. };
  2496. request.send(null);
  2497. };
  2498. var loadFromIndexedDB = function () {
  2499. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2500. };
  2501. if (url.indexOf("file:") !== -1) {
  2502. var fileName = url.substring(5);
  2503. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2504. }
  2505. else {
  2506. // Caching all files
  2507. if (database && database.enableSceneOffline) {
  2508. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2509. }
  2510. else {
  2511. noIndexedDB();
  2512. }
  2513. }
  2514. };
  2515. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2516. var reader = new FileReader();
  2517. reader.onload = function (e) {
  2518. callback(e.target.result);
  2519. };
  2520. reader.onprogress = progressCallback;
  2521. reader.readAsDataURL(fileToLoad);
  2522. };
  2523. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2524. var reader = new FileReader();
  2525. reader.onload = function (e) {
  2526. callback(e.target.result);
  2527. };
  2528. reader.onprogress = progressCallBack;
  2529. if (!useArrayBuffer) {
  2530. // Asynchronous read
  2531. reader.readAsText(fileToLoad);
  2532. }
  2533. else {
  2534. reader.readAsArrayBuffer(fileToLoad);
  2535. }
  2536. };
  2537. // Misc.
  2538. Tools.Clamp = function (value, min, max) {
  2539. if (min === void 0) { min = 0; }
  2540. if (max === void 0) { max = 1; }
  2541. return Math.min(max, Math.max(min, value));
  2542. };
  2543. // Returns -1 when value is a negative number and
  2544. // +1 when value is a positive number.
  2545. Tools.Sign = function (value) {
  2546. value = +value; // convert to a number
  2547. if (value === 0 || isNaN(value))
  2548. return value;
  2549. return value > 0 ? 1 : -1;
  2550. };
  2551. Tools.Format = function (value, decimals) {
  2552. if (decimals === void 0) { decimals = 2; }
  2553. return value.toFixed(decimals);
  2554. };
  2555. Tools.CheckExtends = function (v, min, max) {
  2556. if (v.x < min.x)
  2557. min.x = v.x;
  2558. if (v.y < min.y)
  2559. min.y = v.y;
  2560. if (v.z < min.z)
  2561. min.z = v.z;
  2562. if (v.x > max.x)
  2563. max.x = v.x;
  2564. if (v.y > max.y)
  2565. max.y = v.y;
  2566. if (v.z > max.z)
  2567. max.z = v.z;
  2568. };
  2569. Tools.WithinEpsilon = function (a, b, epsilon) {
  2570. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2571. var num = a - b;
  2572. return -epsilon <= num && num <= epsilon;
  2573. };
  2574. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2575. for (var prop in source) {
  2576. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2577. continue;
  2578. }
  2579. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2580. continue;
  2581. }
  2582. var sourceValue = source[prop];
  2583. var typeOfSourceValue = typeof sourceValue;
  2584. if (typeOfSourceValue == "function") {
  2585. continue;
  2586. }
  2587. if (typeOfSourceValue == "object") {
  2588. if (sourceValue instanceof Array) {
  2589. destination[prop] = [];
  2590. if (sourceValue.length > 0) {
  2591. if (typeof sourceValue[0] == "object") {
  2592. for (var index = 0; index < sourceValue.length; index++) {
  2593. var clonedValue = cloneValue(sourceValue[index], destination);
  2594. if (destination[prop].indexOf(clonedValue) === -1) {
  2595. destination[prop].push(clonedValue);
  2596. }
  2597. }
  2598. }
  2599. else {
  2600. destination[prop] = sourceValue.slice(0);
  2601. }
  2602. }
  2603. }
  2604. else {
  2605. destination[prop] = cloneValue(sourceValue, destination);
  2606. }
  2607. }
  2608. else {
  2609. destination[prop] = sourceValue;
  2610. }
  2611. }
  2612. };
  2613. Tools.IsEmpty = function (obj) {
  2614. for (var i in obj) {
  2615. return false;
  2616. }
  2617. return true;
  2618. };
  2619. Tools.RegisterTopRootEvents = function (events) {
  2620. for (var index = 0; index < events.length; index++) {
  2621. var event = events[index];
  2622. window.addEventListener(event.name, event.handler, false);
  2623. try {
  2624. if (window.parent) {
  2625. window.parent.addEventListener(event.name, event.handler, false);
  2626. }
  2627. }
  2628. catch (e) {
  2629. }
  2630. }
  2631. };
  2632. Tools.UnregisterTopRootEvents = function (events) {
  2633. for (var index = 0; index < events.length; index++) {
  2634. var event = events[index];
  2635. window.removeEventListener(event.name, event.handler);
  2636. try {
  2637. if (window.parent) {
  2638. window.parent.removeEventListener(event.name, event.handler);
  2639. }
  2640. }
  2641. catch (e) {
  2642. }
  2643. }
  2644. };
  2645. Tools.CreateScreenshot = function (engine, camera, size) {
  2646. var width;
  2647. var height;
  2648. var scene = camera.getScene();
  2649. var previousCamera = null;
  2650. if (scene.activeCamera !== camera) {
  2651. previousCamera = scene.activeCamera;
  2652. scene.activeCamera = camera;
  2653. }
  2654. //If a precision value is specified
  2655. if (size.precision) {
  2656. width = Math.round(engine.getRenderWidth() * size.precision);
  2657. height = Math.round(width / engine.getAspectRatio(camera));
  2658. size = { width: width, height: height };
  2659. }
  2660. else if (size.width && size.height) {
  2661. width = size.width;
  2662. height = size.height;
  2663. }
  2664. else if (size.width && !size.height) {
  2665. width = size.width;
  2666. height = Math.round(width / engine.getAspectRatio(camera));
  2667. size = { width: width, height: height };
  2668. }
  2669. else if (size.height && !size.width) {
  2670. height = size.height;
  2671. width = Math.round(height * engine.getAspectRatio(camera));
  2672. size = { width: width, height: height };
  2673. }
  2674. else if (!isNaN(size)) {
  2675. height = size;
  2676. width = size;
  2677. }
  2678. else {
  2679. Tools.Error("Invalid 'size' parameter !");
  2680. return;
  2681. }
  2682. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2683. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2684. texture.renderList = scene.meshes;
  2685. texture.onAfterRender = function () {
  2686. // Read the contents of the framebuffer
  2687. var numberOfChannelsByLine = width * 4;
  2688. var halfHeight = height / 2;
  2689. //Reading datas from WebGL
  2690. var data = engine.readPixels(0, 0, width, height);
  2691. for (var i = 0; i < halfHeight; i++) {
  2692. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2693. var currentCell = j + i * numberOfChannelsByLine;
  2694. var targetLine = height - i - 1;
  2695. var targetCell = j + targetLine * numberOfChannelsByLine;
  2696. var temp = data[currentCell];
  2697. data[currentCell] = data[targetCell];
  2698. data[targetCell] = temp;
  2699. }
  2700. }
  2701. // Create a 2D canvas to store the result
  2702. if (!screenshotCanvas) {
  2703. screenshotCanvas = document.createElement('canvas');
  2704. }
  2705. screenshotCanvas.width = width;
  2706. screenshotCanvas.height = height;
  2707. var context = screenshotCanvas.getContext('2d');
  2708. // Copy the pixels to a 2D canvas
  2709. var imageData = context.createImageData(width, height);
  2710. imageData.data.set(data);
  2711. context.putImageData(imageData, 0, 0);
  2712. var base64Image = screenshotCanvas.toDataURL();
  2713. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2714. if (("download" in document.createElement("a"))) {
  2715. var a = window.document.createElement("a");
  2716. a.href = base64Image;
  2717. var date = new Date();
  2718. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2719. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2720. window.document.body.appendChild(a);
  2721. a.addEventListener("click", function () {
  2722. a.parentElement.removeChild(a);
  2723. });
  2724. a.click();
  2725. }
  2726. else {
  2727. var newWindow = window.open("");
  2728. var img = newWindow.document.createElement("img");
  2729. img.src = base64Image;
  2730. newWindow.document.body.appendChild(img);
  2731. }
  2732. };
  2733. texture.render(true);
  2734. texture.dispose();
  2735. if (previousCamera) {
  2736. scene.activeCamera = previousCamera;
  2737. }
  2738. };
  2739. // XHR response validator for local file scenario
  2740. Tools.ValidateXHRData = function (xhr, dataType) {
  2741. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2742. if (dataType === void 0) { dataType = 7; }
  2743. try {
  2744. if (dataType & 1) {
  2745. if (xhr.responseText && xhr.responseText.length > 0) {
  2746. return true;
  2747. }
  2748. else if (dataType === 1) {
  2749. return false;
  2750. }
  2751. }
  2752. if (dataType & 2) {
  2753. // Check header width and height since there is no "TGA" magic number
  2754. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2755. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2756. return true;
  2757. }
  2758. else if (dataType === 2) {
  2759. return false;
  2760. }
  2761. }
  2762. if (dataType & 4) {
  2763. // Check for the "DDS" magic number
  2764. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2765. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2766. return true;
  2767. }
  2768. else {
  2769. return false;
  2770. }
  2771. }
  2772. }
  2773. catch (e) {
  2774. }
  2775. return false;
  2776. };
  2777. Object.defineProperty(Tools, "NoneLogLevel", {
  2778. get: function () {
  2779. return Tools._NoneLogLevel;
  2780. },
  2781. enumerable: true,
  2782. configurable: true
  2783. });
  2784. Object.defineProperty(Tools, "MessageLogLevel", {
  2785. get: function () {
  2786. return Tools._MessageLogLevel;
  2787. },
  2788. enumerable: true,
  2789. configurable: true
  2790. });
  2791. Object.defineProperty(Tools, "WarningLogLevel", {
  2792. get: function () {
  2793. return Tools._WarningLogLevel;
  2794. },
  2795. enumerable: true,
  2796. configurable: true
  2797. });
  2798. Object.defineProperty(Tools, "ErrorLogLevel", {
  2799. get: function () {
  2800. return Tools._ErrorLogLevel;
  2801. },
  2802. enumerable: true,
  2803. configurable: true
  2804. });
  2805. Object.defineProperty(Tools, "AllLogLevel", {
  2806. get: function () {
  2807. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2808. },
  2809. enumerable: true,
  2810. configurable: true
  2811. });
  2812. Tools._AddLogEntry = function (entry) {
  2813. Tools._LogCache = entry + Tools._LogCache;
  2814. if (Tools.OnNewCacheEntry) {
  2815. Tools.OnNewCacheEntry(entry);
  2816. }
  2817. };
  2818. Tools._FormatMessage = function (message) {
  2819. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  2820. var date = new Date();
  2821. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2822. };
  2823. Tools._LogDisabled = function (message) {
  2824. // nothing to do
  2825. };
  2826. Tools._LogEnabled = function (message) {
  2827. var formattedMessage = Tools._FormatMessage(message);
  2828. console.log("BJS - " + formattedMessage);
  2829. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2830. Tools._AddLogEntry(entry);
  2831. };
  2832. Tools._WarnDisabled = function (message) {
  2833. // nothing to do
  2834. };
  2835. Tools._WarnEnabled = function (message) {
  2836. var formattedMessage = Tools._FormatMessage(message);
  2837. console.warn("BJS - " + formattedMessage);
  2838. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2839. Tools._AddLogEntry(entry);
  2840. };
  2841. Tools._ErrorDisabled = function (message) {
  2842. // nothing to do
  2843. };
  2844. Tools._ErrorEnabled = function (message) {
  2845. var formattedMessage = Tools._FormatMessage(message);
  2846. console.error("BJS - " + formattedMessage);
  2847. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2848. Tools._AddLogEntry(entry);
  2849. };
  2850. Object.defineProperty(Tools, "LogCache", {
  2851. get: function () {
  2852. return Tools._LogCache;
  2853. },
  2854. enumerable: true,
  2855. configurable: true
  2856. });
  2857. Object.defineProperty(Tools, "LogLevels", {
  2858. set: function (level) {
  2859. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2860. Tools.Log = Tools._LogEnabled;
  2861. }
  2862. else {
  2863. Tools.Log = Tools._LogDisabled;
  2864. }
  2865. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2866. Tools.Warn = Tools._WarnEnabled;
  2867. }
  2868. else {
  2869. Tools.Warn = Tools._WarnDisabled;
  2870. }
  2871. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2872. Tools.Error = Tools._ErrorEnabled;
  2873. }
  2874. else {
  2875. Tools.Error = Tools._ErrorDisabled;
  2876. }
  2877. },
  2878. enumerable: true,
  2879. configurable: true
  2880. });
  2881. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2882. get: function () {
  2883. return Tools._PerformanceNoneLogLevel;
  2884. },
  2885. enumerable: true,
  2886. configurable: true
  2887. });
  2888. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2889. get: function () {
  2890. return Tools._PerformanceUserMarkLogLevel;
  2891. },
  2892. enumerable: true,
  2893. configurable: true
  2894. });
  2895. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2896. get: function () {
  2897. return Tools._PerformanceConsoleLogLevel;
  2898. },
  2899. enumerable: true,
  2900. configurable: true
  2901. });
  2902. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2903. set: function (level) {
  2904. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2905. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2906. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2907. return;
  2908. }
  2909. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2910. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2911. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2912. return;
  2913. }
  2914. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2915. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2916. },
  2917. enumerable: true,
  2918. configurable: true
  2919. });
  2920. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2921. };
  2922. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2923. };
  2924. Tools._StartUserMark = function (counterName, condition) {
  2925. if (condition === void 0) { condition = true; }
  2926. if (!condition || !Tools._performance.mark) {
  2927. return;
  2928. }
  2929. Tools._performance.mark(counterName + "-Begin");
  2930. };
  2931. Tools._EndUserMark = function (counterName, condition) {
  2932. if (condition === void 0) { condition = true; }
  2933. if (!condition || !Tools._performance.mark) {
  2934. return;
  2935. }
  2936. Tools._performance.mark(counterName + "-End");
  2937. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2938. };
  2939. Tools._StartPerformanceConsole = function (counterName, condition) {
  2940. if (condition === void 0) { condition = true; }
  2941. if (!condition) {
  2942. return;
  2943. }
  2944. Tools._StartUserMark(counterName, condition);
  2945. if (console.time) {
  2946. console.time(counterName);
  2947. }
  2948. };
  2949. Tools._EndPerformanceConsole = function (counterName, condition) {
  2950. if (condition === void 0) { condition = true; }
  2951. if (!condition) {
  2952. return;
  2953. }
  2954. Tools._EndUserMark(counterName, condition);
  2955. if (console.time) {
  2956. console.timeEnd(counterName);
  2957. }
  2958. };
  2959. Object.defineProperty(Tools, "Now", {
  2960. get: function () {
  2961. if (window.performance && window.performance.now) {
  2962. return window.performance.now();
  2963. }
  2964. return new Date().getTime();
  2965. },
  2966. enumerable: true,
  2967. configurable: true
  2968. });
  2969. // Deprecated
  2970. Tools.GetFps = function () {
  2971. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  2972. return 0;
  2973. };
  2974. Tools.BaseUrl = "";
  2975. Tools.GetExponantOfTwo = function (value, max) {
  2976. var count = 1;
  2977. do {
  2978. count *= 2;
  2979. } while (count < value);
  2980. if (count > max)
  2981. count = max;
  2982. return count;
  2983. };
  2984. // Logs
  2985. Tools._NoneLogLevel = 0;
  2986. Tools._MessageLogLevel = 1;
  2987. Tools._WarningLogLevel = 2;
  2988. Tools._ErrorLogLevel = 4;
  2989. Tools._LogCache = "";
  2990. Tools.Log = Tools._LogEnabled;
  2991. Tools.Warn = Tools._WarnEnabled;
  2992. Tools.Error = Tools._ErrorEnabled;
  2993. // Performances
  2994. Tools._PerformanceNoneLogLevel = 0;
  2995. Tools._PerformanceUserMarkLogLevel = 1;
  2996. Tools._PerformanceConsoleLogLevel = 2;
  2997. Tools._performance = window.performance;
  2998. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2999. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3000. return Tools;
  3001. })();
  3002. BABYLON.Tools = Tools;
  3003. /**
  3004. * An implementation of a loop for asynchronous functions.
  3005. */
  3006. var AsyncLoop = (function () {
  3007. /**
  3008. * Constroctor.
  3009. * @param iterations the number of iterations.
  3010. * @param _fn the function to run each iteration
  3011. * @param _successCallback the callback that will be called upon succesful execution
  3012. * @param offset starting offset.
  3013. */
  3014. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3015. if (offset === void 0) { offset = 0; }
  3016. this.iterations = iterations;
  3017. this._fn = _fn;
  3018. this._successCallback = _successCallback;
  3019. this.index = offset - 1;
  3020. this._done = false;
  3021. }
  3022. /**
  3023. * Execute the next iteration. Must be called after the last iteration was finished.
  3024. */
  3025. AsyncLoop.prototype.executeNext = function () {
  3026. if (!this._done) {
  3027. if (this.index + 1 < this.iterations) {
  3028. ++this.index;
  3029. this._fn(this);
  3030. }
  3031. else {
  3032. this.breakLoop();
  3033. }
  3034. }
  3035. };
  3036. /**
  3037. * Break the loop and run the success callback.
  3038. */
  3039. AsyncLoop.prototype.breakLoop = function () {
  3040. this._done = true;
  3041. this._successCallback();
  3042. };
  3043. /**
  3044. * Helper function
  3045. */
  3046. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3047. if (offset === void 0) { offset = 0; }
  3048. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3049. loop.executeNext();
  3050. return loop;
  3051. };
  3052. /**
  3053. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3054. * @param iterations total number of iterations
  3055. * @param syncedIterations number of synchronous iterations in each async iteration.
  3056. * @param fn the function to call each iteration.
  3057. * @param callback a success call back that will be called when iterating stops.
  3058. * @param breakFunction a break condition (optional)
  3059. * @param timeout timeout settings for the setTimeout function. default - 0.
  3060. * @constructor
  3061. */
  3062. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3063. if (timeout === void 0) { timeout = 0; }
  3064. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3065. if (breakFunction && breakFunction())
  3066. loop.breakLoop();
  3067. else {
  3068. setTimeout(function () {
  3069. for (var i = 0; i < syncedIterations; ++i) {
  3070. var iteration = (loop.index * syncedIterations) + i;
  3071. if (iteration >= iterations)
  3072. break;
  3073. fn(iteration);
  3074. if (breakFunction && breakFunction()) {
  3075. loop.breakLoop();
  3076. break;
  3077. }
  3078. }
  3079. loop.executeNext();
  3080. }, timeout);
  3081. }
  3082. }, callback);
  3083. };
  3084. return AsyncLoop;
  3085. })();
  3086. BABYLON.AsyncLoop = AsyncLoop;
  3087. })(BABYLON || (BABYLON = {}));
  3088. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3089. (function (BABYLON) {
  3090. var _DepthCullingState = (function () {
  3091. function _DepthCullingState() {
  3092. this._isDepthTestDirty = false;
  3093. this._isDepthMaskDirty = false;
  3094. this._isDepthFuncDirty = false;
  3095. this._isCullFaceDirty = false;
  3096. this._isCullDirty = false;
  3097. }
  3098. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3099. get: function () {
  3100. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3101. },
  3102. enumerable: true,
  3103. configurable: true
  3104. });
  3105. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3106. get: function () {
  3107. return this._cullFace;
  3108. },
  3109. set: function (value) {
  3110. if (this._cullFace === value) {
  3111. return;
  3112. }
  3113. this._cullFace = value;
  3114. this._isCullFaceDirty = true;
  3115. },
  3116. enumerable: true,
  3117. configurable: true
  3118. });
  3119. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3120. get: function () {
  3121. return this._cull;
  3122. },
  3123. set: function (value) {
  3124. if (this._cull === value) {
  3125. return;
  3126. }
  3127. this._cull = value;
  3128. this._isCullDirty = true;
  3129. },
  3130. enumerable: true,
  3131. configurable: true
  3132. });
  3133. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3134. get: function () {
  3135. return this._depthFunc;
  3136. },
  3137. set: function (value) {
  3138. if (this._depthFunc === value) {
  3139. return;
  3140. }
  3141. this._depthFunc = value;
  3142. this._isDepthFuncDirty = true;
  3143. },
  3144. enumerable: true,
  3145. configurable: true
  3146. });
  3147. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3148. get: function () {
  3149. return this._depthMask;
  3150. },
  3151. set: function (value) {
  3152. if (this._depthMask === value) {
  3153. return;
  3154. }
  3155. this._depthMask = value;
  3156. this._isDepthMaskDirty = true;
  3157. },
  3158. enumerable: true,
  3159. configurable: true
  3160. });
  3161. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3162. get: function () {
  3163. return this._depthTest;
  3164. },
  3165. set: function (value) {
  3166. if (this._depthTest === value) {
  3167. return;
  3168. }
  3169. this._depthTest = value;
  3170. this._isDepthTestDirty = true;
  3171. },
  3172. enumerable: true,
  3173. configurable: true
  3174. });
  3175. _DepthCullingState.prototype.reset = function () {
  3176. this._depthMask = true;
  3177. this._depthTest = true;
  3178. this._depthFunc = null;
  3179. this._cull = null;
  3180. this._cullFace = null;
  3181. this._isDepthTestDirty = true;
  3182. this._isDepthMaskDirty = true;
  3183. this._isDepthFuncDirty = false;
  3184. this._isCullFaceDirty = false;
  3185. this._isCullDirty = false;
  3186. };
  3187. _DepthCullingState.prototype.apply = function (gl) {
  3188. if (!this.isDirty) {
  3189. return;
  3190. }
  3191. // Cull
  3192. if (this._isCullDirty) {
  3193. if (this.cull) {
  3194. gl.enable(gl.CULL_FACE);
  3195. }
  3196. else {
  3197. gl.disable(gl.CULL_FACE);
  3198. }
  3199. this._isCullDirty = false;
  3200. }
  3201. // Cull face
  3202. if (this._isCullFaceDirty) {
  3203. gl.cullFace(this.cullFace);
  3204. this._isCullFaceDirty = false;
  3205. }
  3206. // Depth mask
  3207. if (this._isDepthMaskDirty) {
  3208. gl.depthMask(this.depthMask);
  3209. this._isDepthMaskDirty = false;
  3210. }
  3211. // Depth test
  3212. if (this._isDepthTestDirty) {
  3213. if (this.depthTest) {
  3214. gl.enable(gl.DEPTH_TEST);
  3215. }
  3216. else {
  3217. gl.disable(gl.DEPTH_TEST);
  3218. }
  3219. this._isDepthTestDirty = false;
  3220. }
  3221. // Depth func
  3222. if (this._isDepthFuncDirty) {
  3223. gl.depthFunc(this.depthFunc);
  3224. this._isDepthFuncDirty = false;
  3225. }
  3226. };
  3227. return _DepthCullingState;
  3228. })();
  3229. BABYLON._DepthCullingState = _DepthCullingState;
  3230. var _AlphaState = (function () {
  3231. function _AlphaState() {
  3232. this._isAlphaBlendDirty = false;
  3233. this._isBlendFunctionParametersDirty = false;
  3234. this._alphaBlend = false;
  3235. this._blendFunctionParameters = new Array(4);
  3236. }
  3237. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3238. get: function () {
  3239. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3240. },
  3241. enumerable: true,
  3242. configurable: true
  3243. });
  3244. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3245. get: function () {
  3246. return this._alphaBlend;
  3247. },
  3248. set: function (value) {
  3249. if (this._alphaBlend === value) {
  3250. return;
  3251. }
  3252. this._alphaBlend = value;
  3253. this._isAlphaBlendDirty = true;
  3254. },
  3255. enumerable: true,
  3256. configurable: true
  3257. });
  3258. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3259. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3260. return;
  3261. }
  3262. this._blendFunctionParameters[0] = value0;
  3263. this._blendFunctionParameters[1] = value1;
  3264. this._blendFunctionParameters[2] = value2;
  3265. this._blendFunctionParameters[3] = value3;
  3266. this._isBlendFunctionParametersDirty = true;
  3267. };
  3268. _AlphaState.prototype.reset = function () {
  3269. this._alphaBlend = false;
  3270. this._blendFunctionParameters[0] = null;
  3271. this._blendFunctionParameters[1] = null;
  3272. this._blendFunctionParameters[2] = null;
  3273. this._blendFunctionParameters[3] = null;
  3274. this._isAlphaBlendDirty = true;
  3275. this._isBlendFunctionParametersDirty = false;
  3276. };
  3277. _AlphaState.prototype.apply = function (gl) {
  3278. if (!this.isDirty) {
  3279. return;
  3280. }
  3281. // Alpha blend
  3282. if (this._isAlphaBlendDirty) {
  3283. if (this._alphaBlend) {
  3284. gl.enable(gl.BLEND);
  3285. }
  3286. else {
  3287. gl.disable(gl.BLEND);
  3288. }
  3289. this._isAlphaBlendDirty = false;
  3290. }
  3291. // Alpha function
  3292. if (this._isBlendFunctionParametersDirty) {
  3293. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3294. this._isBlendFunctionParametersDirty = false;
  3295. }
  3296. };
  3297. return _AlphaState;
  3298. })();
  3299. BABYLON._AlphaState = _AlphaState;
  3300. var compileShader = function (gl, source, type, defines) {
  3301. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3302. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3303. gl.compileShader(shader);
  3304. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3305. throw new Error(gl.getShaderInfoLog(shader));
  3306. }
  3307. return shader;
  3308. };
  3309. var getWebGLTextureType = function (gl, type) {
  3310. var textureType = gl.UNSIGNED_BYTE;
  3311. if (type === Engine.TEXTURETYPE_FLOAT)
  3312. textureType = gl.FLOAT;
  3313. return textureType;
  3314. };
  3315. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3316. var magFilter = gl.NEAREST;
  3317. var minFilter = gl.NEAREST;
  3318. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3319. magFilter = gl.LINEAR;
  3320. if (generateMipMaps) {
  3321. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3322. }
  3323. else {
  3324. minFilter = gl.LINEAR;
  3325. }
  3326. }
  3327. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3328. magFilter = gl.LINEAR;
  3329. if (generateMipMaps) {
  3330. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3331. }
  3332. else {
  3333. minFilter = gl.LINEAR;
  3334. }
  3335. }
  3336. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3337. magFilter = gl.NEAREST;
  3338. if (generateMipMaps) {
  3339. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3340. }
  3341. else {
  3342. minFilter = gl.NEAREST;
  3343. }
  3344. }
  3345. return {
  3346. min: minFilter,
  3347. mag: magFilter
  3348. };
  3349. };
  3350. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3351. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3352. var engine = scene.getEngine();
  3353. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3354. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3355. gl.bindTexture(gl.TEXTURE_2D, texture);
  3356. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3357. processFunction(potWidth, potHeight);
  3358. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3359. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3360. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3361. if (!noMipmap && !isCompressed) {
  3362. gl.generateMipmap(gl.TEXTURE_2D);
  3363. }
  3364. gl.bindTexture(gl.TEXTURE_2D, null);
  3365. engine._activeTexturesCache = [];
  3366. texture._baseWidth = width;
  3367. texture._baseHeight = height;
  3368. texture._width = potWidth;
  3369. texture._height = potHeight;
  3370. texture.isReady = true;
  3371. texture.samplingMode = samplingMode;
  3372. scene._removePendingData(texture);
  3373. };
  3374. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3375. var onload = function () {
  3376. loadedImages[index] = img;
  3377. loadedImages._internalCount++;
  3378. scene._removePendingData(img);
  3379. if (loadedImages._internalCount === 6) {
  3380. onfinish(loadedImages);
  3381. }
  3382. };
  3383. var onerror = function () {
  3384. scene._removePendingData(img);
  3385. };
  3386. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3387. scene._addPendingData(img);
  3388. };
  3389. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3390. var loadedImages = [];
  3391. loadedImages._internalCount = 0;
  3392. for (var index = 0; index < 6; index++) {
  3393. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3394. }
  3395. };
  3396. var EngineCapabilities = (function () {
  3397. function EngineCapabilities() {
  3398. }
  3399. return EngineCapabilities;
  3400. })();
  3401. BABYLON.EngineCapabilities = EngineCapabilities;
  3402. /**
  3403. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3404. */
  3405. var Engine = (function () {
  3406. /**
  3407. * @constructor
  3408. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3409. * @param {boolean} [antialias] - enable antialias
  3410. * @param options - further options to be sent to the getContext function
  3411. */
  3412. function Engine(canvas, antialias, options) {
  3413. var _this = this;
  3414. // Public members
  3415. this.isFullscreen = false;
  3416. this.isPointerLock = false;
  3417. this.cullBackFaces = true;
  3418. this.renderEvenInBackground = true;
  3419. this.scenes = new Array();
  3420. this._windowIsBackground = false;
  3421. this._loadingDivBackgroundColor = "black";
  3422. this._drawCalls = 0;
  3423. this._renderingQueueLaunched = false;
  3424. this._activeRenderLoops = [];
  3425. // FPS
  3426. this.fpsRange = 60;
  3427. this.previousFramesDuration = [];
  3428. this.fps = 60;
  3429. this.deltaTime = 0;
  3430. // States
  3431. this._depthCullingState = new _DepthCullingState();
  3432. this._alphaState = new _AlphaState();
  3433. this._alphaMode = Engine.ALPHA_DISABLE;
  3434. // Cache
  3435. this._loadedTexturesCache = new Array();
  3436. this._activeTexturesCache = new Array();
  3437. this._compiledEffects = {};
  3438. this._uintIndicesCurrentlySet = false;
  3439. this._renderingCanvas = canvas;
  3440. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3441. options = options || {};
  3442. options.antialias = antialias;
  3443. try {
  3444. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3445. }
  3446. catch (e) {
  3447. throw new Error("WebGL not supported");
  3448. }
  3449. if (!this._gl) {
  3450. throw new Error("WebGL not supported");
  3451. }
  3452. this._onBlur = function () {
  3453. _this._windowIsBackground = true;
  3454. };
  3455. this._onFocus = function () {
  3456. _this._windowIsBackground = false;
  3457. };
  3458. window.addEventListener("blur", this._onBlur);
  3459. window.addEventListener("focus", this._onFocus);
  3460. // Textures
  3461. this._workingCanvas = document.createElement("canvas");
  3462. this._workingContext = this._workingCanvas.getContext("2d");
  3463. // Viewport
  3464. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3465. this.resize();
  3466. // Caps
  3467. this._caps = new EngineCapabilities();
  3468. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3469. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3470. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3471. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3472. // Infos
  3473. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3474. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3475. if (rendererInfo != null) {
  3476. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3477. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3478. }
  3479. if (!this._glVendor) {
  3480. this._glVendor = "Unknown vendor";
  3481. }
  3482. if (!this._glRenderer) {
  3483. this._glRenderer = "Unknown renderer";
  3484. }
  3485. // Extensions
  3486. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3487. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3488. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3489. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  3490. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3491. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3492. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3493. // Depth buffer
  3494. this.setDepthBuffer(true);
  3495. this.setDepthFunctionToLessOrEqual();
  3496. this.setDepthWrite(true);
  3497. // Fullscreen
  3498. this._onFullscreenChange = function () {
  3499. if (document.fullscreen !== undefined) {
  3500. _this.isFullscreen = document.fullscreen;
  3501. }
  3502. else if (document.mozFullScreen !== undefined) {
  3503. _this.isFullscreen = document.mozFullScreen;
  3504. }
  3505. else if (document.webkitIsFullScreen !== undefined) {
  3506. _this.isFullscreen = document.webkitIsFullScreen;
  3507. }
  3508. else if (document.msIsFullScreen !== undefined) {
  3509. _this.isFullscreen = document.msIsFullScreen;
  3510. }
  3511. // Pointer lock
  3512. if (_this.isFullscreen && _this._pointerLockRequested) {
  3513. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3514. if (canvas.requestPointerLock) {
  3515. canvas.requestPointerLock();
  3516. }
  3517. }
  3518. };
  3519. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3520. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3521. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3522. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3523. // Pointer lock
  3524. this._onPointerLockChange = function () {
  3525. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3526. };
  3527. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3528. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3529. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3530. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3531. if (!Engine.audioEngine) {
  3532. Engine.audioEngine = new BABYLON.AudioEngine();
  3533. }
  3534. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3535. }
  3536. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3537. get: function () {
  3538. return Engine._ALPHA_DISABLE;
  3539. },
  3540. enumerable: true,
  3541. configurable: true
  3542. });
  3543. Object.defineProperty(Engine, "ALPHA_ADD", {
  3544. get: function () {
  3545. return Engine._ALPHA_ADD;
  3546. },
  3547. enumerable: true,
  3548. configurable: true
  3549. });
  3550. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3551. get: function () {
  3552. return Engine._ALPHA_COMBINE;
  3553. },
  3554. enumerable: true,
  3555. configurable: true
  3556. });
  3557. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3558. get: function () {
  3559. return Engine._DELAYLOADSTATE_NONE;
  3560. },
  3561. enumerable: true,
  3562. configurable: true
  3563. });
  3564. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3565. get: function () {
  3566. return Engine._DELAYLOADSTATE_LOADED;
  3567. },
  3568. enumerable: true,
  3569. configurable: true
  3570. });
  3571. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3572. get: function () {
  3573. return Engine._DELAYLOADSTATE_LOADING;
  3574. },
  3575. enumerable: true,
  3576. configurable: true
  3577. });
  3578. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3579. get: function () {
  3580. return Engine._DELAYLOADSTATE_NOTLOADED;
  3581. },
  3582. enumerable: true,
  3583. configurable: true
  3584. });
  3585. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3586. get: function () {
  3587. return Engine._TEXTUREFORMAT_ALPHA;
  3588. },
  3589. enumerable: true,
  3590. configurable: true
  3591. });
  3592. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3593. get: function () {
  3594. return Engine._TEXTUREFORMAT_LUMINANCE;
  3595. },
  3596. enumerable: true,
  3597. configurable: true
  3598. });
  3599. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3600. get: function () {
  3601. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3602. },
  3603. enumerable: true,
  3604. configurable: true
  3605. });
  3606. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3607. get: function () {
  3608. return Engine._TEXTUREFORMAT_RGB;
  3609. },
  3610. enumerable: true,
  3611. configurable: true
  3612. });
  3613. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3614. get: function () {
  3615. return Engine._TEXTUREFORMAT_RGBA;
  3616. },
  3617. enumerable: true,
  3618. configurable: true
  3619. });
  3620. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3621. get: function () {
  3622. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3623. },
  3624. enumerable: true,
  3625. configurable: true
  3626. });
  3627. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3628. get: function () {
  3629. return Engine._TEXTURETYPE_FLOAT;
  3630. },
  3631. enumerable: true,
  3632. configurable: true
  3633. });
  3634. Object.defineProperty(Engine, "Version", {
  3635. get: function () {
  3636. return "2.0.0";
  3637. },
  3638. enumerable: true,
  3639. configurable: true
  3640. });
  3641. Engine.prototype.getGlInfo = function () {
  3642. return {
  3643. vendor: this._glVendor,
  3644. renderer: this._glRenderer,
  3645. version: this._glVersion
  3646. };
  3647. };
  3648. Engine.prototype.getAudioEngine = function () {
  3649. return Engine.audioEngine;
  3650. };
  3651. Engine.prototype.getAspectRatio = function (camera) {
  3652. var viewport = camera.viewport;
  3653. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3654. };
  3655. Engine.prototype.getRenderWidth = function () {
  3656. if (this._currentRenderTarget) {
  3657. return this._currentRenderTarget._width;
  3658. }
  3659. return this._renderingCanvas.width;
  3660. };
  3661. Engine.prototype.getRenderHeight = function () {
  3662. if (this._currentRenderTarget) {
  3663. return this._currentRenderTarget._height;
  3664. }
  3665. return this._renderingCanvas.height;
  3666. };
  3667. Engine.prototype.getRenderingCanvas = function () {
  3668. return this._renderingCanvas;
  3669. };
  3670. Engine.prototype.getRenderingCanvasClientRect = function () {
  3671. return this._renderingCanvas.getBoundingClientRect();
  3672. };
  3673. Engine.prototype.setHardwareScalingLevel = function (level) {
  3674. this._hardwareScalingLevel = level;
  3675. this.resize();
  3676. };
  3677. Engine.prototype.getHardwareScalingLevel = function () {
  3678. return this._hardwareScalingLevel;
  3679. };
  3680. Engine.prototype.getLoadedTexturesCache = function () {
  3681. return this._loadedTexturesCache;
  3682. };
  3683. Engine.prototype.getCaps = function () {
  3684. return this._caps;
  3685. };
  3686. Object.defineProperty(Engine.prototype, "drawCalls", {
  3687. get: function () {
  3688. return this._drawCalls;
  3689. },
  3690. enumerable: true,
  3691. configurable: true
  3692. });
  3693. // Methods
  3694. Engine.prototype.resetDrawCalls = function () {
  3695. this._drawCalls = 0;
  3696. };
  3697. Engine.prototype.setDepthFunctionToGreater = function () {
  3698. this._depthCullingState.depthFunc = this._gl.GREATER;
  3699. };
  3700. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3701. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3702. };
  3703. Engine.prototype.setDepthFunctionToLess = function () {
  3704. this._depthCullingState.depthFunc = this._gl.LESS;
  3705. };
  3706. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3707. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3708. };
  3709. /**
  3710. * stop executing a render loop function and remove it from the execution array
  3711. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  3712. */
  3713. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3714. if (!renderFunction) {
  3715. this._activeRenderLoops = [];
  3716. return;
  3717. }
  3718. var index = this._activeRenderLoops.indexOf(renderFunction);
  3719. if (index >= 0) {
  3720. this._activeRenderLoops.splice(index, 1);
  3721. }
  3722. };
  3723. Engine.prototype._renderLoop = function () {
  3724. var _this = this;
  3725. var shouldRender = true;
  3726. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3727. shouldRender = false;
  3728. }
  3729. if (shouldRender) {
  3730. // Start new frame
  3731. this.beginFrame();
  3732. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3733. var renderFunction = this._activeRenderLoops[index];
  3734. renderFunction();
  3735. }
  3736. // Present
  3737. this.endFrame();
  3738. }
  3739. if (this._activeRenderLoops.length > 0) {
  3740. // Register new frame
  3741. BABYLON.Tools.QueueNewFrame(function () {
  3742. _this._renderLoop();
  3743. });
  3744. }
  3745. else {
  3746. this._renderingQueueLaunched = false;
  3747. }
  3748. };
  3749. /**
  3750. * Register and execute a render loop. The engine can have more than one render function.
  3751. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  3752. * @example
  3753. * engine.runRenderLoop(function () {
  3754. * scene.render()
  3755. * })
  3756. */
  3757. Engine.prototype.runRenderLoop = function (renderFunction) {
  3758. var _this = this;
  3759. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3760. return;
  3761. }
  3762. this._activeRenderLoops.push(renderFunction);
  3763. if (!this._renderingQueueLaunched) {
  3764. this._renderingQueueLaunched = true;
  3765. BABYLON.Tools.QueueNewFrame(function () {
  3766. _this._renderLoop();
  3767. });
  3768. }
  3769. };
  3770. /**
  3771. * Toggle full screen mode.
  3772. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  3773. */
  3774. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3775. if (this.isFullscreen) {
  3776. BABYLON.Tools.ExitFullscreen();
  3777. }
  3778. else {
  3779. this._pointerLockRequested = requestPointerLock;
  3780. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3781. }
  3782. };
  3783. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3784. this.applyStates();
  3785. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3786. if (this._depthCullingState.depthMask) {
  3787. this._gl.clearDepth(1.0);
  3788. }
  3789. var mode = 0;
  3790. if (backBuffer)
  3791. mode |= this._gl.COLOR_BUFFER_BIT;
  3792. if (depthStencil && this._depthCullingState.depthMask)
  3793. mode |= this._gl.DEPTH_BUFFER_BIT;
  3794. this._gl.clear(mode);
  3795. };
  3796. /**
  3797. * Set the WebGL's viewport
  3798. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  3799. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  3800. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  3801. */
  3802. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3803. var width = requiredWidth || this._renderingCanvas.width;
  3804. var height = requiredHeight || this._renderingCanvas.height;
  3805. var x = viewport.x || 0;
  3806. var y = viewport.y || 0;
  3807. this._cachedViewport = viewport;
  3808. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3809. };
  3810. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3811. this._cachedViewport = null;
  3812. this._gl.viewport(x, y, width, height);
  3813. };
  3814. Engine.prototype.beginFrame = function () {
  3815. this._measureFps();
  3816. };
  3817. Engine.prototype.endFrame = function () {
  3818. this.flushFramebuffer();
  3819. };
  3820. /**
  3821. * resize the view according to the canvas' size.
  3822. * @example
  3823. * window.addEventListener("resize", function () {
  3824. * engine.resize();
  3825. * });
  3826. */
  3827. Engine.prototype.resize = function () {
  3828. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3829. };
  3830. /**
  3831. * force a specific size of the canvas
  3832. * @param {number} width - the new canvas' width
  3833. * @param {number} height - the new canvas' height
  3834. */
  3835. Engine.prototype.setSize = function (width, height) {
  3836. this._renderingCanvas.width = width;
  3837. this._renderingCanvas.height = height;
  3838. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3839. };
  3840. Engine.prototype.bindFramebuffer = function (texture) {
  3841. this._currentRenderTarget = texture;
  3842. var gl = this._gl;
  3843. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3844. this._gl.viewport(0, 0, texture._width, texture._height);
  3845. this.wipeCaches();
  3846. };
  3847. Engine.prototype.unBindFramebuffer = function (texture) {
  3848. this._currentRenderTarget = null;
  3849. if (texture.generateMipMaps) {
  3850. var gl = this._gl;
  3851. gl.bindTexture(gl.TEXTURE_2D, texture);
  3852. gl.generateMipmap(gl.TEXTURE_2D);
  3853. gl.bindTexture(gl.TEXTURE_2D, null);
  3854. }
  3855. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3856. };
  3857. Engine.prototype.flushFramebuffer = function () {
  3858. // this._gl.flush();
  3859. };
  3860. Engine.prototype.restoreDefaultFramebuffer = function () {
  3861. this._currentRenderTarget = null;
  3862. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3863. this.setViewport(this._cachedViewport);
  3864. this.wipeCaches();
  3865. };
  3866. // VBOs
  3867. Engine.prototype._resetVertexBufferBinding = function () {
  3868. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3869. this._cachedVertexBuffers = null;
  3870. };
  3871. Engine.prototype.createVertexBuffer = function (vertices) {
  3872. var vbo = this._gl.createBuffer();
  3873. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3874. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3875. this._resetVertexBufferBinding();
  3876. vbo.references = 1;
  3877. return vbo;
  3878. };
  3879. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3880. var vbo = this._gl.createBuffer();
  3881. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3882. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3883. this._resetVertexBufferBinding();
  3884. vbo.references = 1;
  3885. return vbo;
  3886. };
  3887. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3888. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3889. if (offset === undefined) {
  3890. offset = 0;
  3891. }
  3892. if (vertices instanceof Float32Array) {
  3893. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3894. }
  3895. else {
  3896. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3897. }
  3898. this._resetVertexBufferBinding();
  3899. };
  3900. Engine.prototype._resetIndexBufferBinding = function () {
  3901. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3902. this._cachedIndexBuffer = null;
  3903. };
  3904. Engine.prototype.createIndexBuffer = function (indices) {
  3905. var vbo = this._gl.createBuffer();
  3906. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3907. // Check for 32 bits indices
  3908. var arrayBuffer;
  3909. var need32Bits = false;
  3910. if (this._caps.uintIndices) {
  3911. for (var index = 0; index < indices.length; index++) {
  3912. if (indices[index] > 65535) {
  3913. need32Bits = true;
  3914. break;
  3915. }
  3916. }
  3917. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3918. }
  3919. else {
  3920. arrayBuffer = new Uint16Array(indices);
  3921. }
  3922. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3923. this._resetIndexBufferBinding();
  3924. vbo.references = 1;
  3925. vbo.is32Bits = need32Bits;
  3926. return vbo;
  3927. };
  3928. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3929. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3930. this._cachedVertexBuffers = vertexBuffer;
  3931. this._cachedEffectForVertexBuffers = effect;
  3932. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3933. var offset = 0;
  3934. for (var index = 0; index < vertexDeclaration.length; index++) {
  3935. var order = effect.getAttributeLocation(index);
  3936. if (order >= 0) {
  3937. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3938. }
  3939. offset += vertexDeclaration[index] * 4;
  3940. }
  3941. }
  3942. if (this._cachedIndexBuffer !== indexBuffer) {
  3943. this._cachedIndexBuffer = indexBuffer;
  3944. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3945. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3946. }
  3947. };
  3948. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3949. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3950. this._cachedVertexBuffers = vertexBuffers;
  3951. this._cachedEffectForVertexBuffers = effect;
  3952. var attributes = effect.getAttributesNames();
  3953. for (var index = 0; index < attributes.length; index++) {
  3954. var order = effect.getAttributeLocation(index);
  3955. if (order >= 0) {
  3956. var vertexBuffer = vertexBuffers[attributes[index]];
  3957. if (!vertexBuffer) {
  3958. continue;
  3959. }
  3960. var stride = vertexBuffer.getStrideSize();
  3961. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3962. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3963. }
  3964. }
  3965. }
  3966. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3967. this._cachedIndexBuffer = indexBuffer;
  3968. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3969. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3970. }
  3971. };
  3972. Engine.prototype._releaseBuffer = function (buffer) {
  3973. buffer.references--;
  3974. if (buffer.references === 0) {
  3975. this._gl.deleteBuffer(buffer);
  3976. return true;
  3977. }
  3978. return false;
  3979. };
  3980. Engine.prototype.createInstancesBuffer = function (capacity) {
  3981. var buffer = this._gl.createBuffer();
  3982. buffer.capacity = capacity;
  3983. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3984. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3985. return buffer;
  3986. };
  3987. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3988. this._gl.deleteBuffer(buffer);
  3989. };
  3990. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3991. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3992. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3993. for (var index = 0; index < 4; index++) {
  3994. var offsetLocation = offsetLocations[index];
  3995. this._gl.enableVertexAttribArray(offsetLocation);
  3996. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3997. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3998. }
  3999. };
  4000. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4001. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4002. for (var index = 0; index < 4; index++) {
  4003. var offsetLocation = offsetLocations[index];
  4004. this._gl.disableVertexAttribArray(offsetLocation);
  4005. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4006. }
  4007. };
  4008. Engine.prototype.applyStates = function () {
  4009. this._depthCullingState.apply(this._gl);
  4010. this._alphaState.apply(this._gl);
  4011. };
  4012. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4013. // Apply states
  4014. this.applyStates();
  4015. this._drawCalls++;
  4016. // Render
  4017. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4018. if (instancesCount) {
  4019. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4020. return;
  4021. }
  4022. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4023. };
  4024. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4025. // Apply states
  4026. this.applyStates();
  4027. this._drawCalls++;
  4028. if (instancesCount) {
  4029. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4030. return;
  4031. }
  4032. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4033. };
  4034. // Shaders
  4035. Engine.prototype._releaseEffect = function (effect) {
  4036. if (this._compiledEffects[effect._key]) {
  4037. delete this._compiledEffects[effect._key];
  4038. if (effect.getProgram()) {
  4039. this._gl.deleteProgram(effect.getProgram());
  4040. }
  4041. }
  4042. };
  4043. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4044. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4045. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4046. var name = vertex + "+" + fragment + "@" + defines;
  4047. if (this._compiledEffects[name]) {
  4048. return this._compiledEffects[name];
  4049. }
  4050. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4051. effect._key = name;
  4052. this._compiledEffects[name] = effect;
  4053. return effect;
  4054. };
  4055. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4056. if (uniformsNames === void 0) { uniformsNames = []; }
  4057. if (samplers === void 0) { samplers = []; }
  4058. if (defines === void 0) { defines = ""; }
  4059. return this.createEffect({
  4060. vertex: "particles",
  4061. fragmentElement: fragmentName
  4062. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4063. };
  4064. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4065. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4066. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4067. var shaderProgram = this._gl.createProgram();
  4068. this._gl.attachShader(shaderProgram, vertexShader);
  4069. this._gl.attachShader(shaderProgram, fragmentShader);
  4070. this._gl.linkProgram(shaderProgram);
  4071. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4072. if (!linked) {
  4073. var error = this._gl.getProgramInfoLog(shaderProgram);
  4074. if (error) {
  4075. throw new Error(error);
  4076. }
  4077. }
  4078. this._gl.deleteShader(vertexShader);
  4079. this._gl.deleteShader(fragmentShader);
  4080. return shaderProgram;
  4081. };
  4082. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4083. var results = [];
  4084. for (var index = 0; index < uniformsNames.length; index++) {
  4085. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4086. }
  4087. return results;
  4088. };
  4089. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4090. var results = [];
  4091. for (var index = 0; index < attributesNames.length; index++) {
  4092. try {
  4093. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4094. }
  4095. catch (e) {
  4096. results.push(-1);
  4097. }
  4098. }
  4099. return results;
  4100. };
  4101. Engine.prototype.enableEffect = function (effect) {
  4102. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4103. if (effect && effect.onBind) {
  4104. effect.onBind(effect);
  4105. }
  4106. return;
  4107. }
  4108. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4109. // Use program
  4110. this._gl.useProgram(effect.getProgram());
  4111. for (var i in this._vertexAttribArrays) {
  4112. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4113. continue;
  4114. }
  4115. this._vertexAttribArrays[i] = false;
  4116. this._gl.disableVertexAttribArray(i);
  4117. }
  4118. var attributesCount = effect.getAttributesCount();
  4119. for (var index = 0; index < attributesCount; index++) {
  4120. // Attributes
  4121. var order = effect.getAttributeLocation(index);
  4122. if (order >= 0) {
  4123. this._vertexAttribArrays[order] = true;
  4124. this._gl.enableVertexAttribArray(order);
  4125. }
  4126. }
  4127. this._currentEffect = effect;
  4128. if (effect.onBind) {
  4129. effect.onBind(effect);
  4130. }
  4131. };
  4132. Engine.prototype.setArray = function (uniform, array) {
  4133. if (!uniform)
  4134. return;
  4135. this._gl.uniform1fv(uniform, array);
  4136. };
  4137. Engine.prototype.setMatrices = function (uniform, matrices) {
  4138. if (!uniform)
  4139. return;
  4140. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4141. };
  4142. Engine.prototype.setMatrix = function (uniform, matrix) {
  4143. if (!uniform)
  4144. return;
  4145. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4146. };
  4147. Engine.prototype.setFloat = function (uniform, value) {
  4148. if (!uniform)
  4149. return;
  4150. this._gl.uniform1f(uniform, value);
  4151. };
  4152. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4153. if (!uniform)
  4154. return;
  4155. this._gl.uniform2f(uniform, x, y);
  4156. };
  4157. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4158. if (!uniform)
  4159. return;
  4160. this._gl.uniform3f(uniform, x, y, z);
  4161. };
  4162. Engine.prototype.setBool = function (uniform, bool) {
  4163. if (!uniform)
  4164. return;
  4165. this._gl.uniform1i(uniform, bool);
  4166. };
  4167. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4168. if (!uniform)
  4169. return;
  4170. this._gl.uniform4f(uniform, x, y, z, w);
  4171. };
  4172. Engine.prototype.setColor3 = function (uniform, color3) {
  4173. if (!uniform)
  4174. return;
  4175. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4176. };
  4177. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4178. if (!uniform)
  4179. return;
  4180. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4181. };
  4182. // States
  4183. Engine.prototype.setState = function (culling, force) {
  4184. // Culling
  4185. if (this._depthCullingState.cull !== culling || force) {
  4186. if (culling) {
  4187. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4188. this._depthCullingState.cull = true;
  4189. }
  4190. else {
  4191. this._depthCullingState.cull = false;
  4192. }
  4193. }
  4194. };
  4195. Engine.prototype.setDepthBuffer = function (enable) {
  4196. this._depthCullingState.depthTest = enable;
  4197. };
  4198. Engine.prototype.getDepthWrite = function () {
  4199. return this._depthCullingState.depthMask;
  4200. };
  4201. Engine.prototype.setDepthWrite = function (enable) {
  4202. this._depthCullingState.depthMask = enable;
  4203. };
  4204. Engine.prototype.setColorWrite = function (enable) {
  4205. this._gl.colorMask(enable, enable, enable, enable);
  4206. };
  4207. Engine.prototype.setAlphaMode = function (mode) {
  4208. switch (mode) {
  4209. case Engine.ALPHA_DISABLE:
  4210. this.setDepthWrite(true);
  4211. this._alphaState.alphaBlend = false;
  4212. break;
  4213. case Engine.ALPHA_COMBINE:
  4214. this.setDepthWrite(false);
  4215. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4216. this._alphaState.alphaBlend = true;
  4217. break;
  4218. case Engine.ALPHA_ADD:
  4219. this.setDepthWrite(false);
  4220. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4221. this._alphaState.alphaBlend = true;
  4222. break;
  4223. }
  4224. this._alphaMode = mode;
  4225. };
  4226. Engine.prototype.getAlphaMode = function () {
  4227. return this._alphaMode;
  4228. };
  4229. Engine.prototype.setAlphaTesting = function (enable) {
  4230. this._alphaTest = enable;
  4231. };
  4232. Engine.prototype.getAlphaTesting = function () {
  4233. return this._alphaTest;
  4234. };
  4235. // Textures
  4236. Engine.prototype.wipeCaches = function () {
  4237. this._activeTexturesCache = [];
  4238. this._currentEffect = null;
  4239. this._depthCullingState.reset();
  4240. this._alphaState.reset();
  4241. this._cachedVertexBuffers = null;
  4242. this._cachedIndexBuffer = null;
  4243. this._cachedEffectForVertexBuffers = null;
  4244. };
  4245. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4246. var gl = this._gl;
  4247. gl.bindTexture(gl.TEXTURE_2D, texture);
  4248. var magFilter = gl.NEAREST;
  4249. var minFilter = gl.NEAREST;
  4250. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4251. magFilter = gl.LINEAR;
  4252. minFilter = gl.LINEAR;
  4253. }
  4254. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4255. magFilter = gl.LINEAR;
  4256. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4257. }
  4258. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4259. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4260. gl.bindTexture(gl.TEXTURE_2D, null);
  4261. texture.samplingMode = samplingMode;
  4262. };
  4263. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4264. var _this = this;
  4265. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4266. if (onLoad === void 0) { onLoad = null; }
  4267. if (onError === void 0) { onError = null; }
  4268. if (buffer === void 0) { buffer = null; }
  4269. var texture = this._gl.createTexture();
  4270. var extension;
  4271. var fromData = false;
  4272. if (url.substr(0, 5) === "data:") {
  4273. fromData = true;
  4274. }
  4275. if (!fromData)
  4276. extension = url.substr(url.length - 4, 4).toLowerCase();
  4277. else {
  4278. var oldUrl = url;
  4279. fromData = oldUrl.split(':');
  4280. url = oldUrl;
  4281. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4282. }
  4283. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4284. var isTGA = (extension === ".tga");
  4285. scene._addPendingData(texture);
  4286. texture.url = url;
  4287. texture.noMipmap = noMipmap;
  4288. texture.references = 1;
  4289. this._loadedTexturesCache.push(texture);
  4290. var onerror = function () {
  4291. scene._removePendingData(texture);
  4292. if (onError) {
  4293. onError();
  4294. }
  4295. };
  4296. if (isTGA) {
  4297. var callback = function (arrayBuffer) {
  4298. var data = new Uint8Array(arrayBuffer);
  4299. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4300. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4301. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4302. if (onLoad) {
  4303. onLoad();
  4304. }
  4305. }, samplingMode);
  4306. };
  4307. if (!(fromData instanceof Array))
  4308. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4309. callback(arrayBuffer);
  4310. }, onerror, scene.database, true);
  4311. else
  4312. callback(buffer);
  4313. }
  4314. else if (isDDS) {
  4315. callback = function (data) {
  4316. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4317. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4318. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4319. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4320. if (onLoad) {
  4321. onLoad();
  4322. }
  4323. }, samplingMode);
  4324. };
  4325. if (!(fromData instanceof Array))
  4326. BABYLON.Tools.LoadFile(url, function (data) {
  4327. callback(data);
  4328. }, onerror, scene.database, true);
  4329. else
  4330. callback(buffer);
  4331. }
  4332. else {
  4333. var onload = function (img) {
  4334. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4335. var isPot = (img.width === potWidth && img.height === potHeight);
  4336. if (!isPot) {
  4337. _this._workingCanvas.width = potWidth;
  4338. _this._workingCanvas.height = potHeight;
  4339. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4340. _this._workingContext.imageSmoothingEnabled = false;
  4341. _this._workingContext.mozImageSmoothingEnabled = false;
  4342. _this._workingContext.oImageSmoothingEnabled = false;
  4343. _this._workingContext.webkitImageSmoothingEnabled = false;
  4344. _this._workingContext.msImageSmoothingEnabled = false;
  4345. }
  4346. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4347. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4348. _this._workingContext.imageSmoothingEnabled = true;
  4349. _this._workingContext.mozImageSmoothingEnabled = true;
  4350. _this._workingContext.oImageSmoothingEnabled = true;
  4351. _this._workingContext.webkitImageSmoothingEnabled = true;
  4352. _this._workingContext.msImageSmoothingEnabled = true;
  4353. }
  4354. }
  4355. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4356. if (onLoad) {
  4357. onLoad();
  4358. }
  4359. }, samplingMode);
  4360. };
  4361. if (!(fromData instanceof Array))
  4362. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4363. else
  4364. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4365. }
  4366. return texture;
  4367. };
  4368. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4369. var texture = this._gl.createTexture();
  4370. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4371. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4372. // Format
  4373. var internalFormat = this._gl.RGBA;
  4374. switch (format) {
  4375. case Engine.TEXTUREFORMAT_ALPHA:
  4376. internalFormat = this._gl.ALPHA;
  4377. break;
  4378. case Engine.TEXTUREFORMAT_LUMINANCE:
  4379. internalFormat = this._gl.LUMINANCE;
  4380. break;
  4381. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4382. internalFormat = this._gl.LUMINANCE_ALPHA;
  4383. break;
  4384. case Engine.TEXTUREFORMAT_RGB:
  4385. internalFormat = this._gl.RGB;
  4386. break;
  4387. case Engine.TEXTUREFORMAT_RGBA:
  4388. internalFormat = this._gl.RGBA;
  4389. break;
  4390. }
  4391. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4392. if (generateMipMaps) {
  4393. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4394. }
  4395. // Filters
  4396. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4397. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4398. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4399. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4400. this._activeTexturesCache = [];
  4401. texture._baseWidth = width;
  4402. texture._baseHeight = height;
  4403. texture._width = width;
  4404. texture._height = height;
  4405. texture.isReady = true;
  4406. texture.references = 1;
  4407. texture.samplingMode = samplingMode;
  4408. this._loadedTexturesCache.push(texture);
  4409. return texture;
  4410. };
  4411. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4412. var texture = this._gl.createTexture();
  4413. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4414. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4415. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4416. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4417. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4418. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4419. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4420. this._activeTexturesCache = [];
  4421. texture._baseWidth = width;
  4422. texture._baseHeight = height;
  4423. texture._width = width;
  4424. texture._height = height;
  4425. texture.isReady = false;
  4426. texture.generateMipMaps = generateMipMaps;
  4427. texture.references = 1;
  4428. texture.samplingMode = samplingMode;
  4429. this._loadedTexturesCache.push(texture);
  4430. return texture;
  4431. };
  4432. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4433. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4434. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4435. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4436. if (texture.generateMipMaps) {
  4437. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4438. }
  4439. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4440. this._activeTexturesCache = [];
  4441. texture.isReady = true;
  4442. };
  4443. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4444. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4445. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4446. // Scale the video if it is a NPOT using the current working canvas
  4447. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4448. if (!texture._workingCanvas) {
  4449. texture._workingCanvas = document.createElement("canvas");
  4450. texture._workingContext = texture._workingCanvas.getContext("2d");
  4451. texture._workingCanvas.width = texture._width;
  4452. texture._workingCanvas.height = texture._height;
  4453. }
  4454. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4455. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4456. }
  4457. else {
  4458. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4459. }
  4460. if (texture.generateMipMaps) {
  4461. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4462. }
  4463. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4464. this._activeTexturesCache = [];
  4465. texture.isReady = true;
  4466. };
  4467. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4468. // old version had a "generateMipMaps" arg instead of options.
  4469. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4470. // in the same way, generateDepthBuffer is defaulted to true
  4471. var generateMipMaps = false;
  4472. var generateDepthBuffer = true;
  4473. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4474. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4475. if (options !== undefined) {
  4476. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4477. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4478. type = options.type === undefined ? type : options.type;
  4479. if (options.samplingMode !== undefined) {
  4480. samplingMode = options.samplingMode;
  4481. }
  4482. if (type === Engine.TEXTURETYPE_FLOAT) {
  4483. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4484. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4485. }
  4486. }
  4487. var gl = this._gl;
  4488. var texture = gl.createTexture();
  4489. gl.bindTexture(gl.TEXTURE_2D, texture);
  4490. var width = size.width || size;
  4491. var height = size.height || size;
  4492. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4493. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4494. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4495. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4496. }
  4497. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4498. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4499. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4500. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4501. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4502. var depthBuffer;
  4503. // Create the depth buffer
  4504. if (generateDepthBuffer) {
  4505. depthBuffer = gl.createRenderbuffer();
  4506. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4507. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4508. }
  4509. // Create the framebuffer
  4510. var framebuffer = gl.createFramebuffer();
  4511. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4512. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4513. if (generateDepthBuffer) {
  4514. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4515. }
  4516. // Unbind
  4517. gl.bindTexture(gl.TEXTURE_2D, null);
  4518. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4519. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4520. texture._framebuffer = framebuffer;
  4521. if (generateDepthBuffer) {
  4522. texture._depthBuffer = depthBuffer;
  4523. }
  4524. texture._width = width;
  4525. texture._height = height;
  4526. texture.isReady = true;
  4527. texture.generateMipMaps = generateMipMaps;
  4528. texture.references = 1;
  4529. texture.samplingMode = samplingMode;
  4530. this._activeTexturesCache = [];
  4531. this._loadedTexturesCache.push(texture);
  4532. return texture;
  4533. };
  4534. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4535. var _this = this;
  4536. var gl = this._gl;
  4537. var texture = gl.createTexture();
  4538. texture.isCube = true;
  4539. texture.url = rootUrl;
  4540. texture.references = 1;
  4541. this._loadedTexturesCache.push(texture);
  4542. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4543. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4544. if (isDDS) {
  4545. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4546. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4547. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4548. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4549. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4550. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4551. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4552. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4553. }
  4554. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4555. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4556. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4557. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4558. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4559. _this._activeTexturesCache = [];
  4560. texture._width = info.width;
  4561. texture._height = info.height;
  4562. texture.isReady = true;
  4563. }, null, null, true);
  4564. }
  4565. else {
  4566. cascadeLoad(rootUrl, scene, function (imgs) {
  4567. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4568. var height = width;
  4569. _this._workingCanvas.width = width;
  4570. _this._workingCanvas.height = height;
  4571. var faces = [
  4572. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4573. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4574. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4575. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4576. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4577. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4578. ];
  4579. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4580. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4581. for (var index = 0; index < faces.length; index++) {
  4582. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4583. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4584. }
  4585. if (!noMipmap) {
  4586. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4587. }
  4588. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4589. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4590. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4591. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4592. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4593. _this._activeTexturesCache = [];
  4594. texture._width = width;
  4595. texture._height = height;
  4596. texture.isReady = true;
  4597. }, extensions);
  4598. }
  4599. return texture;
  4600. };
  4601. Engine.prototype._releaseTexture = function (texture) {
  4602. var gl = this._gl;
  4603. if (texture._framebuffer) {
  4604. gl.deleteFramebuffer(texture._framebuffer);
  4605. }
  4606. if (texture._depthBuffer) {
  4607. gl.deleteRenderbuffer(texture._depthBuffer);
  4608. }
  4609. gl.deleteTexture(texture);
  4610. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4611. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4612. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4613. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4614. this._activeTexturesCache[channel] = null;
  4615. }
  4616. var index = this._loadedTexturesCache.indexOf(texture);
  4617. if (index !== -1) {
  4618. this._loadedTexturesCache.splice(index, 1);
  4619. }
  4620. };
  4621. Engine.prototype.bindSamplers = function (effect) {
  4622. this._gl.useProgram(effect.getProgram());
  4623. var samplers = effect.getSamplers();
  4624. for (var index = 0; index < samplers.length; index++) {
  4625. var uniform = effect.getUniform(samplers[index]);
  4626. this._gl.uniform1i(uniform, index);
  4627. }
  4628. this._currentEffect = null;
  4629. };
  4630. Engine.prototype._bindTexture = function (channel, texture) {
  4631. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4632. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4633. this._activeTexturesCache[channel] = null;
  4634. };
  4635. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4636. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4637. };
  4638. Engine.prototype.setTexture = function (channel, texture) {
  4639. if (channel < 0) {
  4640. return;
  4641. }
  4642. // Not ready?
  4643. if (!texture || !texture.isReady()) {
  4644. if (this._activeTexturesCache[channel] != null) {
  4645. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4646. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4647. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4648. this._activeTexturesCache[channel] = null;
  4649. }
  4650. return;
  4651. }
  4652. // Video
  4653. if (texture instanceof BABYLON.VideoTexture) {
  4654. if (texture.update()) {
  4655. this._activeTexturesCache[channel] = null;
  4656. }
  4657. }
  4658. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4659. texture.delayLoad();
  4660. return;
  4661. }
  4662. if (this._activeTexturesCache[channel] === texture) {
  4663. return;
  4664. }
  4665. this._activeTexturesCache[channel] = texture;
  4666. var internalTexture = texture.getInternalTexture();
  4667. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4668. if (internalTexture.isCube) {
  4669. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4670. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4671. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4672. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4673. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4674. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4675. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4676. }
  4677. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4678. }
  4679. else {
  4680. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4681. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4682. internalTexture._cachedWrapU = texture.wrapU;
  4683. switch (texture.wrapU) {
  4684. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4685. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4686. break;
  4687. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4688. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4689. break;
  4690. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4691. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4692. break;
  4693. }
  4694. }
  4695. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4696. internalTexture._cachedWrapV = texture.wrapV;
  4697. switch (texture.wrapV) {
  4698. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4699. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4700. break;
  4701. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4702. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4703. break;
  4704. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4705. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4706. break;
  4707. }
  4708. }
  4709. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4710. }
  4711. };
  4712. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4713. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4714. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4715. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4716. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4717. }
  4718. };
  4719. Engine.prototype.readPixels = function (x, y, width, height) {
  4720. var data = new Uint8Array(height * width * 4);
  4721. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4722. return data;
  4723. };
  4724. // Dispose
  4725. Engine.prototype.dispose = function () {
  4726. this.hideLoadingUI();
  4727. this.stopRenderLoop();
  4728. while (this.scenes.length) {
  4729. this.scenes[0].dispose();
  4730. }
  4731. // Release audio engine
  4732. Engine.audioEngine.dispose();
  4733. for (var name in this._compiledEffects) {
  4734. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4735. }
  4736. for (var i in this._vertexAttribArrays) {
  4737. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4738. continue;
  4739. }
  4740. this._gl.disableVertexAttribArray(i);
  4741. }
  4742. // Events
  4743. window.removeEventListener("blur", this._onBlur);
  4744. window.removeEventListener("focus", this._onFocus);
  4745. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4746. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4747. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4748. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4749. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4750. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4751. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4752. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4753. };
  4754. // Loading screen
  4755. Engine.prototype.displayLoadingUI = function () {
  4756. var _this = this;
  4757. this._loadingDiv = document.createElement("div");
  4758. this._loadingDiv.style.opacity = "0";
  4759. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4760. // Loading text
  4761. this._loadingTextDiv = document.createElement("div");
  4762. this._loadingTextDiv.style.position = "absolute";
  4763. this._loadingTextDiv.style.left = "0";
  4764. this._loadingTextDiv.style.top = "50%";
  4765. this._loadingTextDiv.style.marginTop = "80px";
  4766. this._loadingTextDiv.style.width = "100%";
  4767. this._loadingTextDiv.style.height = "20px";
  4768. this._loadingTextDiv.style.fontFamily = "Arial";
  4769. this._loadingTextDiv.style.fontSize = "14px";
  4770. this._loadingTextDiv.style.color = "white";
  4771. this._loadingTextDiv.style.textAlign = "center";
  4772. this._loadingTextDiv.innerHTML = "Loading";
  4773. this._loadingDiv.appendChild(this._loadingTextDiv);
  4774. // Loading img
  4775. var imgBack = new Image();
  4776. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==";
  4777. imgBack.style.position = "absolute";
  4778. imgBack.style.left = "50%";
  4779. imgBack.style.top = "50%";
  4780. imgBack.style.marginLeft = "-50px";
  4781. imgBack.style.marginTop = "-50px";
  4782. imgBack.style.transition = "transform 1.0s ease";
  4783. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4784. var deg = 360;
  4785. var onTransitionEnd = function () {
  4786. deg += 360;
  4787. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4788. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4789. };
  4790. imgBack.addEventListener("transitionend", onTransitionEnd);
  4791. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4792. this._loadingDiv.appendChild(imgBack);
  4793. // front image
  4794. var imgFront = new Image();
  4795. imgFront.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=";
  4796. imgFront.style.position = "absolute";
  4797. imgFront.style.left = "50%";
  4798. imgFront.style.top = "50%";
  4799. imgFront.style.marginLeft = "-50px";
  4800. imgFront.style.marginTop = "-50px";
  4801. this._loadingDiv.appendChild(imgFront);
  4802. // Resize
  4803. this._resizeLoadingUI = function () {
  4804. var canvasRect = _this.getRenderingCanvasClientRect();
  4805. _this._loadingDiv.style.position = "absolute";
  4806. _this._loadingDiv.style.left = canvasRect.left + "px";
  4807. _this._loadingDiv.style.top = canvasRect.top + "px";
  4808. _this._loadingDiv.style.width = canvasRect.width + "px";
  4809. _this._loadingDiv.style.height = canvasRect.height + "px";
  4810. };
  4811. this._resizeLoadingUI();
  4812. window.addEventListener("resize", this._resizeLoadingUI);
  4813. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4814. document.body.appendChild(this._loadingDiv);
  4815. setTimeout(function () {
  4816. _this._loadingDiv.style.opacity = "1";
  4817. imgBack.style.transform = "rotateZ(360deg)";
  4818. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4819. }, 0);
  4820. };
  4821. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4822. set: function (text) {
  4823. if (!this._loadingDiv) {
  4824. return;
  4825. }
  4826. this._loadingTextDiv.innerHTML = text;
  4827. },
  4828. enumerable: true,
  4829. configurable: true
  4830. });
  4831. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4832. get: function () {
  4833. return this._loadingDivBackgroundColor;
  4834. },
  4835. set: function (color) {
  4836. this._loadingDivBackgroundColor = color;
  4837. if (!this._loadingDiv) {
  4838. return;
  4839. }
  4840. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4841. },
  4842. enumerable: true,
  4843. configurable: true
  4844. });
  4845. Engine.prototype.hideLoadingUI = function () {
  4846. var _this = this;
  4847. if (!this._loadingDiv) {
  4848. return;
  4849. }
  4850. var onTransitionEnd = function () {
  4851. if (!_this._loadingDiv) {
  4852. return;
  4853. }
  4854. document.body.removeChild(_this._loadingDiv);
  4855. window.removeEventListener("resize", _this._resizeLoadingUI);
  4856. _this._loadingDiv = null;
  4857. };
  4858. this._loadingDiv.style.opacity = "0";
  4859. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4860. };
  4861. // FPS
  4862. Engine.prototype.getFps = function () {
  4863. return this.fps;
  4864. };
  4865. Engine.prototype.getDeltaTime = function () {
  4866. return this.deltaTime;
  4867. };
  4868. Engine.prototype._measureFps = function () {
  4869. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4870. var length = this.previousFramesDuration.length;
  4871. if (length >= 2) {
  4872. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4873. }
  4874. if (length >= this.fpsRange) {
  4875. if (length > this.fpsRange) {
  4876. this.previousFramesDuration.splice(0, 1);
  4877. length = this.previousFramesDuration.length;
  4878. }
  4879. var sum = 0;
  4880. for (var id = 0; id < length - 1; id++) {
  4881. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4882. }
  4883. this.fps = 1000.0 / (sum / (length - 1));
  4884. }
  4885. };
  4886. // Statics
  4887. Engine.isSupported = function () {
  4888. try {
  4889. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4890. if (navigator.isCocoonJS) {
  4891. return true;
  4892. }
  4893. var tempcanvas = document.createElement("canvas");
  4894. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4895. return gl != null && !!window.WebGLRenderingContext;
  4896. }
  4897. catch (e) {
  4898. return false;
  4899. }
  4900. };
  4901. // Const statics
  4902. Engine._ALPHA_DISABLE = 0;
  4903. Engine._ALPHA_ADD = 1;
  4904. Engine._ALPHA_COMBINE = 2;
  4905. Engine._DELAYLOADSTATE_NONE = 0;
  4906. Engine._DELAYLOADSTATE_LOADED = 1;
  4907. Engine._DELAYLOADSTATE_LOADING = 2;
  4908. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4909. Engine._TEXTUREFORMAT_ALPHA = 0;
  4910. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  4911. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  4912. Engine._TEXTUREFORMAT_RGB = 4;
  4913. Engine._TEXTUREFORMAT_RGBA = 4;
  4914. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  4915. Engine._TEXTURETYPE_FLOAT = 1;
  4916. // Updatable statics so stick with vars here
  4917. Engine.Epsilon = 0.001;
  4918. Engine.CollisionsEpsilon = 0.001;
  4919. Engine.ShadersRepository = "Babylon/Shaders/";
  4920. return Engine;
  4921. })();
  4922. BABYLON.Engine = Engine;
  4923. })(BABYLON || (BABYLON = {}));
  4924. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  4925. (function (BABYLON) {
  4926. /**
  4927. * Node is the basic class for all scene objects (Mesh, Light Camera).
  4928. */
  4929. var Node = (function () {
  4930. /**
  4931. * @constructor
  4932. * @param {string} name - the name and id to be given to this node
  4933. * @param {BABYLON.Scene} the scene this node will be added to
  4934. */
  4935. function Node(name, scene) {
  4936. this.state = "";
  4937. this.animations = new Array();
  4938. this._childrenFlag = -1;
  4939. this._isEnabled = true;
  4940. this._isReady = true;
  4941. this._currentRenderId = -1;
  4942. this.name = name;
  4943. this.id = name;
  4944. this._scene = scene;
  4945. this._initCache();
  4946. }
  4947. Node.prototype.getScene = function () {
  4948. return this._scene;
  4949. };
  4950. Node.prototype.getEngine = function () {
  4951. return this._scene.getEngine();
  4952. };
  4953. // override it in derived class
  4954. Node.prototype.getWorldMatrix = function () {
  4955. return BABYLON.Matrix.Identity();
  4956. };
  4957. // override it in derived class if you add new variables to the cache
  4958. // and call the parent class method
  4959. Node.prototype._initCache = function () {
  4960. this._cache = {};
  4961. this._cache.parent = undefined;
  4962. };
  4963. Node.prototype.updateCache = function (force) {
  4964. if (!force && this.isSynchronized())
  4965. return;
  4966. this._cache.parent = this.parent;
  4967. this._updateCache();
  4968. };
  4969. // override it in derived class if you add new variables to the cache
  4970. // and call the parent class method if !ignoreParentClass
  4971. Node.prototype._updateCache = function (ignoreParentClass) {
  4972. };
  4973. // override it in derived class if you add new variables to the cache
  4974. Node.prototype._isSynchronized = function () {
  4975. return true;
  4976. };
  4977. Node.prototype.isSynchronizedWithParent = function () {
  4978. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4979. };
  4980. Node.prototype.isSynchronized = function (updateCache) {
  4981. var check = this.hasNewParent();
  4982. check = check || !this.isSynchronizedWithParent();
  4983. check = check || !this._isSynchronized();
  4984. if (updateCache)
  4985. this.updateCache(true);
  4986. return !check;
  4987. };
  4988. Node.prototype.hasNewParent = function (update) {
  4989. if (this._cache.parent === this.parent)
  4990. return false;
  4991. if (update)
  4992. this._cache.parent = this.parent;
  4993. return true;
  4994. };
  4995. /**
  4996. * Is this node ready to be used/rendered
  4997. * @return {boolean} is it ready
  4998. */
  4999. Node.prototype.isReady = function () {
  5000. return this._isReady;
  5001. };
  5002. /**
  5003. * Is this node enabled.
  5004. * If the node has a parent and is enabled, the parent will be inspected as well.
  5005. * @return {boolean} whether this node (and its parent) is enabled.
  5006. * @see setEnabled
  5007. */
  5008. Node.prototype.isEnabled = function () {
  5009. if (!this._isEnabled) {
  5010. return false;
  5011. }
  5012. if (this.parent) {
  5013. return this.parent.isEnabled();
  5014. }
  5015. return true;
  5016. };
  5017. /**
  5018. * Set the enabled state of this node.
  5019. * @param {boolean} value - the new enabled state
  5020. * @see isEnabled
  5021. */
  5022. Node.prototype.setEnabled = function (value) {
  5023. this._isEnabled = value;
  5024. };
  5025. /**
  5026. * Is this node a descendant of the given node.
  5027. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5028. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5029. * @see parent
  5030. */
  5031. Node.prototype.isDescendantOf = function (ancestor) {
  5032. if (this.parent) {
  5033. if (this.parent === ancestor) {
  5034. return true;
  5035. }
  5036. return this.parent.isDescendantOf(ancestor);
  5037. }
  5038. return false;
  5039. };
  5040. Node.prototype._getDescendants = function (list, results) {
  5041. for (var index = 0; index < list.length; index++) {
  5042. var item = list[index];
  5043. if (item.isDescendantOf(this)) {
  5044. results.push(item);
  5045. }
  5046. }
  5047. };
  5048. /**
  5049. * Will return all nodes that have this node as parent.
  5050. * @return {BABYLON.Node[]} all children nodes of all types.
  5051. */
  5052. Node.prototype.getDescendants = function () {
  5053. var results = [];
  5054. this._getDescendants(this._scene.meshes, results);
  5055. this._getDescendants(this._scene.lights, results);
  5056. this._getDescendants(this._scene.cameras, results);
  5057. return results;
  5058. };
  5059. Node.prototype._setReady = function (state) {
  5060. if (state == this._isReady) {
  5061. return;
  5062. }
  5063. if (!state) {
  5064. this._isReady = false;
  5065. return;
  5066. }
  5067. this._isReady = true;
  5068. if (this.onReady) {
  5069. this.onReady(this);
  5070. }
  5071. };
  5072. return Node;
  5073. })();
  5074. BABYLON.Node = Node;
  5075. })(BABYLON || (BABYLON = {}));
  5076. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5077. (function (BABYLON) {
  5078. var BoundingSphere = (function () {
  5079. function BoundingSphere(minimum, maximum) {
  5080. this.minimum = minimum;
  5081. this.maximum = maximum;
  5082. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5083. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5084. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5085. this.radius = distance * 0.5;
  5086. this.centerWorld = BABYLON.Vector3.Zero();
  5087. this._update(BABYLON.Matrix.Identity());
  5088. }
  5089. // Methods
  5090. BoundingSphere.prototype._update = function (world) {
  5091. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5092. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5093. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5094. };
  5095. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5096. for (var i = 0; i < 6; i++) {
  5097. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5098. return false;
  5099. }
  5100. return true;
  5101. };
  5102. BoundingSphere.prototype.intersectsPoint = function (point) {
  5103. var x = this.centerWorld.x - point.x;
  5104. var y = this.centerWorld.y - point.y;
  5105. var z = this.centerWorld.z - point.z;
  5106. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5107. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5108. return false;
  5109. return true;
  5110. };
  5111. // Statics
  5112. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5113. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5114. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5115. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5116. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5117. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5118. return false;
  5119. return true;
  5120. };
  5121. return BoundingSphere;
  5122. })();
  5123. BABYLON.BoundingSphere = BoundingSphere;
  5124. })(BABYLON || (BABYLON = {}));
  5125. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5126. (function (BABYLON) {
  5127. var BoundingBox = (function () {
  5128. function BoundingBox(minimum, maximum) {
  5129. this.minimum = minimum;
  5130. this.maximum = maximum;
  5131. this.vectors = new Array();
  5132. this.vectorsWorld = new Array();
  5133. // Bounding vectors
  5134. this.vectors.push(this.minimum.clone());
  5135. this.vectors.push(this.maximum.clone());
  5136. this.vectors.push(this.minimum.clone());
  5137. this.vectors[2].x = this.maximum.x;
  5138. this.vectors.push(this.minimum.clone());
  5139. this.vectors[3].y = this.maximum.y;
  5140. this.vectors.push(this.minimum.clone());
  5141. this.vectors[4].z = this.maximum.z;
  5142. this.vectors.push(this.maximum.clone());
  5143. this.vectors[5].z = this.minimum.z;
  5144. this.vectors.push(this.maximum.clone());
  5145. this.vectors[6].x = this.minimum.x;
  5146. this.vectors.push(this.maximum.clone());
  5147. this.vectors[7].y = this.minimum.y;
  5148. // OBB
  5149. this.center = this.maximum.add(this.minimum).scale(0.5);
  5150. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5151. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5152. for (var index = 0; index < this.vectors.length; index++) {
  5153. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5154. }
  5155. this.minimumWorld = BABYLON.Vector3.Zero();
  5156. this.maximumWorld = BABYLON.Vector3.Zero();
  5157. this._update(BABYLON.Matrix.Identity());
  5158. }
  5159. // Methods
  5160. BoundingBox.prototype.getWorldMatrix = function () {
  5161. return this._worldMatrix;
  5162. };
  5163. BoundingBox.prototype._update = function (world) {
  5164. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5165. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5166. for (var index = 0; index < this.vectors.length; index++) {
  5167. var v = this.vectorsWorld[index];
  5168. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5169. if (v.x < this.minimumWorld.x)
  5170. this.minimumWorld.x = v.x;
  5171. if (v.y < this.minimumWorld.y)
  5172. this.minimumWorld.y = v.y;
  5173. if (v.z < this.minimumWorld.z)
  5174. this.minimumWorld.z = v.z;
  5175. if (v.x > this.maximumWorld.x)
  5176. this.maximumWorld.x = v.x;
  5177. if (v.y > this.maximumWorld.y)
  5178. this.maximumWorld.y = v.y;
  5179. if (v.z > this.maximumWorld.z)
  5180. this.maximumWorld.z = v.z;
  5181. }
  5182. // OBB
  5183. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5184. this.center.scaleInPlace(0.5);
  5185. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5186. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5187. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5188. this._worldMatrix = world;
  5189. };
  5190. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5191. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5192. };
  5193. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5194. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5195. };
  5196. BoundingBox.prototype.intersectsPoint = function (point) {
  5197. var delta = BABYLON.Engine.Epsilon;
  5198. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5199. return false;
  5200. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5201. return false;
  5202. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5203. return false;
  5204. return true;
  5205. };
  5206. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5207. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5208. };
  5209. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5210. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5211. return false;
  5212. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5213. return false;
  5214. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5215. return false;
  5216. return true;
  5217. };
  5218. // Statics
  5219. BoundingBox.Intersects = function (box0, box1) {
  5220. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5221. return false;
  5222. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5223. return false;
  5224. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5225. return false;
  5226. return true;
  5227. };
  5228. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5229. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5230. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5231. return (num <= (sphereRadius * sphereRadius));
  5232. };
  5233. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5234. for (var p = 0; p < 6; p++) {
  5235. for (var i = 0; i < 8; i++) {
  5236. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5237. return false;
  5238. }
  5239. }
  5240. }
  5241. return true;
  5242. };
  5243. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5244. for (var p = 0; p < 6; p++) {
  5245. var inCount = 8;
  5246. for (var i = 0; i < 8; i++) {
  5247. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5248. --inCount;
  5249. }
  5250. else {
  5251. break;
  5252. }
  5253. }
  5254. if (inCount == 0)
  5255. return false;
  5256. }
  5257. return true;
  5258. };
  5259. return BoundingBox;
  5260. })();
  5261. BABYLON.BoundingBox = BoundingBox;
  5262. })(BABYLON || (BABYLON = {}));
  5263. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5264. (function (BABYLON) {
  5265. var computeBoxExtents = function (axis, box) {
  5266. var p = BABYLON.Vector3.Dot(box.center, axis);
  5267. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5268. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5269. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5270. var r = r0 + r1 + r2;
  5271. return {
  5272. min: p - r,
  5273. max: p + r
  5274. };
  5275. };
  5276. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5277. var axisOverlap = function (axis, box0, box1) {
  5278. var result0 = computeBoxExtents(axis, box0);
  5279. var result1 = computeBoxExtents(axis, box1);
  5280. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5281. };
  5282. var BoundingInfo = (function () {
  5283. function BoundingInfo(minimum, maximum) {
  5284. this.minimum = minimum;
  5285. this.maximum = maximum;
  5286. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5287. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5288. }
  5289. // Methods
  5290. BoundingInfo.prototype._update = function (world) {
  5291. this.boundingBox._update(world);
  5292. this.boundingSphere._update(world);
  5293. };
  5294. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5295. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5296. return false;
  5297. return this.boundingBox.isInFrustum(frustumPlanes);
  5298. };
  5299. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5300. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5301. };
  5302. BoundingInfo.prototype._checkCollision = function (collider) {
  5303. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5304. };
  5305. BoundingInfo.prototype.intersectsPoint = function (point) {
  5306. if (!this.boundingSphere.centerWorld) {
  5307. return false;
  5308. }
  5309. if (!this.boundingSphere.intersectsPoint(point)) {
  5310. return false;
  5311. }
  5312. if (!this.boundingBox.intersectsPoint(point)) {
  5313. return false;
  5314. }
  5315. return true;
  5316. };
  5317. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5318. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5319. return false;
  5320. }
  5321. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5322. return false;
  5323. }
  5324. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5325. return false;
  5326. }
  5327. if (!precise) {
  5328. return true;
  5329. }
  5330. var box0 = this.boundingBox;
  5331. var box1 = boundingInfo.boundingBox;
  5332. if (!axisOverlap(box0.directions[0], box0, box1))
  5333. return false;
  5334. if (!axisOverlap(box0.directions[1], box0, box1))
  5335. return false;
  5336. if (!axisOverlap(box0.directions[2], box0, box1))
  5337. return false;
  5338. if (!axisOverlap(box1.directions[0], box0, box1))
  5339. return false;
  5340. if (!axisOverlap(box1.directions[1], box0, box1))
  5341. return false;
  5342. if (!axisOverlap(box1.directions[2], box0, box1))
  5343. return false;
  5344. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5345. return false;
  5346. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5347. return false;
  5348. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5349. return false;
  5350. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5351. return false;
  5352. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5353. return false;
  5354. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5355. return false;
  5356. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5357. return false;
  5358. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5359. return false;
  5360. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5361. return false;
  5362. return true;
  5363. };
  5364. return BoundingInfo;
  5365. })();
  5366. BABYLON.BoundingInfo = BoundingInfo;
  5367. })(BABYLON || (BABYLON = {}));
  5368. //# sourceMappingURL=babylon.boundingInfo.js.map
  5369. var BABYLON;
  5370. (function (BABYLON) {
  5371. var Light = (function (_super) {
  5372. __extends(Light, _super);
  5373. function Light(name, scene) {
  5374. _super.call(this, name, scene);
  5375. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5376. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5377. this.intensity = 1.0;
  5378. this.range = Number.MAX_VALUE;
  5379. this.includedOnlyMeshes = new Array();
  5380. this.excludedMeshes = new Array();
  5381. this._excludedMeshesIds = new Array();
  5382. this._includedOnlyMeshesIds = new Array();
  5383. scene.lights.push(this);
  5384. }
  5385. Light.prototype.getShadowGenerator = function () {
  5386. return this._shadowGenerator;
  5387. };
  5388. Light.prototype.getAbsolutePosition = function () {
  5389. return BABYLON.Vector3.Zero();
  5390. };
  5391. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5392. };
  5393. Light.prototype._getWorldMatrix = function () {
  5394. return BABYLON.Matrix.Identity();
  5395. };
  5396. Light.prototype.canAffectMesh = function (mesh) {
  5397. if (!mesh) {
  5398. return true;
  5399. }
  5400. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5401. return false;
  5402. }
  5403. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5404. return false;
  5405. }
  5406. return true;
  5407. };
  5408. Light.prototype.getWorldMatrix = function () {
  5409. this._currentRenderId = this.getScene().getRenderId();
  5410. var worldMatrix = this._getWorldMatrix();
  5411. if (this.parent && this.parent.getWorldMatrix) {
  5412. if (!this._parentedWorldMatrix) {
  5413. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5414. }
  5415. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5416. return this._parentedWorldMatrix;
  5417. }
  5418. return worldMatrix;
  5419. };
  5420. Light.prototype.dispose = function () {
  5421. if (this._shadowGenerator) {
  5422. this._shadowGenerator.dispose();
  5423. this._shadowGenerator = null;
  5424. }
  5425. // Remove from scene
  5426. var index = this.getScene().lights.indexOf(this);
  5427. this.getScene().lights.splice(index, 1);
  5428. };
  5429. return Light;
  5430. })(BABYLON.Node);
  5431. BABYLON.Light = Light;
  5432. })(BABYLON || (BABYLON = {}));
  5433. //# sourceMappingURL=babylon.light.js.map
  5434. var BABYLON;
  5435. (function (BABYLON) {
  5436. var PointLight = (function (_super) {
  5437. __extends(PointLight, _super);
  5438. function PointLight(name, position, scene) {
  5439. _super.call(this, name, scene);
  5440. this.position = position;
  5441. }
  5442. PointLight.prototype.getAbsolutePosition = function () {
  5443. return this._transformedPosition ? this._transformedPosition : this.position;
  5444. };
  5445. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5446. if (this.parent && this.parent.getWorldMatrix) {
  5447. if (!this._transformedPosition) {
  5448. this._transformedPosition = BABYLON.Vector3.Zero();
  5449. }
  5450. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5451. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5452. return;
  5453. }
  5454. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5455. };
  5456. PointLight.prototype.getShadowGenerator = function () {
  5457. return null;
  5458. };
  5459. PointLight.prototype._getWorldMatrix = function () {
  5460. if (!this._worldMatrix) {
  5461. this._worldMatrix = BABYLON.Matrix.Identity();
  5462. }
  5463. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5464. return this._worldMatrix;
  5465. };
  5466. return PointLight;
  5467. })(BABYLON.Light);
  5468. BABYLON.PointLight = PointLight;
  5469. })(BABYLON || (BABYLON = {}));
  5470. //# sourceMappingURL=babylon.pointLight.js.map
  5471. var BABYLON;
  5472. (function (BABYLON) {
  5473. var SpotLight = (function (_super) {
  5474. __extends(SpotLight, _super);
  5475. function SpotLight(name, position, direction, angle, exponent, scene) {
  5476. _super.call(this, name, scene);
  5477. this.position = position;
  5478. this.direction = direction;
  5479. this.angle = angle;
  5480. this.exponent = exponent;
  5481. }
  5482. SpotLight.prototype.getAbsolutePosition = function () {
  5483. return this.transformedPosition ? this.transformedPosition : this.position;
  5484. };
  5485. SpotLight.prototype.setDirectionToTarget = function (target) {
  5486. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5487. return this.direction;
  5488. };
  5489. SpotLight.prototype.computeTransformedPosition = function () {
  5490. if (this.parent && this.parent.getWorldMatrix) {
  5491. if (!this.transformedPosition) {
  5492. this.transformedPosition = BABYLON.Vector3.Zero();
  5493. }
  5494. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5495. return true;
  5496. }
  5497. return false;
  5498. };
  5499. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5500. var normalizeDirection;
  5501. if (this.parent && this.parent.getWorldMatrix) {
  5502. if (!this._transformedDirection) {
  5503. this._transformedDirection = BABYLON.Vector3.Zero();
  5504. }
  5505. this.computeTransformedPosition();
  5506. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5507. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5508. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5509. }
  5510. else {
  5511. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5512. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5513. }
  5514. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5515. };
  5516. SpotLight.prototype._getWorldMatrix = function () {
  5517. if (!this._worldMatrix) {
  5518. this._worldMatrix = BABYLON.Matrix.Identity();
  5519. }
  5520. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5521. return this._worldMatrix;
  5522. };
  5523. return SpotLight;
  5524. })(BABYLON.Light);
  5525. BABYLON.SpotLight = SpotLight;
  5526. })(BABYLON || (BABYLON = {}));
  5527. //# sourceMappingURL=babylon.spotLight.js.map
  5528. var BABYLON;
  5529. (function (BABYLON) {
  5530. var DirectionalLight = (function (_super) {
  5531. __extends(DirectionalLight, _super);
  5532. function DirectionalLight(name, direction, scene) {
  5533. _super.call(this, name, scene);
  5534. this.direction = direction;
  5535. this.position = direction.scale(-1);
  5536. }
  5537. DirectionalLight.prototype.getAbsolutePosition = function () {
  5538. return this.transformedPosition ? this.transformedPosition : this.position;
  5539. };
  5540. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5541. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5542. return this.direction;
  5543. };
  5544. DirectionalLight.prototype.computeTransformedPosition = function () {
  5545. if (this.parent && this.parent.getWorldMatrix) {
  5546. if (!this.transformedPosition) {
  5547. this.transformedPosition = BABYLON.Vector3.Zero();
  5548. }
  5549. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5550. return true;
  5551. }
  5552. return false;
  5553. };
  5554. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5555. if (this.parent && this.parent.getWorldMatrix) {
  5556. if (!this._transformedDirection) {
  5557. this._transformedDirection = BABYLON.Vector3.Zero();
  5558. }
  5559. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5560. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5561. return;
  5562. }
  5563. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5564. };
  5565. DirectionalLight.prototype._getWorldMatrix = function () {
  5566. if (!this._worldMatrix) {
  5567. this._worldMatrix = BABYLON.Matrix.Identity();
  5568. }
  5569. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5570. return this._worldMatrix;
  5571. };
  5572. return DirectionalLight;
  5573. })(BABYLON.Light);
  5574. BABYLON.DirectionalLight = DirectionalLight;
  5575. })(BABYLON || (BABYLON = {}));
  5576. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5577. (function (BABYLON) {
  5578. var ShadowGenerator = (function () {
  5579. function ShadowGenerator(mapSize, light) {
  5580. var _this = this;
  5581. // Members
  5582. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5583. this._darkness = 0;
  5584. this._transparencyShadow = false;
  5585. this._viewMatrix = BABYLON.Matrix.Zero();
  5586. this._projectionMatrix = BABYLON.Matrix.Zero();
  5587. this._transformMatrix = BABYLON.Matrix.Zero();
  5588. this._worldViewProjection = BABYLON.Matrix.Zero();
  5589. this._light = light;
  5590. this._scene = light.getScene();
  5591. light._shadowGenerator = this;
  5592. // Render target
  5593. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5594. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5595. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5596. this._shadowMap.renderParticles = false;
  5597. // Custom render function
  5598. var renderSubMesh = function (subMesh) {
  5599. var mesh = subMesh.getRenderingMesh();
  5600. var scene = _this._scene;
  5601. var engine = scene.getEngine();
  5602. // Culling
  5603. engine.setState(subMesh.getMaterial().backFaceCulling);
  5604. // Managing instances
  5605. var batch = mesh._getInstancesRenderList(subMesh._id);
  5606. if (batch.mustReturn) {
  5607. return;
  5608. }
  5609. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5610. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5611. engine.enableEffect(_this._effect);
  5612. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5613. var material = subMesh.getMaterial();
  5614. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5615. // Alpha test
  5616. if (material && material.needAlphaTesting()) {
  5617. var alphaTexture = material.getAlphaTestTexture();
  5618. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5619. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5620. }
  5621. // Bones
  5622. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  5623. if (useBones) {
  5624. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5625. }
  5626. if (hardwareInstancedRendering) {
  5627. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  5628. }
  5629. else {
  5630. if (batch.renderSelf[subMesh._id]) {
  5631. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  5632. // Draw
  5633. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5634. }
  5635. if (batch.visibleInstances[subMesh._id]) {
  5636. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  5637. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  5638. _this._effect.setMatrix("world", instance.getWorldMatrix());
  5639. // Draw
  5640. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5641. }
  5642. }
  5643. }
  5644. }
  5645. else {
  5646. // Need to reset refresh rate of the shadowMap
  5647. _this._shadowMap.resetRefreshCounter();
  5648. }
  5649. };
  5650. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5651. var index;
  5652. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5653. renderSubMesh(opaqueSubMeshes.data[index]);
  5654. }
  5655. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5656. renderSubMesh(alphaTestSubMeshes.data[index]);
  5657. }
  5658. if (_this._transparencyShadow) {
  5659. for (index = 0; index < transparentSubMeshes.length; index++) {
  5660. renderSubMesh(transparentSubMeshes.data[index]);
  5661. }
  5662. }
  5663. };
  5664. }
  5665. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5666. // Static
  5667. get: function () {
  5668. return ShadowGenerator._FILTER_NONE;
  5669. },
  5670. enumerable: true,
  5671. configurable: true
  5672. });
  5673. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5674. get: function () {
  5675. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5676. },
  5677. enumerable: true,
  5678. configurable: true
  5679. });
  5680. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5681. get: function () {
  5682. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5683. },
  5684. enumerable: true,
  5685. configurable: true
  5686. });
  5687. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5688. get: function () {
  5689. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5690. },
  5691. set: function (value) {
  5692. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5693. },
  5694. enumerable: true,
  5695. configurable: true
  5696. });
  5697. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5698. get: function () {
  5699. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5700. },
  5701. set: function (value) {
  5702. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5703. },
  5704. enumerable: true,
  5705. configurable: true
  5706. });
  5707. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5708. var defines = [];
  5709. if (this.useVarianceShadowMap) {
  5710. defines.push("#define VSM");
  5711. }
  5712. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5713. var mesh = subMesh.getMesh();
  5714. var scene = mesh.getScene();
  5715. var material = subMesh.getMaterial();
  5716. // Alpha test
  5717. if (material && material.needAlphaTesting()) {
  5718. defines.push("#define ALPHATEST");
  5719. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5720. attribs.push(BABYLON.VertexBuffer.UVKind);
  5721. defines.push("#define UV1");
  5722. }
  5723. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5724. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5725. defines.push("#define UV2");
  5726. }
  5727. }
  5728. // Bones
  5729. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  5730. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5731. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5732. defines.push("#define BONES");
  5733. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5734. }
  5735. // Instances
  5736. if (useInstances) {
  5737. defines.push("#define INSTANCES");
  5738. attribs.push("world0");
  5739. attribs.push("world1");
  5740. attribs.push("world2");
  5741. attribs.push("world3");
  5742. }
  5743. // Get correct effect
  5744. var join = defines.join("\n");
  5745. if (this._cachedDefines !== join) {
  5746. this._cachedDefines = join;
  5747. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5748. }
  5749. return this._effect.isReady();
  5750. };
  5751. ShadowGenerator.prototype.getShadowMap = function () {
  5752. return this._shadowMap;
  5753. };
  5754. ShadowGenerator.prototype.getLight = function () {
  5755. return this._light;
  5756. };
  5757. // Methods
  5758. ShadowGenerator.prototype.getTransformMatrix = function () {
  5759. var lightPosition = this._light.position;
  5760. var lightDirection = this._light.direction;
  5761. if (this._light.computeTransformedPosition()) {
  5762. lightPosition = this._light.transformedPosition;
  5763. }
  5764. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5765. this._cachedPosition = lightPosition.clone();
  5766. this._cachedDirection = lightDirection.clone();
  5767. var activeCamera = this._scene.activeCamera;
  5768. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5769. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5770. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5771. }
  5772. return this._transformMatrix;
  5773. };
  5774. ShadowGenerator.prototype.getDarkness = function () {
  5775. return this._darkness;
  5776. };
  5777. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5778. if (darkness >= 1.0)
  5779. this._darkness = 1.0;
  5780. else if (darkness <= 0.0)
  5781. this._darkness = 0.0;
  5782. else
  5783. this._darkness = darkness;
  5784. };
  5785. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5786. this._transparencyShadow = hasShadow;
  5787. };
  5788. ShadowGenerator.prototype.dispose = function () {
  5789. this._shadowMap.dispose();
  5790. };
  5791. ShadowGenerator._FILTER_NONE = 0;
  5792. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5793. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5794. return ShadowGenerator;
  5795. })();
  5796. BABYLON.ShadowGenerator = ShadowGenerator;
  5797. })(BABYLON || (BABYLON = {}));
  5798. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5799. var BABYLON;
  5800. (function (BABYLON) {
  5801. var HemisphericLight = (function (_super) {
  5802. __extends(HemisphericLight, _super);
  5803. function HemisphericLight(name, direction, scene) {
  5804. _super.call(this, name, scene);
  5805. this.direction = direction;
  5806. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5807. }
  5808. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5809. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5810. return this.direction;
  5811. };
  5812. HemisphericLight.prototype.getShadowGenerator = function () {
  5813. return null;
  5814. };
  5815. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5816. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5817. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5818. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5819. };
  5820. HemisphericLight.prototype._getWorldMatrix = function () {
  5821. if (!this._worldMatrix) {
  5822. this._worldMatrix = BABYLON.Matrix.Identity();
  5823. }
  5824. return this._worldMatrix;
  5825. };
  5826. return HemisphericLight;
  5827. })(BABYLON.Light);
  5828. BABYLON.HemisphericLight = HemisphericLight;
  5829. })(BABYLON || (BABYLON = {}));
  5830. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  5831. (function (BABYLON) {
  5832. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5833. if (boxMin.x > sphereCenter.x + sphereRadius)
  5834. return false;
  5835. if (sphereCenter.x - sphereRadius > boxMax.x)
  5836. return false;
  5837. if (boxMin.y > sphereCenter.y + sphereRadius)
  5838. return false;
  5839. if (sphereCenter.y - sphereRadius > boxMax.y)
  5840. return false;
  5841. if (boxMin.z > sphereCenter.z + sphereRadius)
  5842. return false;
  5843. if (sphereCenter.z - sphereRadius > boxMax.z)
  5844. return false;
  5845. return true;
  5846. };
  5847. var getLowestRoot = function (a, b, c, maxR) {
  5848. var determinant = b * b - 4.0 * a * c;
  5849. var result = { root: 0, found: false };
  5850. if (determinant < 0)
  5851. return result;
  5852. var sqrtD = Math.sqrt(determinant);
  5853. var r1 = (-b - sqrtD) / (2.0 * a);
  5854. var r2 = (-b + sqrtD) / (2.0 * a);
  5855. if (r1 > r2) {
  5856. var temp = r2;
  5857. r2 = r1;
  5858. r1 = temp;
  5859. }
  5860. if (r1 > 0 && r1 < maxR) {
  5861. result.root = r1;
  5862. result.found = true;
  5863. return result;
  5864. }
  5865. if (r2 > 0 && r2 < maxR) {
  5866. result.root = r2;
  5867. result.found = true;
  5868. return result;
  5869. }
  5870. return result;
  5871. };
  5872. var Collider = (function () {
  5873. function Collider() {
  5874. this.radius = new BABYLON.Vector3(1, 1, 1);
  5875. this.retry = 0;
  5876. this.basePointWorld = BABYLON.Vector3.Zero();
  5877. this.velocityWorld = BABYLON.Vector3.Zero();
  5878. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5879. this._collisionPoint = BABYLON.Vector3.Zero();
  5880. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5881. this._tempVector = BABYLON.Vector3.Zero();
  5882. this._tempVector2 = BABYLON.Vector3.Zero();
  5883. this._tempVector3 = BABYLON.Vector3.Zero();
  5884. this._tempVector4 = BABYLON.Vector3.Zero();
  5885. this._edge = BABYLON.Vector3.Zero();
  5886. this._baseToVertex = BABYLON.Vector3.Zero();
  5887. this._destinationPoint = BABYLON.Vector3.Zero();
  5888. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5889. this._displacementVector = BABYLON.Vector3.Zero();
  5890. }
  5891. // Methods
  5892. Collider.prototype._initialize = function (source, dir, e) {
  5893. this.velocity = dir;
  5894. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5895. this.basePoint = source;
  5896. source.multiplyToRef(this.radius, this.basePointWorld);
  5897. dir.multiplyToRef(this.radius, this.velocityWorld);
  5898. this.velocityWorldLength = this.velocityWorld.length();
  5899. this.epsilon = e;
  5900. this.collisionFound = false;
  5901. };
  5902. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5903. pa.subtractToRef(point, this._tempVector);
  5904. pb.subtractToRef(point, this._tempVector2);
  5905. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5906. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5907. if (d < 0)
  5908. return false;
  5909. pc.subtractToRef(point, this._tempVector3);
  5910. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5911. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5912. if (d < 0)
  5913. return false;
  5914. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5915. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5916. return d >= 0;
  5917. };
  5918. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5919. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5920. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5921. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5922. return false;
  5923. }
  5924. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5925. return false;
  5926. return true;
  5927. };
  5928. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5929. var t0;
  5930. var embeddedInPlane = false;
  5931. if (!subMesh._trianglePlanes) {
  5932. subMesh._trianglePlanes = [];
  5933. }
  5934. if (!subMesh._trianglePlanes[faceIndex]) {
  5935. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5936. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5937. }
  5938. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5939. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5940. return;
  5941. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5942. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5943. if (normalDotVelocity == 0) {
  5944. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5945. return;
  5946. embeddedInPlane = true;
  5947. t0 = 0;
  5948. }
  5949. else {
  5950. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5951. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5952. if (t0 > t1) {
  5953. var temp = t1;
  5954. t1 = t0;
  5955. t0 = temp;
  5956. }
  5957. if (t0 > 1.0 || t1 < 0.0)
  5958. return;
  5959. if (t0 < 0)
  5960. t0 = 0;
  5961. if (t0 > 1.0)
  5962. t0 = 1.0;
  5963. }
  5964. this._collisionPoint.copyFromFloats(0, 0, 0);
  5965. var found = false;
  5966. var t = 1.0;
  5967. if (!embeddedInPlane) {
  5968. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5969. this.velocity.scaleToRef(t0, this._tempVector);
  5970. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5971. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5972. found = true;
  5973. t = t0;
  5974. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5975. }
  5976. }
  5977. if (!found) {
  5978. var velocitySquaredLength = this.velocity.lengthSquared();
  5979. var a = velocitySquaredLength;
  5980. this.basePoint.subtractToRef(p1, this._tempVector);
  5981. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5982. var c = this._tempVector.lengthSquared() - 1.0;
  5983. var lowestRoot = getLowestRoot(a, b, c, t);
  5984. if (lowestRoot.found) {
  5985. t = lowestRoot.root;
  5986. found = true;
  5987. this._collisionPoint.copyFrom(p1);
  5988. }
  5989. this.basePoint.subtractToRef(p2, this._tempVector);
  5990. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5991. c = this._tempVector.lengthSquared() - 1.0;
  5992. lowestRoot = getLowestRoot(a, b, c, t);
  5993. if (lowestRoot.found) {
  5994. t = lowestRoot.root;
  5995. found = true;
  5996. this._collisionPoint.copyFrom(p2);
  5997. }
  5998. this.basePoint.subtractToRef(p3, this._tempVector);
  5999. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6000. c = this._tempVector.lengthSquared() - 1.0;
  6001. lowestRoot = getLowestRoot(a, b, c, t);
  6002. if (lowestRoot.found) {
  6003. t = lowestRoot.root;
  6004. found = true;
  6005. this._collisionPoint.copyFrom(p3);
  6006. }
  6007. p2.subtractToRef(p1, this._edge);
  6008. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6009. var edgeSquaredLength = this._edge.lengthSquared();
  6010. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6011. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6012. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6013. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6014. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6015. lowestRoot = getLowestRoot(a, b, c, t);
  6016. if (lowestRoot.found) {
  6017. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6018. if (f >= 0.0 && f <= 1.0) {
  6019. t = lowestRoot.root;
  6020. found = true;
  6021. this._edge.scaleInPlace(f);
  6022. p1.addToRef(this._edge, this._collisionPoint);
  6023. }
  6024. }
  6025. p3.subtractToRef(p2, this._edge);
  6026. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6027. edgeSquaredLength = this._edge.lengthSquared();
  6028. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6029. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6030. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6031. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6032. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6033. lowestRoot = getLowestRoot(a, b, c, t);
  6034. if (lowestRoot.found) {
  6035. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6036. if (f >= 0.0 && f <= 1.0) {
  6037. t = lowestRoot.root;
  6038. found = true;
  6039. this._edge.scaleInPlace(f);
  6040. p2.addToRef(this._edge, this._collisionPoint);
  6041. }
  6042. }
  6043. p1.subtractToRef(p3, this._edge);
  6044. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6045. edgeSquaredLength = this._edge.lengthSquared();
  6046. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6047. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6048. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6049. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6050. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6051. lowestRoot = getLowestRoot(a, b, c, t);
  6052. if (lowestRoot.found) {
  6053. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6054. if (f >= 0.0 && f <= 1.0) {
  6055. t = lowestRoot.root;
  6056. found = true;
  6057. this._edge.scaleInPlace(f);
  6058. p3.addToRef(this._edge, this._collisionPoint);
  6059. }
  6060. }
  6061. }
  6062. if (found) {
  6063. var distToCollision = t * this.velocity.length();
  6064. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6065. if (!this.intersectionPoint) {
  6066. this.intersectionPoint = this._collisionPoint.clone();
  6067. }
  6068. else {
  6069. this.intersectionPoint.copyFrom(this._collisionPoint);
  6070. }
  6071. this.nearestDistance = distToCollision;
  6072. this.collisionFound = true;
  6073. this.collidedMesh = subMesh.getMesh();
  6074. }
  6075. }
  6076. };
  6077. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6078. for (var i = indexStart; i < indexEnd; i += 3) {
  6079. var p1 = pts[indices[i] - decal];
  6080. var p2 = pts[indices[i + 1] - decal];
  6081. var p3 = pts[indices[i + 2] - decal];
  6082. this._testTriangle(i, subMesh, p3, p2, p1);
  6083. }
  6084. };
  6085. Collider.prototype._getResponse = function (pos, vel) {
  6086. pos.addToRef(vel, this._destinationPoint);
  6087. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6088. this.basePoint.addToRef(vel, pos);
  6089. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6090. this._slidePlaneNormal.normalize();
  6091. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6092. pos.addInPlace(this._displacementVector);
  6093. this.intersectionPoint.addInPlace(this._displacementVector);
  6094. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6095. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6096. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6097. };
  6098. return Collider;
  6099. })();
  6100. BABYLON.Collider = Collider;
  6101. })(BABYLON || (BABYLON = {}));
  6102. //# sourceMappingURL=babylon.collider.js.map
  6103. var BABYLON;
  6104. (function (BABYLON) {
  6105. var Camera = (function (_super) {
  6106. __extends(Camera, _super);
  6107. function Camera(name, position, scene) {
  6108. _super.call(this, name, scene);
  6109. this.position = position;
  6110. // Members
  6111. this.upVector = BABYLON.Vector3.Up();
  6112. this.orthoLeft = null;
  6113. this.orthoRight = null;
  6114. this.orthoBottom = null;
  6115. this.orthoTop = null;
  6116. this.fov = 0.8;
  6117. this.minZ = 1.0;
  6118. this.maxZ = 10000.0;
  6119. this.inertia = 0.9;
  6120. this.mode = Camera.PERSPECTIVE_CAMERA;
  6121. this.isIntermediate = false;
  6122. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6123. this.subCameras = [];
  6124. this.layerMask = 0xFFFFFFFF;
  6125. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6126. this._projectionMatrix = new BABYLON.Matrix();
  6127. this._postProcesses = new Array();
  6128. this._postProcessesTakenIndices = [];
  6129. scene.cameras.push(this);
  6130. if (!scene.activeCamera) {
  6131. scene.activeCamera = this;
  6132. }
  6133. }
  6134. //Cache
  6135. Camera.prototype._initCache = function () {
  6136. _super.prototype._initCache.call(this);
  6137. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6138. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6139. this._cache.mode = undefined;
  6140. this._cache.minZ = undefined;
  6141. this._cache.maxZ = undefined;
  6142. this._cache.fov = undefined;
  6143. this._cache.aspectRatio = undefined;
  6144. this._cache.orthoLeft = undefined;
  6145. this._cache.orthoRight = undefined;
  6146. this._cache.orthoBottom = undefined;
  6147. this._cache.orthoTop = undefined;
  6148. this._cache.renderWidth = undefined;
  6149. this._cache.renderHeight = undefined;
  6150. };
  6151. Camera.prototype._updateCache = function (ignoreParentClass) {
  6152. if (!ignoreParentClass) {
  6153. _super.prototype._updateCache.call(this);
  6154. }
  6155. var engine = this.getEngine();
  6156. this._cache.position.copyFrom(this.position);
  6157. this._cache.upVector.copyFrom(this.upVector);
  6158. this._cache.mode = this.mode;
  6159. this._cache.minZ = this.minZ;
  6160. this._cache.maxZ = this.maxZ;
  6161. this._cache.fov = this.fov;
  6162. this._cache.aspectRatio = engine.getAspectRatio(this);
  6163. this._cache.orthoLeft = this.orthoLeft;
  6164. this._cache.orthoRight = this.orthoRight;
  6165. this._cache.orthoBottom = this.orthoBottom;
  6166. this._cache.orthoTop = this.orthoTop;
  6167. this._cache.renderWidth = engine.getRenderWidth();
  6168. this._cache.renderHeight = engine.getRenderHeight();
  6169. };
  6170. Camera.prototype._updateFromScene = function () {
  6171. this.updateCache();
  6172. this._update();
  6173. };
  6174. // Synchronized
  6175. Camera.prototype._isSynchronized = function () {
  6176. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6177. };
  6178. Camera.prototype._isSynchronizedViewMatrix = function () {
  6179. if (!_super.prototype._isSynchronized.call(this))
  6180. return false;
  6181. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6182. };
  6183. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6184. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6185. if (!check) {
  6186. return false;
  6187. }
  6188. var engine = this.getEngine();
  6189. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6190. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6191. }
  6192. else {
  6193. check = this._cache.orthoLeft === this.orthoLeft && this._cache.orthoRight === this.orthoRight && this._cache.orthoBottom === this.orthoBottom && this._cache.orthoTop === this.orthoTop && this._cache.renderWidth === engine.getRenderWidth() && this._cache.renderHeight === engine.getRenderHeight();
  6194. }
  6195. return check;
  6196. };
  6197. // Controls
  6198. Camera.prototype.attachControl = function (element) {
  6199. };
  6200. Camera.prototype.detachControl = function (element) {
  6201. };
  6202. Camera.prototype._update = function () {
  6203. };
  6204. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6205. if (insertAt === void 0) { insertAt = null; }
  6206. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6207. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6208. return 0;
  6209. }
  6210. if (insertAt == null || insertAt < 0) {
  6211. this._postProcesses.push(postProcess);
  6212. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6213. return this._postProcesses.length - 1;
  6214. }
  6215. var add = 0;
  6216. if (this._postProcesses[insertAt]) {
  6217. var start = this._postProcesses.length - 1;
  6218. for (var i = start; i >= insertAt + 1; --i) {
  6219. this._postProcesses[i + 1] = this._postProcesses[i];
  6220. }
  6221. add = 1;
  6222. }
  6223. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6224. if (this._postProcessesTakenIndices[i] < insertAt) {
  6225. continue;
  6226. }
  6227. start = this._postProcessesTakenIndices.length - 1;
  6228. for (var j = start; j >= i; --j) {
  6229. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6230. }
  6231. this._postProcessesTakenIndices[i] = insertAt;
  6232. break;
  6233. }
  6234. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6235. this._postProcessesTakenIndices.push(insertAt);
  6236. }
  6237. var result = insertAt + add;
  6238. this._postProcesses[result] = postProcess;
  6239. return result;
  6240. };
  6241. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6242. if (atIndices === void 0) { atIndices = null; }
  6243. var result = [];
  6244. if (!atIndices) {
  6245. var length = this._postProcesses.length;
  6246. for (var i = 0; i < length; i++) {
  6247. if (this._postProcesses[i] !== postProcess) {
  6248. continue;
  6249. }
  6250. delete this._postProcesses[i];
  6251. var index = this._postProcessesTakenIndices.indexOf(i);
  6252. this._postProcessesTakenIndices.splice(index, 1);
  6253. }
  6254. }
  6255. else {
  6256. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6257. for (i = 0; i < atIndices.length; i++) {
  6258. var foundPostProcess = this._postProcesses[atIndices[i]];
  6259. if (foundPostProcess !== postProcess) {
  6260. result.push(i);
  6261. continue;
  6262. }
  6263. delete this._postProcesses[atIndices[i]];
  6264. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6265. this._postProcessesTakenIndices.splice(index, 1);
  6266. }
  6267. }
  6268. return result;
  6269. };
  6270. Camera.prototype.getWorldMatrix = function () {
  6271. if (!this._worldMatrix) {
  6272. this._worldMatrix = BABYLON.Matrix.Identity();
  6273. }
  6274. var viewMatrix = this.getViewMatrix();
  6275. viewMatrix.invertToRef(this._worldMatrix);
  6276. return this._worldMatrix;
  6277. };
  6278. Camera.prototype._getViewMatrix = function () {
  6279. return BABYLON.Matrix.Identity();
  6280. };
  6281. Camera.prototype.getViewMatrix = function () {
  6282. this._computedViewMatrix = this._computeViewMatrix();
  6283. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6284. return this._computedViewMatrix;
  6285. }
  6286. if (!this._worldMatrix) {
  6287. this._worldMatrix = BABYLON.Matrix.Identity();
  6288. }
  6289. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6290. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6291. this._computedViewMatrix.invert();
  6292. this._currentRenderId = this.getScene().getRenderId();
  6293. return this._computedViewMatrix;
  6294. };
  6295. Camera.prototype._computeViewMatrix = function (force) {
  6296. if (!force && this._isSynchronizedViewMatrix()) {
  6297. return this._computedViewMatrix;
  6298. }
  6299. this._computedViewMatrix = this._getViewMatrix();
  6300. if (!this.parent || !this.parent.getWorldMatrix) {
  6301. this._currentRenderId = this.getScene().getRenderId();
  6302. }
  6303. return this._computedViewMatrix;
  6304. };
  6305. Camera.prototype.getProjectionMatrix = function (force) {
  6306. if (!force && this._isSynchronizedProjectionMatrix()) {
  6307. return this._projectionMatrix;
  6308. }
  6309. var engine = this.getEngine();
  6310. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6311. if (this.minZ <= 0) {
  6312. this.minZ = 0.1;
  6313. }
  6314. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  6315. return this._projectionMatrix;
  6316. }
  6317. var halfWidth = engine.getRenderWidth() / 2.0;
  6318. var halfHeight = engine.getRenderHeight() / 2.0;
  6319. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6320. return this._projectionMatrix;
  6321. };
  6322. Camera.prototype.dispose = function () {
  6323. // Remove from scene
  6324. var index = this.getScene().cameras.indexOf(this);
  6325. this.getScene().cameras.splice(index, 1);
  6326. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6327. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6328. }
  6329. };
  6330. // Statics
  6331. Camera.PERSPECTIVE_CAMERA = 0;
  6332. Camera.ORTHOGRAPHIC_CAMERA = 1;
  6333. return Camera;
  6334. })(BABYLON.Node);
  6335. BABYLON.Camera = Camera;
  6336. })(BABYLON || (BABYLON = {}));
  6337. //# sourceMappingURL=babylon.camera.js.map
  6338. var BABYLON;
  6339. (function (BABYLON) {
  6340. var TargetCamera = (function (_super) {
  6341. __extends(TargetCamera, _super);
  6342. function TargetCamera(name, position, scene) {
  6343. _super.call(this, name, position, scene);
  6344. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6345. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6346. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6347. this.speed = 2.0;
  6348. this.noRotationConstraint = false;
  6349. this.lockedTarget = null;
  6350. this._currentTarget = BABYLON.Vector3.Zero();
  6351. this._viewMatrix = BABYLON.Matrix.Zero();
  6352. this._camMatrix = BABYLON.Matrix.Zero();
  6353. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6354. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6355. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6356. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6357. this._lookAtTemp = BABYLON.Matrix.Zero();
  6358. this._tempMatrix = BABYLON.Matrix.Zero();
  6359. }
  6360. TargetCamera.prototype._getLockedTargetPosition = function () {
  6361. if (!this.lockedTarget) {
  6362. return null;
  6363. }
  6364. return this.lockedTarget.position || this.lockedTarget;
  6365. };
  6366. // Cache
  6367. TargetCamera.prototype._initCache = function () {
  6368. _super.prototype._initCache.call(this);
  6369. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6370. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6371. };
  6372. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6373. if (!ignoreParentClass) {
  6374. _super.prototype._updateCache.call(this);
  6375. }
  6376. var lockedTargetPosition = this._getLockedTargetPosition();
  6377. if (!lockedTargetPosition) {
  6378. this._cache.lockedTarget = null;
  6379. }
  6380. else {
  6381. if (!this._cache.lockedTarget) {
  6382. this._cache.lockedTarget = lockedTargetPosition.clone();
  6383. }
  6384. else {
  6385. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6386. }
  6387. }
  6388. this._cache.rotation.copyFrom(this.rotation);
  6389. };
  6390. // Synchronized
  6391. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6392. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6393. return false;
  6394. }
  6395. var lockedTargetPosition = this._getLockedTargetPosition();
  6396. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6397. };
  6398. // Methods
  6399. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6400. var engine = this.getEngine();
  6401. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6402. };
  6403. // Target
  6404. TargetCamera.prototype.setTarget = function (target) {
  6405. this.upVector.normalize();
  6406. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6407. this._camMatrix.invert();
  6408. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6409. var vDir = target.subtract(this.position);
  6410. if (vDir.x >= 0.0) {
  6411. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6412. }
  6413. else {
  6414. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6415. }
  6416. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6417. if (isNaN(this.rotation.x)) {
  6418. this.rotation.x = 0;
  6419. }
  6420. if (isNaN(this.rotation.y)) {
  6421. this.rotation.y = 0;
  6422. }
  6423. if (isNaN(this.rotation.z)) {
  6424. this.rotation.z = 0;
  6425. }
  6426. };
  6427. TargetCamera.prototype.getTarget = function () {
  6428. return this._currentTarget;
  6429. };
  6430. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6431. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6432. };
  6433. TargetCamera.prototype._updatePosition = function () {
  6434. this.position.addInPlace(this.cameraDirection);
  6435. };
  6436. TargetCamera.prototype._update = function () {
  6437. var needToMove = this._decideIfNeedsToMove();
  6438. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6439. // Move
  6440. if (needToMove) {
  6441. this._updatePosition();
  6442. }
  6443. // Rotate
  6444. if (needToRotate) {
  6445. this.rotation.x += this.cameraRotation.x;
  6446. this.rotation.y += this.cameraRotation.y;
  6447. if (!this.noRotationConstraint) {
  6448. var limit = (Math.PI / 2) * 0.95;
  6449. if (this.rotation.x > limit)
  6450. this.rotation.x = limit;
  6451. if (this.rotation.x < -limit)
  6452. this.rotation.x = -limit;
  6453. }
  6454. }
  6455. // Inertia
  6456. if (needToMove) {
  6457. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6458. this.cameraDirection.x = 0;
  6459. }
  6460. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6461. this.cameraDirection.y = 0;
  6462. }
  6463. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6464. this.cameraDirection.z = 0;
  6465. }
  6466. this.cameraDirection.scaleInPlace(this.inertia);
  6467. }
  6468. if (needToRotate) {
  6469. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6470. this.cameraRotation.x = 0;
  6471. }
  6472. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6473. this.cameraRotation.y = 0;
  6474. }
  6475. this.cameraRotation.scaleInPlace(this.inertia);
  6476. }
  6477. };
  6478. TargetCamera.prototype._getViewMatrix = function () {
  6479. if (!this.lockedTarget) {
  6480. // Compute
  6481. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6482. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6483. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6484. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6485. this._lookAtTemp.invert();
  6486. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6487. }
  6488. else {
  6489. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6490. }
  6491. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6492. // Computing target and final matrix
  6493. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6494. }
  6495. else {
  6496. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6497. }
  6498. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6499. return this._viewMatrix;
  6500. };
  6501. return TargetCamera;
  6502. })(BABYLON.Camera);
  6503. BABYLON.TargetCamera = TargetCamera;
  6504. })(BABYLON || (BABYLON = {}));
  6505. //# sourceMappingURL=babylon.targetCamera.js.map
  6506. var BABYLON;
  6507. (function (BABYLON) {
  6508. var FollowCamera = (function (_super) {
  6509. __extends(FollowCamera, _super);
  6510. function FollowCamera(name, position, scene) {
  6511. _super.call(this, name, position, scene);
  6512. this.radius = 12;
  6513. this.rotationOffset = 0;
  6514. this.heightOffset = 4;
  6515. this.cameraAcceleration = 0.05;
  6516. this.maxCameraSpeed = 20;
  6517. }
  6518. FollowCamera.prototype.getRadians = function (degrees) {
  6519. return degrees * Math.PI / 180;
  6520. };
  6521. FollowCamera.prototype.follow = function (cameraTarget) {
  6522. if (!cameraTarget)
  6523. return;
  6524. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6525. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6526. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6527. var dx = targetX - this.position.x;
  6528. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6529. var dz = (targetZ) - this.position.z;
  6530. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  6531. var vy = dy * this.cameraAcceleration;
  6532. var vz = dz * this.cameraAcceleration * 2;
  6533. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6534. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6535. }
  6536. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6537. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6538. }
  6539. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6540. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6541. }
  6542. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6543. this.setTarget(cameraTarget.position);
  6544. };
  6545. FollowCamera.prototype._update = function () {
  6546. _super.prototype._update.call(this);
  6547. this.follow(this.target);
  6548. };
  6549. return FollowCamera;
  6550. })(BABYLON.TargetCamera);
  6551. BABYLON.FollowCamera = FollowCamera;
  6552. })(BABYLON || (BABYLON = {}));
  6553. //# sourceMappingURL=babylon.followCamera.js.map
  6554. var BABYLON;
  6555. (function (BABYLON) {
  6556. var FreeCamera = (function (_super) {
  6557. __extends(FreeCamera, _super);
  6558. function FreeCamera(name, position, scene) {
  6559. _super.call(this, name, position, scene);
  6560. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6561. this.keysUp = [38];
  6562. this.keysDown = [40];
  6563. this.keysLeft = [37];
  6564. this.keysRight = [39];
  6565. this.checkCollisions = false;
  6566. this.applyGravity = false;
  6567. this.angularSensibility = 2000.0;
  6568. this._keys = [];
  6569. this._collider = new BABYLON.Collider();
  6570. this._needMoveForGravity = true;
  6571. this._oldPosition = BABYLON.Vector3.Zero();
  6572. this._diffPosition = BABYLON.Vector3.Zero();
  6573. this._newPosition = BABYLON.Vector3.Zero();
  6574. }
  6575. // Controls
  6576. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6577. var _this = this;
  6578. var previousPosition;
  6579. var engine = this.getEngine();
  6580. if (this._attachedElement) {
  6581. return;
  6582. }
  6583. this._attachedElement = element;
  6584. if (this._onMouseDown === undefined) {
  6585. this._onMouseDown = function (evt) {
  6586. previousPosition = {
  6587. x: evt.clientX,
  6588. y: evt.clientY
  6589. };
  6590. if (!noPreventDefault) {
  6591. evt.preventDefault();
  6592. }
  6593. };
  6594. this._onMouseUp = function (evt) {
  6595. previousPosition = null;
  6596. if (!noPreventDefault) {
  6597. evt.preventDefault();
  6598. }
  6599. };
  6600. this._onMouseOut = function (evt) {
  6601. previousPosition = null;
  6602. _this._keys = [];
  6603. if (!noPreventDefault) {
  6604. evt.preventDefault();
  6605. }
  6606. };
  6607. this._onMouseMove = function (evt) {
  6608. if (!previousPosition && !engine.isPointerLock) {
  6609. return;
  6610. }
  6611. var offsetX;
  6612. var offsetY;
  6613. if (!engine.isPointerLock) {
  6614. offsetX = evt.clientX - previousPosition.x;
  6615. offsetY = evt.clientY - previousPosition.y;
  6616. }
  6617. else {
  6618. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6619. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6620. }
  6621. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6622. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6623. previousPosition = {
  6624. x: evt.clientX,
  6625. y: evt.clientY
  6626. };
  6627. if (!noPreventDefault) {
  6628. evt.preventDefault();
  6629. }
  6630. };
  6631. this._onKeyDown = function (evt) {
  6632. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  6633. var index = _this._keys.indexOf(evt.keyCode);
  6634. if (index === -1) {
  6635. _this._keys.push(evt.keyCode);
  6636. }
  6637. if (!noPreventDefault) {
  6638. evt.preventDefault();
  6639. }
  6640. }
  6641. };
  6642. this._onKeyUp = function (evt) {
  6643. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  6644. var index = _this._keys.indexOf(evt.keyCode);
  6645. if (index >= 0) {
  6646. _this._keys.splice(index, 1);
  6647. }
  6648. if (!noPreventDefault) {
  6649. evt.preventDefault();
  6650. }
  6651. }
  6652. };
  6653. this._onLostFocus = function () {
  6654. _this._keys = [];
  6655. };
  6656. this._reset = function () {
  6657. _this._keys = [];
  6658. previousPosition = null;
  6659. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6660. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6661. };
  6662. }
  6663. element.addEventListener("mousedown", this._onMouseDown, false);
  6664. element.addEventListener("mouseup", this._onMouseUp, false);
  6665. element.addEventListener("mouseout", this._onMouseOut, false);
  6666. element.addEventListener("mousemove", this._onMouseMove, false);
  6667. BABYLON.Tools.RegisterTopRootEvents([
  6668. { name: "keydown", handler: this._onKeyDown },
  6669. { name: "keyup", handler: this._onKeyUp },
  6670. { name: "blur", handler: this._onLostFocus }
  6671. ]);
  6672. };
  6673. FreeCamera.prototype.detachControl = function (element) {
  6674. if (this._attachedElement != element) {
  6675. return;
  6676. }
  6677. element.removeEventListener("mousedown", this._onMouseDown);
  6678. element.removeEventListener("mouseup", this._onMouseUp);
  6679. element.removeEventListener("mouseout", this._onMouseOut);
  6680. element.removeEventListener("mousemove", this._onMouseMove);
  6681. BABYLON.Tools.UnregisterTopRootEvents([
  6682. { name: "keydown", handler: this._onKeyDown },
  6683. { name: "keyup", handler: this._onKeyUp },
  6684. { name: "blur", handler: this._onLostFocus }
  6685. ]);
  6686. this._attachedElement = null;
  6687. if (this._reset) {
  6688. this._reset();
  6689. }
  6690. };
  6691. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6692. var globalPosition;
  6693. if (this.parent) {
  6694. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6695. }
  6696. else {
  6697. globalPosition = this.position;
  6698. }
  6699. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6700. this._collider.radius = this.ellipsoid;
  6701. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6702. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6703. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6704. this.position.addInPlace(this._diffPosition);
  6705. if (this.onCollide) {
  6706. this.onCollide(this._collider.collidedMesh);
  6707. }
  6708. }
  6709. };
  6710. FreeCamera.prototype._checkInputs = function () {
  6711. if (!this._localDirection) {
  6712. this._localDirection = BABYLON.Vector3.Zero();
  6713. this._transformedDirection = BABYLON.Vector3.Zero();
  6714. }
  6715. for (var index = 0; index < this._keys.length; index++) {
  6716. var keyCode = this._keys[index];
  6717. var speed = this._computeLocalCameraSpeed();
  6718. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6719. this._localDirection.copyFromFloats(-speed, 0, 0);
  6720. }
  6721. else if (this.keysUp.indexOf(keyCode) !== -1) {
  6722. this._localDirection.copyFromFloats(0, 0, speed);
  6723. }
  6724. else if (this.keysRight.indexOf(keyCode) !== -1) {
  6725. this._localDirection.copyFromFloats(speed, 0, 0);
  6726. }
  6727. else if (this.keysDown.indexOf(keyCode) !== -1) {
  6728. this._localDirection.copyFromFloats(0, 0, -speed);
  6729. }
  6730. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6731. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6732. this.cameraDirection.addInPlace(this._transformedDirection);
  6733. }
  6734. };
  6735. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6736. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6737. };
  6738. FreeCamera.prototype._updatePosition = function () {
  6739. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6740. this._collideWithWorld(this.cameraDirection);
  6741. if (this.applyGravity) {
  6742. var oldPosition = this.position;
  6743. this._collideWithWorld(this.getScene().gravity);
  6744. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6745. }
  6746. }
  6747. else {
  6748. this.position.addInPlace(this.cameraDirection);
  6749. }
  6750. };
  6751. FreeCamera.prototype._update = function () {
  6752. this._checkInputs();
  6753. _super.prototype._update.call(this);
  6754. };
  6755. return FreeCamera;
  6756. })(BABYLON.TargetCamera);
  6757. BABYLON.FreeCamera = FreeCamera;
  6758. })(BABYLON || (BABYLON = {}));
  6759. //# sourceMappingURL=babylon.freeCamera.js.map
  6760. var BABYLON;
  6761. (function (BABYLON) {
  6762. // We're mainly based on the logic defined into the FreeCamera code
  6763. var TouchCamera = (function (_super) {
  6764. __extends(TouchCamera, _super);
  6765. function TouchCamera(name, position, scene) {
  6766. _super.call(this, name, position, scene);
  6767. this._offsetX = null;
  6768. this._offsetY = null;
  6769. this._pointerCount = 0;
  6770. this._pointerPressed = [];
  6771. this.angularSensibility = 200000.0;
  6772. this.moveSensibility = 500.0;
  6773. }
  6774. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6775. var _this = this;
  6776. var previousPosition;
  6777. if (this._attachedCanvas) {
  6778. return;
  6779. }
  6780. this._attachedCanvas = canvas;
  6781. if (this._onPointerDown === undefined) {
  6782. this._onPointerDown = function (evt) {
  6783. if (!noPreventDefault) {
  6784. evt.preventDefault();
  6785. }
  6786. _this._pointerPressed.push(evt.pointerId);
  6787. if (_this._pointerPressed.length !== 1) {
  6788. return;
  6789. }
  6790. previousPosition = {
  6791. x: evt.clientX,
  6792. y: evt.clientY
  6793. };
  6794. };
  6795. this._onPointerUp = function (evt) {
  6796. if (!noPreventDefault) {
  6797. evt.preventDefault();
  6798. }
  6799. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6800. if (index === -1) {
  6801. return;
  6802. }
  6803. _this._pointerPressed.splice(index, 1);
  6804. if (index != 0) {
  6805. return;
  6806. }
  6807. previousPosition = null;
  6808. _this._offsetX = null;
  6809. _this._offsetY = null;
  6810. };
  6811. this._onPointerMove = function (evt) {
  6812. if (!noPreventDefault) {
  6813. evt.preventDefault();
  6814. }
  6815. if (!previousPosition) {
  6816. return;
  6817. }
  6818. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6819. if (index != 0) {
  6820. return;
  6821. }
  6822. _this._offsetX = evt.clientX - previousPosition.x;
  6823. _this._offsetY = -(evt.clientY - previousPosition.y);
  6824. };
  6825. this._onLostFocus = function () {
  6826. _this._offsetX = null;
  6827. _this._offsetY = null;
  6828. };
  6829. }
  6830. canvas.addEventListener("pointerdown", this._onPointerDown);
  6831. canvas.addEventListener("pointerup", this._onPointerUp);
  6832. canvas.addEventListener("pointerout", this._onPointerUp);
  6833. canvas.addEventListener("pointermove", this._onPointerMove);
  6834. BABYLON.Tools.RegisterTopRootEvents([
  6835. { name: "blur", handler: this._onLostFocus }
  6836. ]);
  6837. };
  6838. TouchCamera.prototype.detachControl = function (canvas) {
  6839. if (this._attachedCanvas != canvas) {
  6840. return;
  6841. }
  6842. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6843. canvas.removeEventListener("pointerup", this._onPointerUp);
  6844. canvas.removeEventListener("pointerout", this._onPointerUp);
  6845. canvas.removeEventListener("pointermove", this._onPointerMove);
  6846. BABYLON.Tools.UnregisterTopRootEvents([
  6847. { name: "blur", handler: this._onLostFocus }
  6848. ]);
  6849. this._attachedCanvas = null;
  6850. };
  6851. TouchCamera.prototype._checkInputs = function () {
  6852. if (!this._offsetX) {
  6853. return;
  6854. }
  6855. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6856. if (this._pointerPressed.length > 1) {
  6857. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6858. }
  6859. else {
  6860. var speed = this._computeLocalCameraSpeed();
  6861. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6862. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6863. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6864. }
  6865. };
  6866. return TouchCamera;
  6867. })(BABYLON.FreeCamera);
  6868. BABYLON.TouchCamera = TouchCamera;
  6869. })(BABYLON || (BABYLON = {}));
  6870. //# sourceMappingURL=babylon.touchCamera.js.map
  6871. var BABYLON;
  6872. (function (BABYLON) {
  6873. // We're mainly based on the logic defined into the FreeCamera code
  6874. var DeviceOrientationCamera = (function (_super) {
  6875. __extends(DeviceOrientationCamera, _super);
  6876. function DeviceOrientationCamera(name, position, scene) {
  6877. var _this = this;
  6878. _super.call(this, name, position, scene);
  6879. this._offsetX = null;
  6880. this._offsetY = null;
  6881. this._orientationGamma = 0;
  6882. this._orientationBeta = 0;
  6883. this._initialOrientationGamma = 0;
  6884. this._initialOrientationBeta = 0;
  6885. this.angularSensibility = 10000.0;
  6886. this.moveSensibility = 50.0;
  6887. window.addEventListener("resize", function () {
  6888. _this._initialOrientationGamma = null;
  6889. }, false);
  6890. }
  6891. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6892. var _this = this;
  6893. if (this._attachedCanvas) {
  6894. return;
  6895. }
  6896. this._attachedCanvas = canvas;
  6897. if (!this._orientationChanged) {
  6898. this._orientationChanged = function (evt) {
  6899. if (!_this._initialOrientationGamma) {
  6900. _this._initialOrientationGamma = evt.gamma;
  6901. _this._initialOrientationBeta = evt.beta;
  6902. }
  6903. _this._orientationGamma = evt.gamma;
  6904. _this._orientationBeta = evt.beta;
  6905. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6906. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6907. };
  6908. }
  6909. window.addEventListener("deviceorientation", this._orientationChanged);
  6910. };
  6911. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6912. if (this._attachedCanvas != canvas) {
  6913. return;
  6914. }
  6915. window.removeEventListener("deviceorientation", this._orientationChanged);
  6916. this._attachedCanvas = null;
  6917. this._orientationGamma = 0;
  6918. this._orientationBeta = 0;
  6919. this._initialOrientationGamma = 0;
  6920. this._initialOrientationBeta = 0;
  6921. };
  6922. DeviceOrientationCamera.prototype._checkInputs = function () {
  6923. if (!this._offsetX) {
  6924. return;
  6925. }
  6926. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6927. var speed = this._computeLocalCameraSpeed();
  6928. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6929. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6930. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6931. };
  6932. return DeviceOrientationCamera;
  6933. })(BABYLON.FreeCamera);
  6934. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6935. })(BABYLON || (BABYLON = {}));
  6936. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  6937. var BABYLON;
  6938. (function (BABYLON) {
  6939. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6940. var ArcRotateCamera = (function (_super) {
  6941. __extends(ArcRotateCamera, _super);
  6942. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6943. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6944. this.alpha = alpha;
  6945. this.beta = beta;
  6946. this.radius = radius;
  6947. this.target = target;
  6948. this.inertialAlphaOffset = 0;
  6949. this.inertialBetaOffset = 0;
  6950. this.inertialRadiusOffset = 0;
  6951. this.lowerAlphaLimit = null;
  6952. this.upperAlphaLimit = null;
  6953. this.lowerBetaLimit = 0.01;
  6954. this.upperBetaLimit = Math.PI;
  6955. this.lowerRadiusLimit = null;
  6956. this.upperRadiusLimit = null;
  6957. this.angularSensibility = 1000.0;
  6958. this.wheelPrecision = 3.0;
  6959. this.keysUp = [38];
  6960. this.keysDown = [40];
  6961. this.keysLeft = [37];
  6962. this.keysRight = [39];
  6963. this.zoomOnFactor = 1;
  6964. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6965. this._keys = [];
  6966. this._viewMatrix = new BABYLON.Matrix();
  6967. this.checkCollisions = false;
  6968. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6969. this._collider = new BABYLON.Collider();
  6970. this._previousPosition = BABYLON.Vector3.Zero();
  6971. this._collisionVelocity = BABYLON.Vector3.Zero();
  6972. this._newPosition = BABYLON.Vector3.Zero();
  6973. // Pinch
  6974. // value for pinch step scaling
  6975. // set to 20 by default
  6976. this.pinchPrecision = 20;
  6977. this.getViewMatrix();
  6978. }
  6979. ArcRotateCamera.prototype._getTargetPosition = function () {
  6980. return this.target.position || this.target;
  6981. };
  6982. // Cache
  6983. ArcRotateCamera.prototype._initCache = function () {
  6984. _super.prototype._initCache.call(this);
  6985. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6986. this._cache.alpha = undefined;
  6987. this._cache.beta = undefined;
  6988. this._cache.radius = undefined;
  6989. this._cache.targetScreenOffset = undefined;
  6990. };
  6991. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6992. if (!ignoreParentClass) {
  6993. _super.prototype._updateCache.call(this);
  6994. }
  6995. this._cache.target.copyFrom(this._getTargetPosition());
  6996. this._cache.alpha = this.alpha;
  6997. this._cache.beta = this.beta;
  6998. this._cache.radius = this.radius;
  6999. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7000. };
  7001. // Synchronized
  7002. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7003. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7004. return false;
  7005. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  7006. };
  7007. // Methods
  7008. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7009. var _this = this;
  7010. var previousPosition;
  7011. var pointerId;
  7012. // to know if pinch started
  7013. var pinchStarted = false;
  7014. // two pinch point on X
  7015. // that will use for find if user action is pinch open or pinch close
  7016. var pinchPointX1, pinchPointX2;
  7017. if (this._attachedElement) {
  7018. return;
  7019. }
  7020. this._attachedElement = element;
  7021. var engine = this.getEngine();
  7022. if (this._onPointerDown === undefined) {
  7023. this._onPointerDown = function (evt) {
  7024. if (pointerId) {
  7025. return;
  7026. }
  7027. pointerId = evt.pointerId;
  7028. previousPosition = {
  7029. x: evt.clientX,
  7030. y: evt.clientY
  7031. };
  7032. if (!noPreventDefault) {
  7033. evt.preventDefault();
  7034. }
  7035. };
  7036. this._onPointerUp = function (evt) {
  7037. previousPosition = null;
  7038. pointerId = null;
  7039. if (!noPreventDefault) {
  7040. evt.preventDefault();
  7041. }
  7042. };
  7043. this._onPointerMove = function (evt) {
  7044. if (!previousPosition) {
  7045. return;
  7046. }
  7047. if (pointerId !== evt.pointerId) {
  7048. return;
  7049. }
  7050. // return pinch is started
  7051. if (pinchStarted) {
  7052. return;
  7053. }
  7054. var offsetX = evt.clientX - previousPosition.x;
  7055. var offsetY = evt.clientY - previousPosition.y;
  7056. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7057. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7058. previousPosition = {
  7059. x: evt.clientX,
  7060. y: evt.clientY
  7061. };
  7062. if (!noPreventDefault) {
  7063. evt.preventDefault();
  7064. }
  7065. };
  7066. this._onMouseMove = function (evt) {
  7067. if (!engine.isPointerLock) {
  7068. return;
  7069. }
  7070. // return pinch is started
  7071. if (pinchStarted) {
  7072. return;
  7073. }
  7074. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7075. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7076. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7077. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7078. if (!noPreventDefault) {
  7079. evt.preventDefault();
  7080. }
  7081. };
  7082. this._wheel = function (event) {
  7083. var delta = 0;
  7084. if (event.wheelDelta) {
  7085. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7086. }
  7087. else if (event.detail) {
  7088. delta = -event.detail / _this.wheelPrecision;
  7089. }
  7090. if (delta)
  7091. _this.inertialRadiusOffset += delta;
  7092. if (event.preventDefault) {
  7093. if (!noPreventDefault) {
  7094. event.preventDefault();
  7095. }
  7096. }
  7097. };
  7098. this._onKeyDown = function (evt) {
  7099. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  7100. var index = _this._keys.indexOf(evt.keyCode);
  7101. if (index === -1) {
  7102. _this._keys.push(evt.keyCode);
  7103. }
  7104. if (evt.preventDefault) {
  7105. if (!noPreventDefault) {
  7106. evt.preventDefault();
  7107. }
  7108. }
  7109. }
  7110. };
  7111. this._onKeyUp = function (evt) {
  7112. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  7113. var index = _this._keys.indexOf(evt.keyCode);
  7114. if (index >= 0) {
  7115. _this._keys.splice(index, 1);
  7116. }
  7117. if (evt.preventDefault) {
  7118. if (!noPreventDefault) {
  7119. evt.preventDefault();
  7120. }
  7121. }
  7122. }
  7123. };
  7124. this._onLostFocus = function () {
  7125. _this._keys = [];
  7126. pointerId = null;
  7127. };
  7128. this._onGestureStart = function (e) {
  7129. if (window.MSGesture === undefined) {
  7130. return;
  7131. }
  7132. if (!_this._MSGestureHandler) {
  7133. _this._MSGestureHandler = new MSGesture();
  7134. _this._MSGestureHandler.target = element;
  7135. }
  7136. _this._MSGestureHandler.addPointer(e.pointerId);
  7137. };
  7138. this._onGesture = function (e) {
  7139. _this.radius *= e.scale;
  7140. if (e.preventDefault) {
  7141. if (!noPreventDefault) {
  7142. e.stopPropagation();
  7143. e.preventDefault();
  7144. }
  7145. }
  7146. };
  7147. this._reset = function () {
  7148. _this._keys = [];
  7149. _this.inertialAlphaOffset = 0;
  7150. _this.inertialBetaOffset = 0;
  7151. _this.inertialRadiusOffset = 0;
  7152. previousPosition = null;
  7153. pointerId = null;
  7154. };
  7155. this._touchStart = function (event) {
  7156. if (event.touches.length === 2) {
  7157. //-- start pinch if two fingers on the screen
  7158. pinchStarted = true;
  7159. _this._pinchStart(event);
  7160. }
  7161. };
  7162. this._touchMove = function (event) {
  7163. if (pinchStarted) {
  7164. //-- make scaling
  7165. _this._pinchMove(event);
  7166. }
  7167. };
  7168. this._touchEnd = function (event) {
  7169. if (pinchStarted) {
  7170. //-- end of pinch
  7171. _this._pinchEnd(event);
  7172. }
  7173. };
  7174. this._pinchStart = function (event) {
  7175. // save origin touch point
  7176. pinchPointX1 = event.touches[0].clientX;
  7177. pinchPointX2 = event.touches[1].clientX;
  7178. // block the camera
  7179. // if not it rotate around target during pinch
  7180. pinchStarted = true;
  7181. };
  7182. this._pinchMove = function (event) {
  7183. // variable for new camera's radius
  7184. var delta = 0;
  7185. // variables to know if pinch open or pinch close
  7186. var direction = 1;
  7187. var distanceXOrigine, distanceXNow;
  7188. if (event.touches.length !== 2)
  7189. return;
  7190. // calculate absolute distances of the two fingers
  7191. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7192. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7193. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7194. if (distanceXNow < distanceXOrigine) {
  7195. direction = -1;
  7196. }
  7197. // calculate new radius
  7198. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7199. // set new radius
  7200. _this.inertialRadiusOffset -= delta;
  7201. // save origin touch point
  7202. pinchPointX1 = event.touches[0].clientX;
  7203. pinchPointX2 = event.touches[1].clientX;
  7204. };
  7205. this._pinchEnd = function (event) {
  7206. // cancel pinch and deblock camera rotation
  7207. pinchStarted = false;
  7208. };
  7209. }
  7210. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7211. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7212. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7213. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7214. element.addEventListener("mousemove", this._onMouseMove, false);
  7215. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7216. element.addEventListener("MSGestureChange", this._onGesture, false);
  7217. element.addEventListener('mousewheel', this._wheel, false);
  7218. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7219. // pinch
  7220. element.addEventListener('touchstart', this._touchStart, false);
  7221. element.addEventListener('touchmove', this._touchMove, false);
  7222. element.addEventListener('touchend', this._touchEnd, false);
  7223. BABYLON.Tools.RegisterTopRootEvents([
  7224. { name: "keydown", handler: this._onKeyDown },
  7225. { name: "keyup", handler: this._onKeyUp },
  7226. { name: "blur", handler: this._onLostFocus }
  7227. ]);
  7228. };
  7229. ArcRotateCamera.prototype.detachControl = function (element) {
  7230. if (this._attachedElement != element) {
  7231. return;
  7232. }
  7233. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7234. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7235. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7236. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7237. element.removeEventListener("mousemove", this._onMouseMove);
  7238. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7239. element.removeEventListener("MSGestureChange", this._onGesture);
  7240. element.removeEventListener('mousewheel', this._wheel);
  7241. element.removeEventListener('DOMMouseScroll', this._wheel);
  7242. // pinch
  7243. element.removeEventListener('touchstart', this._touchStart);
  7244. element.removeEventListener('touchmove', this._touchMove);
  7245. element.removeEventListener('touchend', this._touchEnd);
  7246. BABYLON.Tools.UnregisterTopRootEvents([
  7247. { name: "keydown", handler: this._onKeyDown },
  7248. { name: "keyup", handler: this._onKeyUp },
  7249. { name: "blur", handler: this._onLostFocus }
  7250. ]);
  7251. this._MSGestureHandler = null;
  7252. this._attachedElement = null;
  7253. if (this._reset) {
  7254. this._reset();
  7255. }
  7256. };
  7257. ArcRotateCamera.prototype._update = function () {
  7258. for (var index = 0; index < this._keys.length; index++) {
  7259. var keyCode = this._keys[index];
  7260. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7261. this.inertialAlphaOffset -= 0.01;
  7262. }
  7263. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7264. this.inertialBetaOffset -= 0.01;
  7265. }
  7266. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7267. this.inertialAlphaOffset += 0.01;
  7268. }
  7269. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7270. this.inertialBetaOffset += 0.01;
  7271. }
  7272. }
  7273. // Inertia
  7274. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7275. this.alpha += this.inertialAlphaOffset;
  7276. this.beta += this.inertialBetaOffset;
  7277. this.radius -= this.inertialRadiusOffset;
  7278. this.inertialAlphaOffset *= this.inertia;
  7279. this.inertialBetaOffset *= this.inertia;
  7280. this.inertialRadiusOffset *= this.inertia;
  7281. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7282. this.inertialAlphaOffset = 0;
  7283. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7284. this.inertialBetaOffset = 0;
  7285. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7286. this.inertialRadiusOffset = 0;
  7287. }
  7288. // Limits
  7289. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7290. this.alpha = this.lowerAlphaLimit;
  7291. }
  7292. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7293. this.alpha = this.upperAlphaLimit;
  7294. }
  7295. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7296. this.beta = this.lowerBetaLimit;
  7297. }
  7298. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7299. this.beta = this.upperBetaLimit;
  7300. }
  7301. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7302. this.radius = this.lowerRadiusLimit;
  7303. }
  7304. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7305. this.radius = this.upperRadiusLimit;
  7306. }
  7307. };
  7308. ArcRotateCamera.prototype.setPosition = function (position) {
  7309. var radiusv3 = position.subtract(this._getTargetPosition());
  7310. this.radius = radiusv3.length();
  7311. // Alpha
  7312. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7313. if (radiusv3.z < 0) {
  7314. this.alpha = 2 * Math.PI - this.alpha;
  7315. }
  7316. // Beta
  7317. this.beta = Math.acos(radiusv3.y / this.radius);
  7318. };
  7319. ArcRotateCamera.prototype._getViewMatrix = function () {
  7320. // Compute
  7321. var cosa = Math.cos(this.alpha);
  7322. var sina = Math.sin(this.alpha);
  7323. var cosb = Math.cos(this.beta);
  7324. var sinb = Math.sin(this.beta);
  7325. var target = this._getTargetPosition();
  7326. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7327. if (this.checkCollisions) {
  7328. this._collider.radius = this.collisionRadius;
  7329. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7330. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7331. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7332. this.position.copyFrom(this._previousPosition);
  7333. this.alpha = this._previousAlpha;
  7334. this.beta = this._previousBeta;
  7335. this.radius = this._previousRadius;
  7336. if (this.onCollide) {
  7337. this.onCollide(this._collider.collidedMesh);
  7338. }
  7339. }
  7340. }
  7341. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7342. this._previousAlpha = this.alpha;
  7343. this._previousBeta = this.beta;
  7344. this._previousRadius = this.radius;
  7345. this._previousPosition.copyFrom(this.position);
  7346. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7347. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7348. return this._viewMatrix;
  7349. };
  7350. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7351. meshes = meshes || this.getScene().meshes;
  7352. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7353. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7354. this.radius = distance * this.zoomOnFactor;
  7355. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7356. };
  7357. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7358. var meshesOrMinMaxVector;
  7359. var distance;
  7360. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7361. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7362. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7363. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7364. }
  7365. else {
  7366. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7367. distance = meshesOrMinMaxVectorAndDistance.distance;
  7368. }
  7369. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7370. this.maxZ = distance * 2;
  7371. };
  7372. return ArcRotateCamera;
  7373. })(BABYLON.Camera);
  7374. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7375. })(BABYLON || (BABYLON = {}));
  7376. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7377. (function (BABYLON) {
  7378. /**
  7379. * Represents a scene to be rendered by the engine.
  7380. * @see http://doc.babylonjs.com/page.php?p=21911
  7381. */
  7382. var Scene = (function () {
  7383. /**
  7384. * @constructor
  7385. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7386. */
  7387. function Scene(engine) {
  7388. // Members
  7389. this.autoClear = true;
  7390. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7391. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7392. this.forceWireframe = false;
  7393. this.forcePointsCloud = false;
  7394. this.forceShowBoundingBoxes = false;
  7395. this.animationsEnabled = true;
  7396. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  7397. // Fog
  7398. /**
  7399. * is fog enabled on this scene.
  7400. * @type {boolean}
  7401. */
  7402. this.fogEnabled = true;
  7403. this.fogMode = Scene.FOGMODE_NONE;
  7404. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7405. this.fogDensity = 0.1;
  7406. this.fogStart = 0;
  7407. this.fogEnd = 1000.0;
  7408. // Lights
  7409. /**
  7410. * is shadow enabled on this scene.
  7411. * @type {boolean}
  7412. */
  7413. this.shadowsEnabled = true;
  7414. /**
  7415. * is light enabled on this scene.
  7416. * @type {boolean}
  7417. */
  7418. this.lightsEnabled = true;
  7419. /**
  7420. * All of the lights added to this scene.
  7421. * @see BABYLON.Light
  7422. * @type {BABYLON.Light[]}
  7423. */
  7424. this.lights = new Array();
  7425. // Cameras
  7426. /**
  7427. * All of the cameras added to this scene.
  7428. * @see BABYLON.Camera
  7429. * @type {BABYLON.Camera[]}
  7430. */
  7431. this.cameras = new Array();
  7432. this.activeCameras = new Array();
  7433. // Meshes
  7434. /**
  7435. * All of the (abstract) meshes added to this scene.
  7436. * @see BABYLON.AbstractMesh
  7437. * @type {BABYLON.AbstractMesh[]}
  7438. */
  7439. this.meshes = new Array();
  7440. // Geometries
  7441. this._geometries = new Array();
  7442. this.materials = new Array();
  7443. this.multiMaterials = new Array();
  7444. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7445. // Textures
  7446. this.texturesEnabled = true;
  7447. this.textures = new Array();
  7448. // Particles
  7449. this.particlesEnabled = true;
  7450. this.particleSystems = new Array();
  7451. // Sprites
  7452. this.spriteManagers = new Array();
  7453. // Layers
  7454. this.layers = new Array();
  7455. // Skeletons
  7456. this.skeletonsEnabled = true;
  7457. this.skeletons = new Array();
  7458. // Lens flares
  7459. this.lensFlaresEnabled = true;
  7460. this.lensFlareSystems = new Array();
  7461. // Collisions
  7462. this.collisionsEnabled = true;
  7463. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7464. // Postprocesses
  7465. this.postProcessesEnabled = true;
  7466. // Customs render targets
  7467. this.renderTargetsEnabled = true;
  7468. this.customRenderTargets = new Array();
  7469. // Imported meshes
  7470. this.importedMeshesFiles = new Array();
  7471. this._actionManagers = new Array();
  7472. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7473. // Procedural textures
  7474. this.proceduralTexturesEnabled = true;
  7475. this._proceduralTextures = new Array();
  7476. this.soundTracks = new Array();
  7477. this._totalVertices = 0;
  7478. this._activeVertices = 0;
  7479. this._activeParticles = 0;
  7480. this._lastFrameDuration = 0;
  7481. this._evaluateActiveMeshesDuration = 0;
  7482. this._renderTargetsDuration = 0;
  7483. this._particlesDuration = 0;
  7484. this._renderDuration = 0;
  7485. this._spritesDuration = 0;
  7486. this._animationRatio = 0;
  7487. this._renderId = 0;
  7488. this._executeWhenReadyTimeoutId = -1;
  7489. this._toBeDisposed = new BABYLON.SmartArray(256);
  7490. this._onReadyCallbacks = new Array();
  7491. this._pendingData = []; //ANY
  7492. this._onBeforeRenderCallbacks = new Array();
  7493. this._onAfterRenderCallbacks = new Array();
  7494. this._activeMeshes = new BABYLON.SmartArray(256);
  7495. this._processedMaterials = new BABYLON.SmartArray(256);
  7496. this._renderTargets = new BABYLON.SmartArray(256);
  7497. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7498. this._activeSkeletons = new BABYLON.SmartArray(32);
  7499. this._activeBones = 0;
  7500. this._activeAnimatables = new Array();
  7501. this._transformMatrix = BABYLON.Matrix.Zero();
  7502. this._scaledPosition = BABYLON.Vector3.Zero();
  7503. this._scaledVelocity = BABYLON.Vector3.Zero();
  7504. this._engine = engine;
  7505. engine.scenes.push(this);
  7506. this._renderingManager = new BABYLON.RenderingManager(this);
  7507. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7508. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7509. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7510. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7511. this.attachControl();
  7512. this._debugLayer = new BABYLON.DebugLayer(this);
  7513. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7514. }
  7515. Object.defineProperty(Scene.prototype, "debugLayer", {
  7516. // Properties
  7517. get: function () {
  7518. return this._debugLayer;
  7519. },
  7520. enumerable: true,
  7521. configurable: true
  7522. });
  7523. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7524. /**
  7525. * The mesh that is currently under the pointer.
  7526. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  7527. */
  7528. get: function () {
  7529. return this._meshUnderPointer;
  7530. },
  7531. enumerable: true,
  7532. configurable: true
  7533. });
  7534. Object.defineProperty(Scene.prototype, "pointerX", {
  7535. /**
  7536. * Current on-screen X position of the pointer
  7537. * @return {number} X position of the pointer
  7538. */
  7539. get: function () {
  7540. return this._pointerX;
  7541. },
  7542. enumerable: true,
  7543. configurable: true
  7544. });
  7545. Object.defineProperty(Scene.prototype, "pointerY", {
  7546. /**
  7547. * Current on-screen Y position of the pointer
  7548. * @return {number} Y position of the pointer
  7549. */
  7550. get: function () {
  7551. return this._pointerY;
  7552. },
  7553. enumerable: true,
  7554. configurable: true
  7555. });
  7556. Scene.prototype.getCachedMaterial = function () {
  7557. return this._cachedMaterial;
  7558. };
  7559. Scene.prototype.getBoundingBoxRenderer = function () {
  7560. return this._boundingBoxRenderer;
  7561. };
  7562. Scene.prototype.getOutlineRenderer = function () {
  7563. return this._outlineRenderer;
  7564. };
  7565. Scene.prototype.getEngine = function () {
  7566. return this._engine;
  7567. };
  7568. Scene.prototype.getTotalVertices = function () {
  7569. return this._totalVertices;
  7570. };
  7571. Scene.prototype.getActiveVertices = function () {
  7572. return this._activeVertices;
  7573. };
  7574. Scene.prototype.getActiveParticles = function () {
  7575. return this._activeParticles;
  7576. };
  7577. Scene.prototype.getActiveBones = function () {
  7578. return this._activeBones;
  7579. };
  7580. // Stats
  7581. Scene.prototype.getLastFrameDuration = function () {
  7582. return this._lastFrameDuration;
  7583. };
  7584. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7585. return this._evaluateActiveMeshesDuration;
  7586. };
  7587. Scene.prototype.getActiveMeshes = function () {
  7588. return this._activeMeshes;
  7589. };
  7590. Scene.prototype.getRenderTargetsDuration = function () {
  7591. return this._renderTargetsDuration;
  7592. };
  7593. Scene.prototype.getRenderDuration = function () {
  7594. return this._renderDuration;
  7595. };
  7596. Scene.prototype.getParticlesDuration = function () {
  7597. return this._particlesDuration;
  7598. };
  7599. Scene.prototype.getSpritesDuration = function () {
  7600. return this._spritesDuration;
  7601. };
  7602. Scene.prototype.getAnimationRatio = function () {
  7603. return this._animationRatio;
  7604. };
  7605. Scene.prototype.getRenderId = function () {
  7606. return this._renderId;
  7607. };
  7608. Scene.prototype._updatePointerPosition = function (evt) {
  7609. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7610. this._pointerX = evt.clientX - canvasRect.left;
  7611. this._pointerY = evt.clientY - canvasRect.top;
  7612. if (this.cameraToUseForPointers) {
  7613. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7614. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7615. }
  7616. };
  7617. // Pointers handling
  7618. Scene.prototype.attachControl = function () {
  7619. var _this = this;
  7620. this._onPointerMove = function (evt) {
  7621. var canvas = _this._engine.getRenderingCanvas();
  7622. _this._updatePointerPosition(evt);
  7623. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers; }, false, _this.cameraToUseForPointers);
  7624. if (pickResult.hit) {
  7625. _this._meshUnderPointer = pickResult.pickedMesh;
  7626. _this.setPointerOverMesh(pickResult.pickedMesh);
  7627. canvas.style.cursor = "pointer";
  7628. }
  7629. else {
  7630. _this.setPointerOverMesh(null);
  7631. canvas.style.cursor = "";
  7632. _this._meshUnderPointer = null;
  7633. }
  7634. };
  7635. this._onPointerDown = function (evt) {
  7636. var predicate = null;
  7637. if (!_this.onPointerDown) {
  7638. predicate = function (mesh) {
  7639. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7640. };
  7641. }
  7642. _this._updatePointerPosition(evt);
  7643. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7644. if (pickResult.hit) {
  7645. if (pickResult.pickedMesh.actionManager) {
  7646. switch (evt.button) {
  7647. case 0:
  7648. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7649. break;
  7650. case 1:
  7651. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7652. break;
  7653. case 2:
  7654. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7655. break;
  7656. }
  7657. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7658. }
  7659. }
  7660. if (_this.onPointerDown) {
  7661. _this.onPointerDown(evt, pickResult);
  7662. }
  7663. };
  7664. this._onKeyDown = function (evt) {
  7665. if (_this.actionManager) {
  7666. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7667. }
  7668. };
  7669. this._onKeyUp = function (evt) {
  7670. if (_this.actionManager) {
  7671. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7672. }
  7673. };
  7674. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7675. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7676. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7677. window.addEventListener("keydown", this._onKeyDown, false);
  7678. window.addEventListener("keyup", this._onKeyUp, false);
  7679. };
  7680. Scene.prototype.detachControl = function () {
  7681. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7682. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7683. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7684. window.removeEventListener("keydown", this._onKeyDown);
  7685. window.removeEventListener("keyup", this._onKeyUp);
  7686. };
  7687. // Ready
  7688. Scene.prototype.isReady = function () {
  7689. if (this._pendingData.length > 0) {
  7690. return false;
  7691. }
  7692. for (var index = 0; index < this._geometries.length; index++) {
  7693. var geometry = this._geometries[index];
  7694. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7695. return false;
  7696. }
  7697. }
  7698. for (index = 0; index < this.meshes.length; index++) {
  7699. var mesh = this.meshes[index];
  7700. if (!mesh.isReady()) {
  7701. return false;
  7702. }
  7703. var mat = mesh.material;
  7704. if (mat) {
  7705. if (!mat.isReady(mesh)) {
  7706. return false;
  7707. }
  7708. }
  7709. }
  7710. return true;
  7711. };
  7712. Scene.prototype.resetCachedMaterial = function () {
  7713. this._cachedMaterial = null;
  7714. };
  7715. Scene.prototype.registerBeforeRender = function (func) {
  7716. this._onBeforeRenderCallbacks.push(func);
  7717. };
  7718. Scene.prototype.unregisterBeforeRender = function (func) {
  7719. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7720. if (index > -1) {
  7721. this._onBeforeRenderCallbacks.splice(index, 1);
  7722. }
  7723. };
  7724. Scene.prototype.registerAfterRender = function (func) {
  7725. this._onAfterRenderCallbacks.push(func);
  7726. };
  7727. Scene.prototype.unregisterAfterRender = function (func) {
  7728. var index = this._onAfterRenderCallbacks.indexOf(func);
  7729. if (index > -1) {
  7730. this._onAfterRenderCallbacks.splice(index, 1);
  7731. }
  7732. };
  7733. Scene.prototype._addPendingData = function (data) {
  7734. this._pendingData.push(data);
  7735. };
  7736. Scene.prototype._removePendingData = function (data) {
  7737. var index = this._pendingData.indexOf(data);
  7738. if (index !== -1) {
  7739. this._pendingData.splice(index, 1);
  7740. }
  7741. };
  7742. Scene.prototype.getWaitingItemsCount = function () {
  7743. return this._pendingData.length;
  7744. };
  7745. /**
  7746. * Registers a function to be executed when the scene is ready.
  7747. * @param {Function} func - the function to be executed.
  7748. */
  7749. Scene.prototype.executeWhenReady = function (func) {
  7750. var _this = this;
  7751. this._onReadyCallbacks.push(func);
  7752. if (this._executeWhenReadyTimeoutId !== -1) {
  7753. return;
  7754. }
  7755. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7756. _this._checkIsReady();
  7757. }, 150);
  7758. };
  7759. Scene.prototype._checkIsReady = function () {
  7760. var _this = this;
  7761. if (this.isReady()) {
  7762. this._onReadyCallbacks.forEach(function (func) {
  7763. func();
  7764. });
  7765. this._onReadyCallbacks = [];
  7766. this._executeWhenReadyTimeoutId = -1;
  7767. return;
  7768. }
  7769. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7770. _this._checkIsReady();
  7771. }, 150);
  7772. };
  7773. // Animations
  7774. /**
  7775. * Will start the animation sequence of a given target
  7776. * @param target - the target
  7777. * @param {number} from - from which frame should animation start
  7778. * @param {number} to - till which frame should animation run.
  7779. * @param {boolean} [loop] - should the animation loop
  7780. * @param {number} [speedRatio] - the speed in which to run the animation
  7781. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  7782. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  7783. * @return {BABYLON.Animatable} the animatable object created for this animation
  7784. * @see BABYLON.Animatable
  7785. * @see http://doc.babylonjs.com/page.php?p=22081
  7786. */
  7787. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7788. if (speedRatio === undefined) {
  7789. speedRatio = 1.0;
  7790. }
  7791. this.stopAnimation(target);
  7792. if (!animatable) {
  7793. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7794. }
  7795. // Local animations
  7796. if (target.animations) {
  7797. animatable.appendAnimations(target, target.animations);
  7798. }
  7799. // Children animations
  7800. if (target.getAnimatables) {
  7801. var animatables = target.getAnimatables();
  7802. for (var index = 0; index < animatables.length; index++) {
  7803. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7804. }
  7805. }
  7806. return animatable;
  7807. };
  7808. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7809. if (speedRatio === undefined) {
  7810. speedRatio = 1.0;
  7811. }
  7812. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7813. return animatable;
  7814. };
  7815. Scene.prototype.getAnimatableByTarget = function (target) {
  7816. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7817. if (this._activeAnimatables[index].target === target) {
  7818. return this._activeAnimatables[index];
  7819. }
  7820. }
  7821. return null;
  7822. };
  7823. /**
  7824. * Will stop the animation of the given target
  7825. * @param target - the target
  7826. * @see beginAnimation
  7827. */
  7828. Scene.prototype.stopAnimation = function (target) {
  7829. var animatable = this.getAnimatableByTarget(target);
  7830. if (animatable) {
  7831. animatable.stop();
  7832. }
  7833. };
  7834. Scene.prototype._animate = function () {
  7835. if (!this.animationsEnabled) {
  7836. return;
  7837. }
  7838. if (!this._animationStartDate) {
  7839. this._animationStartDate = BABYLON.Tools.Now;
  7840. }
  7841. // Getting time
  7842. var now = BABYLON.Tools.Now;
  7843. var delay = now - this._animationStartDate;
  7844. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7845. if (!this._activeAnimatables[index]._animate(delay)) {
  7846. this._activeAnimatables.splice(index, 1);
  7847. index--;
  7848. }
  7849. }
  7850. };
  7851. // Matrix
  7852. Scene.prototype.getViewMatrix = function () {
  7853. return this._viewMatrix;
  7854. };
  7855. Scene.prototype.getProjectionMatrix = function () {
  7856. return this._projectionMatrix;
  7857. };
  7858. Scene.prototype.getTransformMatrix = function () {
  7859. return this._transformMatrix;
  7860. };
  7861. Scene.prototype.setTransformMatrix = function (view, projection) {
  7862. this._viewMatrix = view;
  7863. this._projectionMatrix = projection;
  7864. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  7865. };
  7866. // Methods
  7867. /**
  7868. * sets the active camera of the scene using its ID
  7869. * @param {string} id - the camera's ID
  7870. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  7871. * @see activeCamera
  7872. */
  7873. Scene.prototype.setActiveCameraByID = function (id) {
  7874. var camera = this.getCameraByID(id);
  7875. if (camera) {
  7876. this.activeCamera = camera;
  7877. return camera;
  7878. }
  7879. return null;
  7880. };
  7881. /**
  7882. * sets the active camera of the scene using its name
  7883. * @param {string} name - the camera's name
  7884. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  7885. * @see activeCamera
  7886. */
  7887. Scene.prototype.setActiveCameraByName = function (name) {
  7888. var camera = this.getCameraByName(name);
  7889. if (camera) {
  7890. this.activeCamera = camera;
  7891. return camera;
  7892. }
  7893. return null;
  7894. };
  7895. /**
  7896. * get a material using its id
  7897. * @param {string} the material's ID
  7898. * @return {BABYLON.Material|null} the material or null if none found.
  7899. */
  7900. Scene.prototype.getMaterialByID = function (id) {
  7901. for (var index = 0; index < this.materials.length; index++) {
  7902. if (this.materials[index].id === id) {
  7903. return this.materials[index];
  7904. }
  7905. }
  7906. return null;
  7907. };
  7908. /**
  7909. * get a material using its name
  7910. * @param {string} the material's name
  7911. * @return {BABYLON.Material|null} the material or null if none found.
  7912. */
  7913. Scene.prototype.getMaterialByName = function (name) {
  7914. for (var index = 0; index < this.materials.length; index++) {
  7915. if (this.materials[index].name === name) {
  7916. return this.materials[index];
  7917. }
  7918. }
  7919. return null;
  7920. };
  7921. Scene.prototype.getCameraByID = function (id) {
  7922. for (var index = 0; index < this.cameras.length; index++) {
  7923. if (this.cameras[index].id === id) {
  7924. return this.cameras[index];
  7925. }
  7926. }
  7927. return null;
  7928. };
  7929. /**
  7930. * get a camera using its name
  7931. * @param {string} the camera's name
  7932. * @return {BABYLON.Camera|null} the camera or null if none found.
  7933. */
  7934. Scene.prototype.getCameraByName = function (name) {
  7935. for (var index = 0; index < this.cameras.length; index++) {
  7936. if (this.cameras[index].name === name) {
  7937. return this.cameras[index];
  7938. }
  7939. }
  7940. return null;
  7941. };
  7942. /**
  7943. * get a light node using its name
  7944. * @param {string} the light's name
  7945. * @return {BABYLON.Light|null} the light or null if none found.
  7946. */
  7947. Scene.prototype.getLightByName = function (name) {
  7948. for (var index = 0; index < this.lights.length; index++) {
  7949. if (this.lights[index].name === name) {
  7950. return this.lights[index];
  7951. }
  7952. }
  7953. return null;
  7954. };
  7955. /**
  7956. * get a light node using its ID
  7957. * @param {string} the light's id
  7958. * @return {BABYLON.Light|null} the light or null if none found.
  7959. */
  7960. Scene.prototype.getLightByID = function (id) {
  7961. for (var index = 0; index < this.lights.length; index++) {
  7962. if (this.lights[index].id === id) {
  7963. return this.lights[index];
  7964. }
  7965. }
  7966. return null;
  7967. };
  7968. /**
  7969. * get a geometry using its ID
  7970. * @param {string} the geometry's id
  7971. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  7972. */
  7973. Scene.prototype.getGeometryByID = function (id) {
  7974. for (var index = 0; index < this._geometries.length; index++) {
  7975. if (this._geometries[index].id === id) {
  7976. return this._geometries[index];
  7977. }
  7978. }
  7979. return null;
  7980. };
  7981. /**
  7982. * add a new geometry to this scene.
  7983. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  7984. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  7985. * @return {boolean} was the geometry added or not
  7986. */
  7987. Scene.prototype.pushGeometry = function (geometry, force) {
  7988. if (!force && this.getGeometryByID(geometry.id)) {
  7989. return false;
  7990. }
  7991. this._geometries.push(geometry);
  7992. return true;
  7993. };
  7994. Scene.prototype.getGeometries = function () {
  7995. return this._geometries;
  7996. };
  7997. /**
  7998. * Get a the first added mesh found of a given ID
  7999. * @param {string} id - the id to search for
  8000. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8001. */
  8002. Scene.prototype.getMeshByID = function (id) {
  8003. for (var index = 0; index < this.meshes.length; index++) {
  8004. if (this.meshes[index].id === id) {
  8005. return this.meshes[index];
  8006. }
  8007. }
  8008. return null;
  8009. };
  8010. /**
  8011. * Get a the last added mesh found of a given ID
  8012. * @param {string} id - the id to search for
  8013. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8014. */
  8015. Scene.prototype.getLastMeshByID = function (id) {
  8016. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8017. if (this.meshes[index].id === id) {
  8018. return this.meshes[index];
  8019. }
  8020. }
  8021. return null;
  8022. };
  8023. /**
  8024. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8025. * @param {string} id - the id to search for
  8026. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8027. */
  8028. Scene.prototype.getLastEntryByID = function (id) {
  8029. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8030. if (this.meshes[index].id === id) {
  8031. return this.meshes[index];
  8032. }
  8033. }
  8034. for (index = this.cameras.length - 1; index >= 0; index--) {
  8035. if (this.cameras[index].id === id) {
  8036. return this.cameras[index];
  8037. }
  8038. }
  8039. for (index = this.lights.length - 1; index >= 0; index--) {
  8040. if (this.lights[index].id === id) {
  8041. return this.lights[index];
  8042. }
  8043. }
  8044. return null;
  8045. };
  8046. Scene.prototype.getNodeByName = function (name) {
  8047. var mesh = this.getMeshByName(name);
  8048. if (mesh) {
  8049. return mesh;
  8050. }
  8051. var light = this.getLightByName(name);
  8052. if (light) {
  8053. return light;
  8054. }
  8055. return this.getCameraByName(name);
  8056. };
  8057. Scene.prototype.getMeshByName = function (name) {
  8058. for (var index = 0; index < this.meshes.length; index++) {
  8059. if (this.meshes[index].name === name) {
  8060. return this.meshes[index];
  8061. }
  8062. }
  8063. return null;
  8064. };
  8065. Scene.prototype.getSoundByName = function (name) {
  8066. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8067. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8068. return this.mainSoundTrack.soundCollection[index];
  8069. }
  8070. }
  8071. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8072. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8073. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8074. return this.soundTracks[sdIndex].soundCollection[index];
  8075. }
  8076. }
  8077. }
  8078. return null;
  8079. };
  8080. Scene.prototype.getLastSkeletonByID = function (id) {
  8081. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8082. if (this.skeletons[index].id === id) {
  8083. return this.skeletons[index];
  8084. }
  8085. }
  8086. return null;
  8087. };
  8088. Scene.prototype.getSkeletonById = function (id) {
  8089. for (var index = 0; index < this.skeletons.length; index++) {
  8090. if (this.skeletons[index].id === id) {
  8091. return this.skeletons[index];
  8092. }
  8093. }
  8094. return null;
  8095. };
  8096. Scene.prototype.getSkeletonByName = function (name) {
  8097. for (var index = 0; index < this.skeletons.length; index++) {
  8098. if (this.skeletons[index].name === name) {
  8099. return this.skeletons[index];
  8100. }
  8101. }
  8102. return null;
  8103. };
  8104. Scene.prototype.isActiveMesh = function (mesh) {
  8105. return (this._activeMeshes.indexOf(mesh) !== -1);
  8106. };
  8107. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8108. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8109. var material = subMesh.getMaterial();
  8110. if (mesh.showSubMeshesBoundingBox) {
  8111. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8112. }
  8113. if (material) {
  8114. // Render targets
  8115. if (material.getRenderTargetTextures) {
  8116. if (this._processedMaterials.indexOf(material) === -1) {
  8117. this._processedMaterials.push(material);
  8118. this._renderTargets.concat(material.getRenderTargetTextures());
  8119. }
  8120. }
  8121. // Dispatch
  8122. this._activeVertices += subMesh.indexCount;
  8123. this._renderingManager.dispatch(subMesh);
  8124. }
  8125. }
  8126. };
  8127. Scene.prototype._evaluateActiveMeshes = function () {
  8128. this._activeMeshes.reset();
  8129. this._renderingManager.reset();
  8130. this._processedMaterials.reset();
  8131. this._activeParticleSystems.reset();
  8132. this._activeSkeletons.reset();
  8133. this._boundingBoxRenderer.reset();
  8134. if (!this._frustumPlanes) {
  8135. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8136. }
  8137. else {
  8138. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8139. }
  8140. // Meshes
  8141. var meshes;
  8142. var len;
  8143. if (this._selectionOctree) {
  8144. var selection = this._selectionOctree.select(this._frustumPlanes);
  8145. meshes = selection.data;
  8146. len = selection.length;
  8147. }
  8148. else {
  8149. len = this.meshes.length;
  8150. meshes = this.meshes;
  8151. }
  8152. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8153. var mesh = meshes[meshIndex];
  8154. if (mesh.isBlocked) {
  8155. continue;
  8156. }
  8157. this._totalVertices += mesh.getTotalVertices();
  8158. if (!mesh.isReady()) {
  8159. continue;
  8160. }
  8161. mesh.computeWorldMatrix();
  8162. // Intersections
  8163. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8164. this._meshesForIntersections.pushNoDuplicate(mesh);
  8165. }
  8166. // Switch to current LOD
  8167. var meshLOD = mesh.getLOD(this.activeCamera);
  8168. if (!meshLOD) {
  8169. continue;
  8170. }
  8171. mesh._preActivate();
  8172. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8173. this._activeMeshes.push(mesh);
  8174. mesh._activate(this._renderId);
  8175. this._activeMesh(meshLOD);
  8176. }
  8177. }
  8178. // Particle systems
  8179. var beforeParticlesDate = BABYLON.Tools.Now;
  8180. if (this.particlesEnabled) {
  8181. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8182. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8183. var particleSystem = this.particleSystems[particleIndex];
  8184. if (!particleSystem.isStarted()) {
  8185. continue;
  8186. }
  8187. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8188. this._activeParticleSystems.push(particleSystem);
  8189. particleSystem.animate();
  8190. }
  8191. }
  8192. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8193. }
  8194. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8195. };
  8196. Scene.prototype._activeMesh = function (mesh) {
  8197. if (mesh.skeleton && this.skeletonsEnabled) {
  8198. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8199. }
  8200. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8201. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8202. }
  8203. if (mesh && mesh.subMeshes) {
  8204. // Submeshes Octrees
  8205. var len;
  8206. var subMeshes;
  8207. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8208. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8209. len = intersections.length;
  8210. subMeshes = intersections.data;
  8211. }
  8212. else {
  8213. subMeshes = mesh.subMeshes;
  8214. len = subMeshes.length;
  8215. }
  8216. for (var subIndex = 0; subIndex < len; subIndex++) {
  8217. var subMesh = subMeshes[subIndex];
  8218. this._evaluateSubMesh(subMesh, mesh);
  8219. }
  8220. }
  8221. };
  8222. Scene.prototype.updateTransformMatrix = function (force) {
  8223. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8224. };
  8225. Scene.prototype._renderForCamera = function (camera) {
  8226. var engine = this._engine;
  8227. this.activeCamera = camera;
  8228. if (!this.activeCamera)
  8229. throw new Error("Active camera not set");
  8230. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8231. // Viewport
  8232. engine.setViewport(this.activeCamera.viewport);
  8233. // Camera
  8234. this._renderId++;
  8235. this.updateTransformMatrix();
  8236. if (this.beforeCameraRender) {
  8237. this.beforeCameraRender(this.activeCamera);
  8238. }
  8239. // Meshes
  8240. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8241. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8242. this._evaluateActiveMeshes();
  8243. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8244. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8245. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8246. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8247. skeleton.prepare();
  8248. this._activeBones += skeleton.bones.length;
  8249. }
  8250. // Render targets
  8251. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8252. if (this.renderTargetsEnabled) {
  8253. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8254. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8255. var renderTarget = this._renderTargets.data[renderIndex];
  8256. if (renderTarget._shouldRender()) {
  8257. this._renderId++;
  8258. renderTarget.render();
  8259. }
  8260. }
  8261. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8262. this._renderId++;
  8263. }
  8264. if (this._renderTargets.length > 0) {
  8265. engine.restoreDefaultFramebuffer();
  8266. }
  8267. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8268. // Prepare Frame
  8269. this.postProcessManager._prepareFrame();
  8270. var beforeRenderDate = BABYLON.Tools.Now;
  8271. // Backgrounds
  8272. if (this.layers.length) {
  8273. engine.setDepthBuffer(false);
  8274. var layerIndex;
  8275. var layer;
  8276. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8277. layer = this.layers[layerIndex];
  8278. if (layer.isBackground) {
  8279. layer.render();
  8280. }
  8281. }
  8282. engine.setDepthBuffer(true);
  8283. }
  8284. // Render
  8285. BABYLON.Tools.StartPerformanceCounter("Main render");
  8286. this._renderingManager.render(null, null, true, true);
  8287. BABYLON.Tools.EndPerformanceCounter("Main render");
  8288. // Bounding boxes
  8289. this._boundingBoxRenderer.render();
  8290. // Lens flares
  8291. if (this.lensFlaresEnabled) {
  8292. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8293. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8294. this.lensFlareSystems[lensFlareSystemIndex].render();
  8295. }
  8296. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8297. }
  8298. // Foregrounds
  8299. if (this.layers.length) {
  8300. engine.setDepthBuffer(false);
  8301. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8302. layer = this.layers[layerIndex];
  8303. if (!layer.isBackground) {
  8304. layer.render();
  8305. }
  8306. }
  8307. engine.setDepthBuffer(true);
  8308. }
  8309. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8310. // Finalize frame
  8311. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8312. // Update camera
  8313. this.activeCamera._updateFromScene();
  8314. // Reset some special arrays
  8315. this._renderTargets.reset();
  8316. if (this.afterCameraRender) {
  8317. this.afterCameraRender(this.activeCamera);
  8318. }
  8319. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8320. };
  8321. Scene.prototype._processSubCameras = function (camera) {
  8322. if (camera.subCameras.length === 0) {
  8323. this._renderForCamera(camera);
  8324. return;
  8325. }
  8326. for (var index = 0; index < camera.subCameras.length; index++) {
  8327. this._renderForCamera(camera.subCameras[index]);
  8328. }
  8329. this.activeCamera = camera;
  8330. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8331. // Update camera
  8332. this.activeCamera._updateFromScene();
  8333. };
  8334. Scene.prototype._checkIntersections = function () {
  8335. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8336. var sourceMesh = this._meshesForIntersections.data[index];
  8337. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8338. var action = sourceMesh.actionManager.actions[actionIndex];
  8339. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8340. var otherMesh = action.getTriggerParameter();
  8341. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  8342. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8343. if (areIntersecting && currentIntersectionInProgress === -1) {
  8344. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8345. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8346. sourceMesh._intersectionsInProgress.push(otherMesh);
  8347. }
  8348. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8349. sourceMesh._intersectionsInProgress.push(otherMesh);
  8350. }
  8351. }
  8352. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8353. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8354. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8355. if (indexOfOther > -1) {
  8356. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8357. }
  8358. }
  8359. }
  8360. }
  8361. }
  8362. };
  8363. Scene.prototype.render = function () {
  8364. var startDate = BABYLON.Tools.Now;
  8365. this._particlesDuration = 0;
  8366. this._spritesDuration = 0;
  8367. this._activeParticles = 0;
  8368. this._renderDuration = 0;
  8369. this._renderTargetsDuration = 0;
  8370. this._evaluateActiveMeshesDuration = 0;
  8371. this._totalVertices = 0;
  8372. this._activeVertices = 0;
  8373. this._activeBones = 0;
  8374. this.getEngine().resetDrawCalls();
  8375. this._meshesForIntersections.reset();
  8376. this.resetCachedMaterial();
  8377. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8378. // Actions
  8379. if (this.actionManager) {
  8380. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8381. }
  8382. // Before render
  8383. if (this.beforeRender) {
  8384. this.beforeRender();
  8385. }
  8386. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8387. this._onBeforeRenderCallbacks[callbackIndex]();
  8388. }
  8389. // Animations
  8390. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8391. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8392. this._animate();
  8393. // Physics
  8394. if (this._physicsEngine) {
  8395. BABYLON.Tools.StartPerformanceCounter("Physics");
  8396. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8397. BABYLON.Tools.EndPerformanceCounter("Physics");
  8398. }
  8399. // Customs render targets
  8400. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8401. var engine = this.getEngine();
  8402. if (this.renderTargetsEnabled) {
  8403. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8404. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8405. var renderTarget = this.customRenderTargets[customIndex];
  8406. if (renderTarget._shouldRender()) {
  8407. this._renderId++;
  8408. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8409. if (!this.activeCamera)
  8410. throw new Error("Active camera not set");
  8411. // Viewport
  8412. engine.setViewport(this.activeCamera.viewport);
  8413. // Camera
  8414. this.updateTransformMatrix();
  8415. renderTarget.render();
  8416. }
  8417. }
  8418. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8419. this._renderId++;
  8420. }
  8421. if (this.customRenderTargets.length > 0) {
  8422. engine.restoreDefaultFramebuffer();
  8423. }
  8424. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8425. // Procedural textures
  8426. if (this.proceduralTexturesEnabled) {
  8427. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8428. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8429. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8430. if (proceduralTexture._shouldRender()) {
  8431. proceduralTexture.render();
  8432. }
  8433. }
  8434. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8435. }
  8436. // Clear
  8437. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8438. // Shadows
  8439. if (this.shadowsEnabled) {
  8440. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8441. var light = this.lights[lightIndex];
  8442. var shadowGenerator = light.getShadowGenerator();
  8443. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8444. this._renderTargets.push(shadowGenerator.getShadowMap());
  8445. }
  8446. }
  8447. }
  8448. // Depth renderer
  8449. if (this._depthRenderer) {
  8450. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8451. }
  8452. // RenderPipeline
  8453. this.postProcessRenderPipelineManager.update();
  8454. // Multi-cameras?
  8455. if (this.activeCameras.length > 0) {
  8456. var currentRenderId = this._renderId;
  8457. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8458. this._renderId = currentRenderId;
  8459. this._processSubCameras(this.activeCameras[cameraIndex]);
  8460. }
  8461. }
  8462. else {
  8463. if (!this.activeCamera) {
  8464. throw new Error("No camera defined");
  8465. }
  8466. this._processSubCameras(this.activeCamera);
  8467. }
  8468. // Intersection checks
  8469. this._checkIntersections();
  8470. // Update the audio listener attached to the camera
  8471. this._updateAudioParameters();
  8472. // After render
  8473. if (this.afterRender) {
  8474. this.afterRender();
  8475. }
  8476. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8477. this._onAfterRenderCallbacks[callbackIndex]();
  8478. }
  8479. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8480. this._toBeDisposed.data[index].dispose();
  8481. this._toBeDisposed[index] = null;
  8482. }
  8483. this._toBeDisposed.reset();
  8484. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8485. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8486. };
  8487. Scene.prototype._updateAudioParameters = function () {
  8488. var listeningCamera;
  8489. var audioEngine = this._engine.getAudioEngine();
  8490. if (this.activeCameras.length > 0) {
  8491. listeningCamera = this.activeCameras[0];
  8492. }
  8493. else {
  8494. listeningCamera = this.activeCamera;
  8495. }
  8496. if (listeningCamera && audioEngine.canUseWebAudio) {
  8497. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8498. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8499. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8500. cameraDirection.normalize();
  8501. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8502. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8503. var sound = this.mainSoundTrack.soundCollection[i];
  8504. if (sound.useCustomAttenuation) {
  8505. sound.updateDistanceFromListener();
  8506. }
  8507. }
  8508. for (i = 0; i < this.soundTracks.length; i++) {
  8509. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8510. sound = this.soundTracks[i].soundCollection[j];
  8511. if (sound.useCustomAttenuation) {
  8512. sound.updateDistanceFromListener();
  8513. }
  8514. }
  8515. }
  8516. }
  8517. };
  8518. Scene.prototype.enableDepthRenderer = function () {
  8519. if (this._depthRenderer) {
  8520. return this._depthRenderer;
  8521. }
  8522. this._depthRenderer = new BABYLON.DepthRenderer(this);
  8523. return this._depthRenderer;
  8524. };
  8525. Scene.prototype.disableDepthRenderer = function () {
  8526. if (!this._depthRenderer) {
  8527. return;
  8528. }
  8529. this._depthRenderer.dispose();
  8530. this._depthRenderer = null;
  8531. };
  8532. Scene.prototype.dispose = function () {
  8533. this.beforeRender = null;
  8534. this.afterRender = null;
  8535. this.skeletons = [];
  8536. this._boundingBoxRenderer.dispose();
  8537. if (this._depthRenderer) {
  8538. this._depthRenderer.dispose();
  8539. }
  8540. // Debug layer
  8541. this.debugLayer.hide();
  8542. // Events
  8543. if (this.onDispose) {
  8544. this.onDispose();
  8545. }
  8546. this._onBeforeRenderCallbacks = [];
  8547. this._onAfterRenderCallbacks = [];
  8548. this.detachControl();
  8549. // Release sounds & sounds tracks
  8550. this.mainSoundTrack.dispose();
  8551. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  8552. this.soundTracks[scIndex].dispose();
  8553. }
  8554. // Detach cameras
  8555. var canvas = this._engine.getRenderingCanvas();
  8556. var index;
  8557. for (index = 0; index < this.cameras.length; index++) {
  8558. this.cameras[index].detachControl(canvas);
  8559. }
  8560. while (this.lights.length) {
  8561. this.lights[0].dispose();
  8562. }
  8563. while (this.meshes.length) {
  8564. this.meshes[0].dispose(true);
  8565. }
  8566. while (this.cameras.length) {
  8567. this.cameras[0].dispose();
  8568. }
  8569. while (this.materials.length) {
  8570. this.materials[0].dispose();
  8571. }
  8572. while (this.particleSystems.length) {
  8573. this.particleSystems[0].dispose();
  8574. }
  8575. while (this.spriteManagers.length) {
  8576. this.spriteManagers[0].dispose();
  8577. }
  8578. while (this.layers.length) {
  8579. this.layers[0].dispose();
  8580. }
  8581. while (this.textures.length) {
  8582. this.textures[0].dispose();
  8583. }
  8584. // Post-processes
  8585. this.postProcessManager.dispose();
  8586. // Physics
  8587. if (this._physicsEngine) {
  8588. this.disablePhysicsEngine();
  8589. }
  8590. // Remove from engine
  8591. index = this._engine.scenes.indexOf(this);
  8592. if (index > -1) {
  8593. this._engine.scenes.splice(index, 1);
  8594. }
  8595. this._engine.wipeCaches();
  8596. };
  8597. // Collisions
  8598. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8599. if (excludedMesh === void 0) { excludedMesh = null; }
  8600. position.divideToRef(collider.radius, this._scaledPosition);
  8601. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8602. collider.retry = 0;
  8603. collider.initialVelocity = this._scaledVelocity;
  8604. collider.initialPosition = this._scaledPosition;
  8605. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8606. finalPosition.multiplyInPlace(collider.radius);
  8607. };
  8608. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8609. if (excludedMesh === void 0) { excludedMesh = null; }
  8610. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8611. if (collider.retry >= maximumRetry) {
  8612. finalPosition.copyFrom(position);
  8613. return;
  8614. }
  8615. collider._initialize(position, velocity, closeDistance);
  8616. for (var index = 0; index < this.meshes.length; index++) {
  8617. var mesh = this.meshes[index];
  8618. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8619. mesh._checkCollision(collider);
  8620. }
  8621. }
  8622. if (!collider.collisionFound) {
  8623. position.addToRef(velocity, finalPosition);
  8624. return;
  8625. }
  8626. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8627. collider._getResponse(position, velocity);
  8628. }
  8629. if (velocity.length() <= closeDistance) {
  8630. finalPosition.copyFrom(position);
  8631. return;
  8632. }
  8633. collider.retry++;
  8634. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8635. };
  8636. // Octrees
  8637. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8638. if (maxCapacity === void 0) { maxCapacity = 64; }
  8639. if (maxDepth === void 0) { maxDepth = 2; }
  8640. if (!this._selectionOctree) {
  8641. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8642. }
  8643. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8644. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8645. for (var index = 0; index < this.meshes.length; index++) {
  8646. var mesh = this.meshes[index];
  8647. mesh.computeWorldMatrix(true);
  8648. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8649. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8650. BABYLON.Tools.CheckExtends(minBox, min, max);
  8651. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8652. }
  8653. // Update octree
  8654. this._selectionOctree.update(min, max, this.meshes);
  8655. return this._selectionOctree;
  8656. };
  8657. // Picking
  8658. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8659. var engine = this._engine;
  8660. if (!camera) {
  8661. if (!this.activeCamera)
  8662. throw new Error("Active camera not set");
  8663. camera = this.activeCamera;
  8664. }
  8665. var cameraViewport = camera.viewport;
  8666. var viewport = cameraViewport.toGlobal(engine);
  8667. // Moving coordinates to local viewport world
  8668. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8669. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8670. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8671. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8672. };
  8673. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8674. var pickingInfo = null;
  8675. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8676. var mesh = this.meshes[meshIndex];
  8677. if (predicate) {
  8678. if (!predicate(mesh)) {
  8679. continue;
  8680. }
  8681. }
  8682. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8683. continue;
  8684. }
  8685. var world = mesh.getWorldMatrix();
  8686. var ray = rayFunction(world);
  8687. var result = mesh.intersects(ray, fastCheck);
  8688. if (!result || !result.hit)
  8689. continue;
  8690. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8691. continue;
  8692. pickingInfo = result;
  8693. if (fastCheck) {
  8694. break;
  8695. }
  8696. }
  8697. return pickingInfo || new BABYLON.PickingInfo();
  8698. };
  8699. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8700. var _this = this;
  8701. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8702. /// <param name="x">X position on screen</param>
  8703. /// <param name="y">Y position on screen</param>
  8704. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  8705. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8706. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  8707. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  8708. };
  8709. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8710. var _this = this;
  8711. return this._internalPick(function (world) {
  8712. if (!_this._pickWithRayInverseMatrix) {
  8713. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8714. }
  8715. world.invertToRef(_this._pickWithRayInverseMatrix);
  8716. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8717. }, predicate, fastCheck);
  8718. };
  8719. Scene.prototype.setPointerOverMesh = function (mesh) {
  8720. if (this._pointerOverMesh === mesh) {
  8721. return;
  8722. }
  8723. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8724. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8725. }
  8726. this._pointerOverMesh = mesh;
  8727. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8728. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8729. }
  8730. };
  8731. Scene.prototype.getPointerOverMesh = function () {
  8732. return this._pointerOverMesh;
  8733. };
  8734. // Physics
  8735. Scene.prototype.getPhysicsEngine = function () {
  8736. return this._physicsEngine;
  8737. };
  8738. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8739. if (this._physicsEngine) {
  8740. return true;
  8741. }
  8742. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8743. if (!this._physicsEngine.isSupported()) {
  8744. this._physicsEngine = null;
  8745. return false;
  8746. }
  8747. this._physicsEngine._initialize(gravity);
  8748. return true;
  8749. };
  8750. Scene.prototype.disablePhysicsEngine = function () {
  8751. if (!this._physicsEngine) {
  8752. return;
  8753. }
  8754. this._physicsEngine.dispose();
  8755. this._physicsEngine = undefined;
  8756. };
  8757. Scene.prototype.isPhysicsEnabled = function () {
  8758. return this._physicsEngine !== undefined;
  8759. };
  8760. Scene.prototype.setGravity = function (gravity) {
  8761. if (!this._physicsEngine) {
  8762. return;
  8763. }
  8764. this._physicsEngine._setGravity(gravity);
  8765. };
  8766. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8767. if (parts.parts) {
  8768. options = parts;
  8769. parts = parts.parts;
  8770. }
  8771. if (!this._physicsEngine) {
  8772. return null;
  8773. }
  8774. for (var index = 0; index < parts.length; index++) {
  8775. var mesh = parts[index].mesh;
  8776. mesh._physicImpostor = parts[index].impostor;
  8777. mesh._physicsMass = options.mass / parts.length;
  8778. mesh._physicsFriction = options.friction;
  8779. mesh._physicRestitution = options.restitution;
  8780. }
  8781. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8782. };
  8783. //ANY
  8784. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8785. for (var index = 0; index < compound.parts.length; index++) {
  8786. var mesh = compound.parts[index].mesh;
  8787. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8788. this._physicsEngine._unregisterMesh(mesh);
  8789. }
  8790. };
  8791. // Tags
  8792. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  8793. if (tagsQuery === undefined) {
  8794. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8795. return list;
  8796. }
  8797. var listByTags = [];
  8798. forEach = forEach || (function (item) {
  8799. return;
  8800. });
  8801. for (var i in list) {
  8802. var item = list[i];
  8803. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8804. listByTags.push(item);
  8805. forEach(item);
  8806. }
  8807. }
  8808. return listByTags;
  8809. };
  8810. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  8811. return this._getByTags(this.meshes, tagsQuery, forEach);
  8812. };
  8813. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  8814. return this._getByTags(this.cameras, tagsQuery, forEach);
  8815. };
  8816. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  8817. return this._getByTags(this.lights, tagsQuery, forEach);
  8818. };
  8819. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  8820. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  8821. };
  8822. // Statics
  8823. Scene.FOGMODE_NONE = 0;
  8824. Scene.FOGMODE_EXP = 1;
  8825. Scene.FOGMODE_EXP2 = 2;
  8826. Scene.FOGMODE_LINEAR = 3;
  8827. Scene.MinDeltaTime = 1.0;
  8828. Scene.MaxDeltaTime = 1000.0;
  8829. return Scene;
  8830. })();
  8831. BABYLON.Scene = Scene;
  8832. })(BABYLON || (BABYLON = {}));
  8833. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  8834. (function (BABYLON) {
  8835. var VertexBuffer = (function () {
  8836. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8837. if (engine instanceof BABYLON.Mesh) {
  8838. this._engine = engine.getScene().getEngine();
  8839. }
  8840. else {
  8841. this._engine = engine;
  8842. }
  8843. this._updatable = updatable;
  8844. this._data = data;
  8845. if (!postponeInternalCreation) {
  8846. this.create();
  8847. }
  8848. this._kind = kind;
  8849. if (stride) {
  8850. this._strideSize = stride;
  8851. return;
  8852. }
  8853. switch (kind) {
  8854. case VertexBuffer.PositionKind:
  8855. this._strideSize = 3;
  8856. break;
  8857. case VertexBuffer.NormalKind:
  8858. this._strideSize = 3;
  8859. break;
  8860. case VertexBuffer.UVKind:
  8861. this._strideSize = 2;
  8862. break;
  8863. case VertexBuffer.UV2Kind:
  8864. this._strideSize = 2;
  8865. break;
  8866. case VertexBuffer.ColorKind:
  8867. this._strideSize = 4;
  8868. break;
  8869. case VertexBuffer.MatricesIndicesKind:
  8870. this._strideSize = 4;
  8871. break;
  8872. case VertexBuffer.MatricesWeightsKind:
  8873. this._strideSize = 4;
  8874. break;
  8875. }
  8876. }
  8877. // Properties
  8878. VertexBuffer.prototype.isUpdatable = function () {
  8879. return this._updatable;
  8880. };
  8881. VertexBuffer.prototype.getData = function () {
  8882. return this._data;
  8883. };
  8884. VertexBuffer.prototype.getBuffer = function () {
  8885. return this._buffer;
  8886. };
  8887. VertexBuffer.prototype.getStrideSize = function () {
  8888. return this._strideSize;
  8889. };
  8890. // Methods
  8891. VertexBuffer.prototype.create = function (data) {
  8892. if (!data && this._buffer) {
  8893. return; // nothing to do
  8894. }
  8895. data = data || this._data;
  8896. if (!this._buffer) {
  8897. if (this._updatable) {
  8898. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8899. }
  8900. else {
  8901. this._buffer = this._engine.createVertexBuffer(data);
  8902. }
  8903. }
  8904. if (this._updatable) {
  8905. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  8906. this._data = data;
  8907. }
  8908. };
  8909. VertexBuffer.prototype.update = function (data) {
  8910. this.create(data);
  8911. };
  8912. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  8913. if (!this._buffer) {
  8914. return;
  8915. }
  8916. if (this._updatable) {
  8917. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  8918. this._data = null;
  8919. }
  8920. };
  8921. VertexBuffer.prototype.dispose = function () {
  8922. if (!this._buffer) {
  8923. return;
  8924. }
  8925. if (this._engine._releaseBuffer(this._buffer)) {
  8926. this._buffer = null;
  8927. }
  8928. };
  8929. Object.defineProperty(VertexBuffer, "PositionKind", {
  8930. get: function () {
  8931. return VertexBuffer._PositionKind;
  8932. },
  8933. enumerable: true,
  8934. configurable: true
  8935. });
  8936. Object.defineProperty(VertexBuffer, "NormalKind", {
  8937. get: function () {
  8938. return VertexBuffer._NormalKind;
  8939. },
  8940. enumerable: true,
  8941. configurable: true
  8942. });
  8943. Object.defineProperty(VertexBuffer, "UVKind", {
  8944. get: function () {
  8945. return VertexBuffer._UVKind;
  8946. },
  8947. enumerable: true,
  8948. configurable: true
  8949. });
  8950. Object.defineProperty(VertexBuffer, "UV2Kind", {
  8951. get: function () {
  8952. return VertexBuffer._UV2Kind;
  8953. },
  8954. enumerable: true,
  8955. configurable: true
  8956. });
  8957. Object.defineProperty(VertexBuffer, "ColorKind", {
  8958. get: function () {
  8959. return VertexBuffer._ColorKind;
  8960. },
  8961. enumerable: true,
  8962. configurable: true
  8963. });
  8964. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  8965. get: function () {
  8966. return VertexBuffer._MatricesIndicesKind;
  8967. },
  8968. enumerable: true,
  8969. configurable: true
  8970. });
  8971. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  8972. get: function () {
  8973. return VertexBuffer._MatricesWeightsKind;
  8974. },
  8975. enumerable: true,
  8976. configurable: true
  8977. });
  8978. // Enums
  8979. VertexBuffer._PositionKind = "position";
  8980. VertexBuffer._NormalKind = "normal";
  8981. VertexBuffer._UVKind = "uv";
  8982. VertexBuffer._UV2Kind = "uv2";
  8983. VertexBuffer._ColorKind = "color";
  8984. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  8985. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  8986. return VertexBuffer;
  8987. })();
  8988. BABYLON.VertexBuffer = VertexBuffer;
  8989. })(BABYLON || (BABYLON = {}));
  8990. //# sourceMappingURL=babylon.vertexBuffer.js.map
  8991. var BABYLON;
  8992. (function (BABYLON) {
  8993. var AbstractMesh = (function (_super) {
  8994. __extends(AbstractMesh, _super);
  8995. function AbstractMesh(name, scene) {
  8996. _super.call(this, name, scene);
  8997. // Properties
  8998. this.definedFacingForward = true; // orientation for POV movement & rotation
  8999. this.position = new BABYLON.Vector3(0, 0, 0);
  9000. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9001. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9002. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9003. this.visibility = 1.0;
  9004. this.alphaIndex = Number.MAX_VALUE;
  9005. this.infiniteDistance = false;
  9006. this.isVisible = true;
  9007. this.isPickable = true;
  9008. this.showBoundingBox = false;
  9009. this.showSubMeshesBoundingBox = false;
  9010. this.onDispose = null;
  9011. this.checkCollisions = false;
  9012. this.isBlocker = false;
  9013. this.renderingGroupId = 0;
  9014. this.receiveShadows = false;
  9015. this.renderOutline = false;
  9016. this.outlineColor = BABYLON.Color3.Red();
  9017. this.outlineWidth = 0.02;
  9018. this.renderOverlay = false;
  9019. this.overlayColor = BABYLON.Color3.Red();
  9020. this.overlayAlpha = 0.5;
  9021. this.hasVertexAlpha = false;
  9022. this.useVertexColors = true;
  9023. this.applyFog = true;
  9024. this.useOctreeForRenderingSelection = true;
  9025. this.useOctreeForPicking = true;
  9026. this.useOctreeForCollisions = true;
  9027. this.layerMask = 0xFFFFFFFF;
  9028. // Physics
  9029. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9030. // Collisions
  9031. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9032. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9033. this._collider = new BABYLON.Collider();
  9034. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9035. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9036. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9037. // Cache
  9038. this._localScaling = BABYLON.Matrix.Zero();
  9039. this._localRotation = BABYLON.Matrix.Zero();
  9040. this._localTranslation = BABYLON.Matrix.Zero();
  9041. this._localBillboard = BABYLON.Matrix.Zero();
  9042. this._localPivotScaling = BABYLON.Matrix.Zero();
  9043. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9044. this._localWorld = BABYLON.Matrix.Zero();
  9045. this._worldMatrix = BABYLON.Matrix.Zero();
  9046. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9047. this._absolutePosition = BABYLON.Vector3.Zero();
  9048. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9049. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9050. this._isDirty = false;
  9051. this._pivotMatrix = BABYLON.Matrix.Identity();
  9052. this._isDisposed = false;
  9053. this._renderId = 0;
  9054. this._intersectionsInProgress = new Array();
  9055. this._onAfterWorldMatrixUpdate = new Array();
  9056. scene.meshes.push(this);
  9057. }
  9058. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9059. get: function () {
  9060. return AbstractMesh._BILLBOARDMODE_NONE;
  9061. },
  9062. enumerable: true,
  9063. configurable: true
  9064. });
  9065. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9066. get: function () {
  9067. return AbstractMesh._BILLBOARDMODE_X;
  9068. },
  9069. enumerable: true,
  9070. configurable: true
  9071. });
  9072. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9073. get: function () {
  9074. return AbstractMesh._BILLBOARDMODE_Y;
  9075. },
  9076. enumerable: true,
  9077. configurable: true
  9078. });
  9079. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9080. get: function () {
  9081. return AbstractMesh._BILLBOARDMODE_Z;
  9082. },
  9083. enumerable: true,
  9084. configurable: true
  9085. });
  9086. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9087. get: function () {
  9088. return AbstractMesh._BILLBOARDMODE_ALL;
  9089. },
  9090. enumerable: true,
  9091. configurable: true
  9092. });
  9093. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9094. // Methods
  9095. get: function () {
  9096. return false;
  9097. },
  9098. enumerable: true,
  9099. configurable: true
  9100. });
  9101. AbstractMesh.prototype.getLOD = function (camera) {
  9102. return this;
  9103. };
  9104. AbstractMesh.prototype.getTotalVertices = function () {
  9105. return 0;
  9106. };
  9107. AbstractMesh.prototype.getIndices = function () {
  9108. return null;
  9109. };
  9110. AbstractMesh.prototype.getVerticesData = function (kind) {
  9111. return null;
  9112. };
  9113. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9114. return false;
  9115. };
  9116. AbstractMesh.prototype.getBoundingInfo = function () {
  9117. if (this._masterMesh) {
  9118. return this._masterMesh.getBoundingInfo();
  9119. }
  9120. if (!this._boundingInfo) {
  9121. this._updateBoundingInfo();
  9122. }
  9123. return this._boundingInfo;
  9124. };
  9125. AbstractMesh.prototype._preActivate = function () {
  9126. };
  9127. AbstractMesh.prototype._activate = function (renderId) {
  9128. this._renderId = renderId;
  9129. };
  9130. AbstractMesh.prototype.getWorldMatrix = function () {
  9131. if (this._masterMesh) {
  9132. return this._masterMesh.getWorldMatrix();
  9133. }
  9134. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9135. this.computeWorldMatrix();
  9136. }
  9137. return this._worldMatrix;
  9138. };
  9139. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9140. get: function () {
  9141. return this._worldMatrix;
  9142. },
  9143. enumerable: true,
  9144. configurable: true
  9145. });
  9146. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9147. get: function () {
  9148. return this._absolutePosition;
  9149. },
  9150. enumerable: true,
  9151. configurable: true
  9152. });
  9153. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9154. if (!this.rotationQuaternion) {
  9155. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9156. this.rotation = BABYLON.Vector3.Zero();
  9157. }
  9158. if (!space || space == 0 /* LOCAL */) {
  9159. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9160. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9161. }
  9162. else {
  9163. if (this.parent) {
  9164. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9165. invertParentWorldMatrix.invert();
  9166. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9167. }
  9168. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9169. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9170. }
  9171. };
  9172. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9173. var displacementVector = axis.scale(distance);
  9174. if (!space || space == 0 /* LOCAL */) {
  9175. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9176. this.setPositionWithLocalVector(tempV3);
  9177. }
  9178. else {
  9179. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9180. }
  9181. };
  9182. AbstractMesh.prototype.getAbsolutePosition = function () {
  9183. this.computeWorldMatrix();
  9184. return this._absolutePosition;
  9185. };
  9186. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9187. if (!absolutePosition) {
  9188. return;
  9189. }
  9190. var absolutePositionX;
  9191. var absolutePositionY;
  9192. var absolutePositionZ;
  9193. if (absolutePosition.x === undefined) {
  9194. if (arguments.length < 3) {
  9195. return;
  9196. }
  9197. absolutePositionX = arguments[0];
  9198. absolutePositionY = arguments[1];
  9199. absolutePositionZ = arguments[2];
  9200. }
  9201. else {
  9202. absolutePositionX = absolutePosition.x;
  9203. absolutePositionY = absolutePosition.y;
  9204. absolutePositionZ = absolutePosition.z;
  9205. }
  9206. if (this.parent) {
  9207. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9208. invertParentWorldMatrix.invert();
  9209. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9210. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9211. }
  9212. else {
  9213. this.position.x = absolutePositionX;
  9214. this.position.y = absolutePositionY;
  9215. this.position.z = absolutePositionZ;
  9216. }
  9217. };
  9218. // ================================== Point of View Movement =================================
  9219. /**
  9220. * Perform relative position change from the point of view of behind the front of the mesh.
  9221. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9222. * Supports definition of mesh facing forward or backward.
  9223. * @param {number} amountRight
  9224. * @param {number} amountUp
  9225. * @param {number} amountForward
  9226. */
  9227. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9228. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9229. };
  9230. /**
  9231. * Calculate relative position change from the point of view of behind the front of the mesh.
  9232. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9233. * Supports definition of mesh facing forward or backward.
  9234. * @param {number} amountRight
  9235. * @param {number} amountUp
  9236. * @param {number} amountForward
  9237. */
  9238. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9239. var rotMatrix = new BABYLON.Matrix();
  9240. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9241. rotQuaternion.toRotationMatrix(rotMatrix);
  9242. var translationDelta = BABYLON.Vector3.Zero();
  9243. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9244. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9245. return translationDelta;
  9246. };
  9247. // ================================== Point of View Rotation =================================
  9248. /**
  9249. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9250. * Supports definition of mesh facing forward or backward.
  9251. * @param {number} flipBack
  9252. * @param {number} twirlClockwise
  9253. * @param {number} tiltRight
  9254. */
  9255. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9256. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9257. };
  9258. /**
  9259. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9260. * Supports definition of mesh facing forward or backward.
  9261. * @param {number} flipBack
  9262. * @param {number} twirlClockwise
  9263. * @param {number} tiltRight
  9264. */
  9265. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9266. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9267. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9268. };
  9269. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9270. this._pivotMatrix = matrix;
  9271. this._cache.pivotMatrixUpdated = true;
  9272. };
  9273. AbstractMesh.prototype.getPivotMatrix = function () {
  9274. return this._pivotMatrix;
  9275. };
  9276. AbstractMesh.prototype._isSynchronized = function () {
  9277. if (this._isDirty) {
  9278. return false;
  9279. }
  9280. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9281. return false;
  9282. if (this._cache.pivotMatrixUpdated) {
  9283. return false;
  9284. }
  9285. if (this.infiniteDistance) {
  9286. return false;
  9287. }
  9288. if (!this._cache.position.equals(this.position))
  9289. return false;
  9290. if (this.rotationQuaternion) {
  9291. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9292. return false;
  9293. }
  9294. else {
  9295. if (!this._cache.rotation.equals(this.rotation))
  9296. return false;
  9297. }
  9298. if (!this._cache.scaling.equals(this.scaling))
  9299. return false;
  9300. return true;
  9301. };
  9302. AbstractMesh.prototype._initCache = function () {
  9303. _super.prototype._initCache.call(this);
  9304. this._cache.localMatrixUpdated = false;
  9305. this._cache.position = BABYLON.Vector3.Zero();
  9306. this._cache.scaling = BABYLON.Vector3.Zero();
  9307. this._cache.rotation = BABYLON.Vector3.Zero();
  9308. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9309. };
  9310. AbstractMesh.prototype.markAsDirty = function (property) {
  9311. if (property === "rotation") {
  9312. this.rotationQuaternion = null;
  9313. }
  9314. this._currentRenderId = Number.MAX_VALUE;
  9315. this._isDirty = true;
  9316. };
  9317. AbstractMesh.prototype._updateBoundingInfo = function () {
  9318. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9319. this._boundingInfo._update(this.worldMatrixFromCache);
  9320. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9321. };
  9322. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9323. if (!this.subMeshes) {
  9324. return;
  9325. }
  9326. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9327. var subMesh = this.subMeshes[subIndex];
  9328. subMesh.updateBoundingInfo(matrix);
  9329. }
  9330. };
  9331. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9332. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9333. return this._worldMatrix;
  9334. }
  9335. this._cache.position.copyFrom(this.position);
  9336. this._cache.scaling.copyFrom(this.scaling);
  9337. this._cache.pivotMatrixUpdated = false;
  9338. this._currentRenderId = this.getScene().getRenderId();
  9339. this._isDirty = false;
  9340. // Scaling
  9341. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9342. // Rotation
  9343. if (this.rotationQuaternion) {
  9344. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9345. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9346. }
  9347. else {
  9348. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9349. this._cache.rotation.copyFrom(this.rotation);
  9350. }
  9351. // Translation
  9352. if (this.infiniteDistance && !this.parent) {
  9353. var camera = this.getScene().activeCamera;
  9354. var cameraWorldMatrix = camera.getWorldMatrix();
  9355. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9356. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9357. }
  9358. else {
  9359. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9360. }
  9361. // Composing transformations
  9362. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9363. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9364. // Billboarding
  9365. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9366. var localPosition = this.position.clone();
  9367. var zero = this.getScene().activeCamera.position.clone();
  9368. if (this.parent && this.parent.position) {
  9369. localPosition.addInPlace(this.parent.position);
  9370. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9371. }
  9372. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9373. zero = this.getScene().activeCamera.position;
  9374. }
  9375. else {
  9376. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9377. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9378. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9379. zero.y = localPosition.y + 0.001;
  9380. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9381. zero.z = localPosition.z + 0.001;
  9382. }
  9383. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9384. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9385. this._localBillboard.invert();
  9386. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9387. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9388. }
  9389. // Local world
  9390. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9391. // Parent
  9392. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9393. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9394. }
  9395. else {
  9396. this._worldMatrix.copyFrom(this._localWorld);
  9397. }
  9398. // Bounding info
  9399. this._updateBoundingInfo();
  9400. // Absolute position
  9401. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9402. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9403. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9404. }
  9405. return this._worldMatrix;
  9406. };
  9407. /**
  9408. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9409. * @param func: callback function to add
  9410. */
  9411. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9412. this._onAfterWorldMatrixUpdate.push(func);
  9413. };
  9414. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9415. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  9416. if (index > -1) {
  9417. this._onAfterWorldMatrixUpdate.splice(index, 1);
  9418. }
  9419. };
  9420. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9421. this.computeWorldMatrix();
  9422. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9423. };
  9424. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9425. this.computeWorldMatrix();
  9426. var invLocalWorldMatrix = this._localWorld.clone();
  9427. invLocalWorldMatrix.invert();
  9428. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9429. };
  9430. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9431. this.computeWorldMatrix();
  9432. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9433. };
  9434. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9435. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9436. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9437. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9438. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9439. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9440. /// <returns>Mesh oriented towards targetMesh</returns>
  9441. yawCor = yawCor || 0; // default to zero if undefined
  9442. pitchCor = pitchCor || 0;
  9443. rollCor = rollCor || 0;
  9444. var dv = targetPoint.subtract(this.position);
  9445. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9446. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9447. var pitch = Math.atan2(dv.y, len);
  9448. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9449. };
  9450. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9451. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9452. return false;
  9453. }
  9454. return true;
  9455. };
  9456. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9457. if (!camera) {
  9458. camera = this.getScene().activeCamera;
  9459. }
  9460. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9461. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9462. return false;
  9463. }
  9464. return true;
  9465. };
  9466. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9467. if (!this._boundingInfo || !mesh._boundingInfo) {
  9468. return false;
  9469. }
  9470. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9471. };
  9472. AbstractMesh.prototype.intersectsPoint = function (point) {
  9473. if (!this._boundingInfo) {
  9474. return false;
  9475. }
  9476. return this._boundingInfo.intersectsPoint(point);
  9477. };
  9478. // Physics
  9479. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9480. var physicsEngine = this.getScene().getPhysicsEngine();
  9481. if (!physicsEngine) {
  9482. return;
  9483. }
  9484. if (impostor.impostor) {
  9485. // Old API
  9486. options = impostor;
  9487. impostor = impostor.impostor;
  9488. }
  9489. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9490. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9491. physicsEngine._unregisterMesh(this);
  9492. return;
  9493. }
  9494. options.mass = options.mass || 0;
  9495. options.friction = options.friction || 0.2;
  9496. options.restitution = options.restitution || 0.2;
  9497. this._physicImpostor = impostor;
  9498. this._physicsMass = options.mass;
  9499. this._physicsFriction = options.friction;
  9500. this._physicRestitution = options.restitution;
  9501. return physicsEngine._registerMesh(this, impostor, options);
  9502. };
  9503. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9504. if (!this._physicImpostor) {
  9505. return BABYLON.PhysicsEngine.NoImpostor;
  9506. }
  9507. return this._physicImpostor;
  9508. };
  9509. AbstractMesh.prototype.getPhysicsMass = function () {
  9510. if (!this._physicsMass) {
  9511. return 0;
  9512. }
  9513. return this._physicsMass;
  9514. };
  9515. AbstractMesh.prototype.getPhysicsFriction = function () {
  9516. if (!this._physicsFriction) {
  9517. return 0;
  9518. }
  9519. return this._physicsFriction;
  9520. };
  9521. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9522. if (!this._physicRestitution) {
  9523. return 0;
  9524. }
  9525. return this._physicRestitution;
  9526. };
  9527. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9528. if (!camera) {
  9529. camera = this.getScene().activeCamera;
  9530. }
  9531. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9532. };
  9533. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9534. if (!camera) {
  9535. camera = this.getScene().activeCamera;
  9536. }
  9537. return this.absolutePosition.subtract(camera.position).length();
  9538. };
  9539. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9540. if (!this._physicImpostor) {
  9541. return;
  9542. }
  9543. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9544. };
  9545. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9546. if (!this._physicImpostor) {
  9547. return;
  9548. }
  9549. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9550. };
  9551. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9552. if (!this._physicImpostor) {
  9553. return;
  9554. }
  9555. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9556. };
  9557. // Collisions
  9558. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9559. var globalPosition = this.getAbsolutePosition();
  9560. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9561. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9562. this._collider.radius = this.ellipsoid;
  9563. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  9564. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  9565. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9566. this.position.addInPlace(this._diffPositionForCollisions);
  9567. }
  9568. };
  9569. // Submeshes octree
  9570. /**
  9571. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9572. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9573. */
  9574. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9575. if (maxCapacity === void 0) { maxCapacity = 64; }
  9576. if (maxDepth === void 0) { maxDepth = 2; }
  9577. if (!this._submeshesOctree) {
  9578. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9579. }
  9580. this.computeWorldMatrix(true);
  9581. // Update octree
  9582. var bbox = this.getBoundingInfo().boundingBox;
  9583. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9584. return this._submeshesOctree;
  9585. };
  9586. // Collisions
  9587. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9588. this._generatePointsArray();
  9589. // Transformation
  9590. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9591. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9592. subMesh._lastColliderWorldVertices = [];
  9593. subMesh._trianglePlanes = [];
  9594. var start = subMesh.verticesStart;
  9595. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9596. for (var i = start; i < end; i++) {
  9597. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9598. }
  9599. }
  9600. // Collide
  9601. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  9602. };
  9603. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9604. var subMeshes;
  9605. var len;
  9606. // Octrees
  9607. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9608. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9609. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9610. len = intersections.length;
  9611. subMeshes = intersections.data;
  9612. }
  9613. else {
  9614. subMeshes = this.subMeshes;
  9615. len = subMeshes.length;
  9616. }
  9617. for (var index = 0; index < len; index++) {
  9618. var subMesh = subMeshes[index];
  9619. // Bounding test
  9620. if (len > 1 && !subMesh._checkCollision(collider))
  9621. continue;
  9622. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9623. }
  9624. };
  9625. AbstractMesh.prototype._checkCollision = function (collider) {
  9626. // Bounding box test
  9627. if (!this._boundingInfo._checkCollision(collider))
  9628. return;
  9629. // Transformation matrix
  9630. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9631. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9632. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9633. };
  9634. // Picking
  9635. AbstractMesh.prototype._generatePointsArray = function () {
  9636. return false;
  9637. };
  9638. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9639. var pickingInfo = new BABYLON.PickingInfo();
  9640. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9641. return pickingInfo;
  9642. }
  9643. if (!this._generatePointsArray()) {
  9644. return pickingInfo;
  9645. }
  9646. var intersectInfo = null;
  9647. // Octrees
  9648. var subMeshes;
  9649. var len;
  9650. if (this._submeshesOctree && this.useOctreeForPicking) {
  9651. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9652. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9653. len = intersections.length;
  9654. subMeshes = intersections.data;
  9655. }
  9656. else {
  9657. subMeshes = this.subMeshes;
  9658. len = subMeshes.length;
  9659. }
  9660. for (var index = 0; index < len; index++) {
  9661. var subMesh = subMeshes[index];
  9662. // Bounding test
  9663. if (len > 1 && !subMesh.canIntersects(ray))
  9664. continue;
  9665. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9666. if (currentIntersectInfo) {
  9667. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9668. intersectInfo = currentIntersectInfo;
  9669. if (fastCheck) {
  9670. break;
  9671. }
  9672. }
  9673. }
  9674. }
  9675. if (intersectInfo) {
  9676. // Get picked point
  9677. var world = this.getWorldMatrix();
  9678. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9679. var direction = ray.direction.clone();
  9680. // direction.normalize();
  9681. direction = direction.scale(intersectInfo.distance);
  9682. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9683. var pickedPoint = worldOrigin.add(worldDirection);
  9684. // Return result
  9685. pickingInfo.hit = true;
  9686. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9687. pickingInfo.pickedPoint = pickedPoint;
  9688. pickingInfo.pickedMesh = this;
  9689. pickingInfo.bu = intersectInfo.bu;
  9690. pickingInfo.bv = intersectInfo.bv;
  9691. pickingInfo.faceId = intersectInfo.faceId;
  9692. return pickingInfo;
  9693. }
  9694. return pickingInfo;
  9695. };
  9696. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9697. return null;
  9698. };
  9699. AbstractMesh.prototype.releaseSubMeshes = function () {
  9700. if (this.subMeshes) {
  9701. while (this.subMeshes.length) {
  9702. this.subMeshes[0].dispose();
  9703. }
  9704. }
  9705. else {
  9706. this.subMeshes = new Array();
  9707. }
  9708. };
  9709. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9710. // Physics
  9711. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9712. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9713. }
  9714. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9715. var other = this._intersectionsInProgress[index];
  9716. var pos = other._intersectionsInProgress.indexOf(this);
  9717. other._intersectionsInProgress.splice(pos, 1);
  9718. }
  9719. this._intersectionsInProgress = [];
  9720. // SubMeshes
  9721. this.releaseSubMeshes();
  9722. // Remove from scene
  9723. var index = this.getScene().meshes.indexOf(this);
  9724. if (index != -1) {
  9725. // Remove from the scene if mesh found
  9726. this.getScene().meshes.splice(index, 1);
  9727. }
  9728. if (!doNotRecurse) {
  9729. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9730. if (this.getScene().particleSystems[index].emitter == this) {
  9731. this.getScene().particleSystems[index].dispose();
  9732. index--;
  9733. }
  9734. }
  9735. // Children
  9736. var objects = this.getScene().meshes.slice(0);
  9737. for (index = 0; index < objects.length; index++) {
  9738. if (objects[index].parent == this) {
  9739. objects[index].dispose();
  9740. }
  9741. }
  9742. }
  9743. else {
  9744. for (index = 0; index < this.getScene().meshes.length; index++) {
  9745. var obj = this.getScene().meshes[index];
  9746. if (obj.parent === this) {
  9747. obj.parent = null;
  9748. obj.computeWorldMatrix(true);
  9749. }
  9750. }
  9751. }
  9752. this._onAfterWorldMatrixUpdate = [];
  9753. this._isDisposed = true;
  9754. // Callback
  9755. if (this.onDispose) {
  9756. this.onDispose();
  9757. }
  9758. };
  9759. // Statics
  9760. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9761. AbstractMesh._BILLBOARDMODE_X = 1;
  9762. AbstractMesh._BILLBOARDMODE_Y = 2;
  9763. AbstractMesh._BILLBOARDMODE_Z = 4;
  9764. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9765. return AbstractMesh;
  9766. })(BABYLON.Node);
  9767. BABYLON.AbstractMesh = AbstractMesh;
  9768. })(BABYLON || (BABYLON = {}));
  9769. //# sourceMappingURL=babylon.abstractMesh.js.map
  9770. var BABYLON;
  9771. (function (BABYLON) {
  9772. var _InstancesBatch = (function () {
  9773. function _InstancesBatch() {
  9774. this.mustReturn = false;
  9775. this.visibleInstances = new Array();
  9776. this.renderSelf = new Array();
  9777. }
  9778. return _InstancesBatch;
  9779. })();
  9780. BABYLON._InstancesBatch = _InstancesBatch;
  9781. var Mesh = (function (_super) {
  9782. __extends(Mesh, _super);
  9783. /**
  9784. * @constructor
  9785. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9786. * @param {Scene} scene - The scene to add this mesh to.
  9787. * @param {Node} parent - The parent of this mesh, if it has one
  9788. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9789. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9790. * When false, achieved by calling a clone(), also passing False.
  9791. * This will make creation of children, recursive.
  9792. */
  9793. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9794. if (parent === void 0) { parent = null; }
  9795. _super.call(this, name, scene);
  9796. // Members
  9797. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9798. this.instances = new Array();
  9799. this._LODLevels = new Array();
  9800. this._onBeforeRenderCallbacks = new Array();
  9801. this._onAfterRenderCallbacks = new Array();
  9802. this._visibleInstances = {};
  9803. this._renderIdForInstances = new Array();
  9804. this._batchCache = new _InstancesBatch();
  9805. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  9806. if (source) {
  9807. // Geometry
  9808. if (source._geometry) {
  9809. source._geometry.applyToMesh(this);
  9810. }
  9811. // Deep copy
  9812. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9813. // Material
  9814. this.material = source.material;
  9815. if (!doNotCloneChildren) {
  9816. for (var index = 0; index < scene.meshes.length; index++) {
  9817. var mesh = scene.meshes[index];
  9818. if (mesh.parent === source) {
  9819. // doNotCloneChildren is always going to be False
  9820. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  9821. }
  9822. }
  9823. }
  9824. for (index = 0; index < scene.particleSystems.length; index++) {
  9825. var system = scene.particleSystems[index];
  9826. if (system.emitter === source) {
  9827. system.clone(system.name, this);
  9828. }
  9829. }
  9830. this.computeWorldMatrix(true);
  9831. }
  9832. // Parent
  9833. if (parent !== null) {
  9834. this.parent = parent;
  9835. }
  9836. }
  9837. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  9838. // Methods
  9839. get: function () {
  9840. return this._LODLevels.length > 0;
  9841. },
  9842. enumerable: true,
  9843. configurable: true
  9844. });
  9845. Mesh.prototype._sortLODLevels = function () {
  9846. this._LODLevels.sort(function (a, b) {
  9847. if (a.distance < b.distance) {
  9848. return 1;
  9849. }
  9850. if (a.distance > b.distance) {
  9851. return -1;
  9852. }
  9853. return 0;
  9854. });
  9855. };
  9856. /**
  9857. * Add a mesh as LOD level triggered at the given distance.
  9858. * @param {number} distance - the distance from the center of the object to show this level
  9859. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  9860. * @return {BABYLON.Mesh} this mesh (for chaining)
  9861. */
  9862. Mesh.prototype.addLODLevel = function (distance, mesh) {
  9863. if (mesh && mesh._masterMesh) {
  9864. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  9865. return this;
  9866. }
  9867. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  9868. this._LODLevels.push(level);
  9869. if (mesh) {
  9870. mesh._masterMesh = this;
  9871. }
  9872. this._sortLODLevels();
  9873. return this;
  9874. };
  9875. /**
  9876. * Remove a mesh from the LOD array
  9877. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  9878. * @return {BABYLON.Mesh} this mesh (for chaining)
  9879. */
  9880. Mesh.prototype.removeLODLevel = function (mesh) {
  9881. for (var index = 0; index < this._LODLevels.length; index++) {
  9882. if (this._LODLevels[index].mesh === mesh) {
  9883. this._LODLevels.splice(index, 1);
  9884. if (mesh) {
  9885. mesh._masterMesh = null;
  9886. }
  9887. }
  9888. }
  9889. this._sortLODLevels();
  9890. return this;
  9891. };
  9892. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9893. if (!this._LODLevels || this._LODLevels.length === 0) {
  9894. return this;
  9895. }
  9896. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  9897. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  9898. return this;
  9899. }
  9900. for (var index = 0; index < this._LODLevels.length; index++) {
  9901. var level = this._LODLevels[index];
  9902. if (level.distance < distanceToCamera) {
  9903. if (level.mesh) {
  9904. level.mesh._preActivate();
  9905. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9906. }
  9907. return level.mesh;
  9908. }
  9909. }
  9910. return this;
  9911. };
  9912. Object.defineProperty(Mesh.prototype, "geometry", {
  9913. get: function () {
  9914. return this._geometry;
  9915. },
  9916. enumerable: true,
  9917. configurable: true
  9918. });
  9919. Mesh.prototype.getTotalVertices = function () {
  9920. if (!this._geometry) {
  9921. return 0;
  9922. }
  9923. return this._geometry.getTotalVertices();
  9924. };
  9925. Mesh.prototype.getVerticesData = function (kind) {
  9926. if (!this._geometry) {
  9927. return null;
  9928. }
  9929. return this._geometry.getVerticesData(kind);
  9930. };
  9931. Mesh.prototype.getVertexBuffer = function (kind) {
  9932. if (!this._geometry) {
  9933. return undefined;
  9934. }
  9935. return this._geometry.getVertexBuffer(kind);
  9936. };
  9937. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9938. if (!this._geometry) {
  9939. if (this._delayInfo) {
  9940. return this._delayInfo.indexOf(kind) !== -1;
  9941. }
  9942. return false;
  9943. }
  9944. return this._geometry.isVerticesDataPresent(kind);
  9945. };
  9946. Mesh.prototype.getVerticesDataKinds = function () {
  9947. if (!this._geometry) {
  9948. var result = [];
  9949. if (this._delayInfo) {
  9950. for (var kind in this._delayInfo) {
  9951. result.push(kind);
  9952. }
  9953. }
  9954. return result;
  9955. }
  9956. return this._geometry.getVerticesDataKinds();
  9957. };
  9958. Mesh.prototype.getTotalIndices = function () {
  9959. if (!this._geometry) {
  9960. return 0;
  9961. }
  9962. return this._geometry.getTotalIndices();
  9963. };
  9964. Mesh.prototype.getIndices = function () {
  9965. if (!this._geometry) {
  9966. return [];
  9967. }
  9968. return this._geometry.getIndices();
  9969. };
  9970. Object.defineProperty(Mesh.prototype, "isBlocked", {
  9971. get: function () {
  9972. return this._masterMesh !== null && this._masterMesh !== undefined;
  9973. },
  9974. enumerable: true,
  9975. configurable: true
  9976. });
  9977. Mesh.prototype.isReady = function () {
  9978. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9979. return false;
  9980. }
  9981. return _super.prototype.isReady.call(this);
  9982. };
  9983. Mesh.prototype.isDisposed = function () {
  9984. return this._isDisposed;
  9985. };
  9986. // Methods
  9987. Mesh.prototype._preActivate = function () {
  9988. var sceneRenderId = this.getScene().getRenderId();
  9989. if (this._preActivateId == sceneRenderId) {
  9990. return;
  9991. }
  9992. this._preActivateId = sceneRenderId;
  9993. this._visibleInstances = null;
  9994. };
  9995. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  9996. if (!this._visibleInstances) {
  9997. this._visibleInstances = {};
  9998. this._visibleInstances.defaultRenderId = renderId;
  9999. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10000. }
  10001. if (!this._visibleInstances[renderId]) {
  10002. this._visibleInstances[renderId] = new Array();
  10003. }
  10004. this._visibleInstances[renderId].push(instance);
  10005. };
  10006. Mesh.prototype.refreshBoundingInfo = function () {
  10007. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10008. if (data) {
  10009. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10010. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10011. }
  10012. if (this.subMeshes) {
  10013. for (var index = 0; index < this.subMeshes.length; index++) {
  10014. this.subMeshes[index].refreshBoundingInfo();
  10015. }
  10016. }
  10017. this._updateBoundingInfo();
  10018. };
  10019. Mesh.prototype._createGlobalSubMesh = function () {
  10020. var totalVertices = this.getTotalVertices();
  10021. if (!totalVertices || !this.getIndices()) {
  10022. return null;
  10023. }
  10024. this.releaseSubMeshes();
  10025. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10026. };
  10027. Mesh.prototype.subdivide = function (count) {
  10028. if (count < 1) {
  10029. return;
  10030. }
  10031. var totalIndices = this.getTotalIndices();
  10032. var subdivisionSize = (totalIndices / count) | 0;
  10033. var offset = 0;
  10034. while (subdivisionSize % 3 != 0) {
  10035. subdivisionSize++;
  10036. }
  10037. this.releaseSubMeshes();
  10038. for (var index = 0; index < count; index++) {
  10039. if (offset >= totalIndices) {
  10040. break;
  10041. }
  10042. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10043. offset += subdivisionSize;
  10044. }
  10045. this.synchronizeInstances();
  10046. };
  10047. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10048. if (kind instanceof Array) {
  10049. var temp = data;
  10050. data = kind;
  10051. kind = temp;
  10052. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10053. }
  10054. if (!this._geometry) {
  10055. var vertexData = new BABYLON.VertexData();
  10056. vertexData.set(data, kind);
  10057. var scene = this.getScene();
  10058. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10059. }
  10060. else {
  10061. this._geometry.setVerticesData(kind, data, updatable, stride);
  10062. }
  10063. };
  10064. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10065. if (!this._geometry) {
  10066. return;
  10067. }
  10068. if (!makeItUnique) {
  10069. this._geometry.updateVerticesData(kind, data, updateExtends);
  10070. }
  10071. else {
  10072. this.makeGeometryUnique();
  10073. this.updateVerticesData(kind, data, updateExtends, false);
  10074. }
  10075. };
  10076. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10077. if (!this._geometry) {
  10078. return;
  10079. }
  10080. if (!makeItUnique) {
  10081. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10082. }
  10083. else {
  10084. this.makeGeometryUnique();
  10085. this.updateVerticesDataDirectly(kind, data, offset, false);
  10086. }
  10087. };
  10088. Mesh.prototype.makeGeometryUnique = function () {
  10089. if (!this._geometry) {
  10090. return;
  10091. }
  10092. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10093. geometry.applyToMesh(this);
  10094. };
  10095. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10096. if (!this._geometry) {
  10097. var vertexData = new BABYLON.VertexData();
  10098. vertexData.indices = indices;
  10099. var scene = this.getScene();
  10100. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10101. }
  10102. else {
  10103. this._geometry.setIndices(indices, totalVertices);
  10104. }
  10105. };
  10106. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10107. var engine = this.getScene().getEngine();
  10108. // Wireframe
  10109. var indexToBind;
  10110. switch (fillMode) {
  10111. case BABYLON.Material.PointFillMode:
  10112. indexToBind = null;
  10113. break;
  10114. case BABYLON.Material.WireFrameFillMode:
  10115. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10116. break;
  10117. default:
  10118. case BABYLON.Material.TriangleFillMode:
  10119. indexToBind = this._geometry.getIndexBuffer();
  10120. break;
  10121. }
  10122. // VBOs
  10123. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10124. };
  10125. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10126. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10127. return;
  10128. }
  10129. var engine = this.getScene().getEngine();
  10130. switch (fillMode) {
  10131. case BABYLON.Material.PointFillMode:
  10132. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10133. break;
  10134. case BABYLON.Material.WireFrameFillMode:
  10135. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10136. break;
  10137. default:
  10138. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10139. }
  10140. };
  10141. Mesh.prototype.registerBeforeRender = function (func) {
  10142. this._onBeforeRenderCallbacks.push(func);
  10143. };
  10144. Mesh.prototype.unregisterBeforeRender = function (func) {
  10145. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10146. if (index > -1) {
  10147. this._onBeforeRenderCallbacks.splice(index, 1);
  10148. }
  10149. };
  10150. Mesh.prototype.registerAfterRender = function (func) {
  10151. this._onAfterRenderCallbacks.push(func);
  10152. };
  10153. Mesh.prototype.unregisterAfterRender = function (func) {
  10154. var index = this._onAfterRenderCallbacks.indexOf(func);
  10155. if (index > -1) {
  10156. this._onAfterRenderCallbacks.splice(index, 1);
  10157. }
  10158. };
  10159. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10160. var scene = this.getScene();
  10161. this._batchCache.mustReturn = false;
  10162. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10163. this._batchCache.visibleInstances[subMeshId] = null;
  10164. if (this._visibleInstances) {
  10165. var currentRenderId = scene.getRenderId();
  10166. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10167. var selfRenderId = this._renderId;
  10168. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10169. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10170. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10171. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10172. }
  10173. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10174. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10175. this._batchCache.mustReturn = true;
  10176. return this._batchCache;
  10177. }
  10178. if (currentRenderId !== selfRenderId) {
  10179. this._batchCache.renderSelf[subMeshId] = false;
  10180. }
  10181. }
  10182. this._renderIdForInstances[subMeshId] = currentRenderId;
  10183. }
  10184. return this._batchCache;
  10185. };
  10186. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10187. var visibleInstances = batch.visibleInstances[subMesh._id];
  10188. var matricesCount = visibleInstances.length + 1;
  10189. var bufferSize = matricesCount * 16 * 4;
  10190. while (this._instancesBufferSize < bufferSize) {
  10191. this._instancesBufferSize *= 2;
  10192. }
  10193. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10194. if (this._worldMatricesInstancesBuffer) {
  10195. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10196. }
  10197. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10198. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10199. }
  10200. var offset = 0;
  10201. var instancesCount = 0;
  10202. var world = this.getWorldMatrix();
  10203. if (batch.renderSelf[subMesh._id]) {
  10204. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10205. offset += 16;
  10206. instancesCount++;
  10207. }
  10208. if (visibleInstances) {
  10209. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10210. var instance = visibleInstances[instanceIndex];
  10211. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10212. offset += 16;
  10213. instancesCount++;
  10214. }
  10215. }
  10216. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10217. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10218. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10219. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10220. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10221. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10222. this._draw(subMesh, fillMode, instancesCount);
  10223. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10224. };
  10225. Mesh.prototype.render = function (subMesh) {
  10226. var scene = this.getScene();
  10227. // Managing instances
  10228. var batch = this._getInstancesRenderList(subMesh._id);
  10229. if (batch.mustReturn) {
  10230. return;
  10231. }
  10232. // Checking geometry state
  10233. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10234. return;
  10235. }
  10236. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10237. this._onBeforeRenderCallbacks[callbackIndex]();
  10238. }
  10239. var engine = scene.getEngine();
  10240. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10241. // Material
  10242. var effectiveMaterial = subMesh.getMaterial();
  10243. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10244. return;
  10245. }
  10246. // Outline - step 1
  10247. var savedDepthWrite = engine.getDepthWrite();
  10248. if (this.renderOutline) {
  10249. engine.setDepthWrite(false);
  10250. scene.getOutlineRenderer().render(subMesh, batch);
  10251. engine.setDepthWrite(savedDepthWrite);
  10252. }
  10253. effectiveMaterial._preBind();
  10254. var effect = effectiveMaterial.getEffect();
  10255. // Bind
  10256. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10257. this._bind(subMesh, effect, fillMode);
  10258. var world = this.getWorldMatrix();
  10259. effectiveMaterial.bind(world, this);
  10260. // Instances rendering
  10261. if (hardwareInstancedRendering) {
  10262. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10263. }
  10264. else {
  10265. if (batch.renderSelf[subMesh._id]) {
  10266. // Draw
  10267. this._draw(subMesh, fillMode);
  10268. }
  10269. if (batch.visibleInstances[subMesh._id]) {
  10270. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10271. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10272. // World
  10273. world = instance.getWorldMatrix();
  10274. effectiveMaterial.bindOnlyWorldMatrix(world);
  10275. // Draw
  10276. this._draw(subMesh, fillMode);
  10277. }
  10278. }
  10279. }
  10280. // Unbind
  10281. effectiveMaterial.unbind();
  10282. // Outline - step 2
  10283. if (this.renderOutline && savedDepthWrite) {
  10284. engine.setDepthWrite(true);
  10285. engine.setColorWrite(false);
  10286. scene.getOutlineRenderer().render(subMesh, batch);
  10287. engine.setColorWrite(true);
  10288. }
  10289. // Overlay
  10290. if (this.renderOverlay) {
  10291. var currentMode = engine.getAlphaMode();
  10292. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10293. scene.getOutlineRenderer().render(subMesh, batch, true);
  10294. engine.setAlphaMode(currentMode);
  10295. }
  10296. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10297. this._onAfterRenderCallbacks[callbackIndex]();
  10298. }
  10299. };
  10300. Mesh.prototype.getEmittedParticleSystems = function () {
  10301. var results = new Array();
  10302. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10303. var particleSystem = this.getScene().particleSystems[index];
  10304. if (particleSystem.emitter === this) {
  10305. results.push(particleSystem);
  10306. }
  10307. }
  10308. return results;
  10309. };
  10310. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10311. var results = new Array();
  10312. var descendants = this.getDescendants();
  10313. descendants.push(this);
  10314. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10315. var particleSystem = this.getScene().particleSystems[index];
  10316. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10317. results.push(particleSystem);
  10318. }
  10319. }
  10320. return results;
  10321. };
  10322. Mesh.prototype.getChildren = function () {
  10323. var results = [];
  10324. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10325. var mesh = this.getScene().meshes[index];
  10326. if (mesh.parent == this) {
  10327. results.push(mesh);
  10328. }
  10329. }
  10330. return results;
  10331. };
  10332. Mesh.prototype._checkDelayState = function () {
  10333. var _this = this;
  10334. var that = this;
  10335. var scene = this.getScene();
  10336. if (this._geometry) {
  10337. this._geometry.load(scene);
  10338. }
  10339. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10340. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10341. scene._addPendingData(that);
  10342. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  10343. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  10344. if (data instanceof ArrayBuffer) {
  10345. _this._delayLoadingFunction(data, _this);
  10346. }
  10347. else {
  10348. _this._delayLoadingFunction(JSON.parse(data), _this);
  10349. }
  10350. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10351. scene._removePendingData(_this);
  10352. }, function () {
  10353. }, scene.database, getBinaryData);
  10354. }
  10355. };
  10356. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  10357. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10358. return false;
  10359. }
  10360. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  10361. return false;
  10362. }
  10363. this._checkDelayState();
  10364. return true;
  10365. };
  10366. Mesh.prototype.setMaterialByID = function (id) {
  10367. var materials = this.getScene().materials;
  10368. for (var index = 0; index < materials.length; index++) {
  10369. if (materials[index].id == id) {
  10370. this.material = materials[index];
  10371. return;
  10372. }
  10373. }
  10374. // Multi
  10375. var multiMaterials = this.getScene().multiMaterials;
  10376. for (index = 0; index < multiMaterials.length; index++) {
  10377. if (multiMaterials[index].id == id) {
  10378. this.material = multiMaterials[index];
  10379. return;
  10380. }
  10381. }
  10382. };
  10383. Mesh.prototype.getAnimatables = function () {
  10384. var results = [];
  10385. if (this.material) {
  10386. results.push(this.material);
  10387. }
  10388. if (this.skeleton) {
  10389. results.push(this.skeleton);
  10390. }
  10391. return results;
  10392. };
  10393. // Geometry
  10394. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  10395. // Position
  10396. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  10397. return;
  10398. }
  10399. this._resetPointsArrayCache();
  10400. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10401. var temp = [];
  10402. for (var index = 0; index < data.length; index += 3) {
  10403. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10404. }
  10405. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  10406. // Normals
  10407. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  10408. return;
  10409. }
  10410. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10411. for (index = 0; index < data.length; index += 3) {
  10412. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10413. }
  10414. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  10415. };
  10416. // Cache
  10417. Mesh.prototype._resetPointsArrayCache = function () {
  10418. this._positions = null;
  10419. };
  10420. Mesh.prototype._generatePointsArray = function () {
  10421. if (this._positions)
  10422. return true;
  10423. this._positions = [];
  10424. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10425. if (!data) {
  10426. return false;
  10427. }
  10428. for (var index = 0; index < data.length; index += 3) {
  10429. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  10430. }
  10431. return true;
  10432. };
  10433. // Clone
  10434. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10435. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  10436. };
  10437. // Dispose
  10438. Mesh.prototype.dispose = function (doNotRecurse) {
  10439. if (this._geometry) {
  10440. this._geometry.releaseForMesh(this, true);
  10441. }
  10442. // Instances
  10443. if (this._worldMatricesInstancesBuffer) {
  10444. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10445. this._worldMatricesInstancesBuffer = null;
  10446. }
  10447. while (this.instances.length) {
  10448. this.instances[0].dispose();
  10449. }
  10450. _super.prototype.dispose.call(this, doNotRecurse);
  10451. };
  10452. // Geometric tools
  10453. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  10454. var _this = this;
  10455. var scene = this.getScene();
  10456. var onload = function (img) {
  10457. // Getting height map data
  10458. var canvas = document.createElement("canvas");
  10459. var context = canvas.getContext("2d");
  10460. var heightMapWidth = img.width;
  10461. var heightMapHeight = img.height;
  10462. canvas.width = heightMapWidth;
  10463. canvas.height = heightMapHeight;
  10464. context.drawImage(img, 0, 0);
  10465. // Create VertexData from map data
  10466. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10467. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  10468. //execute success callback, if set
  10469. if (onSuccess) {
  10470. onSuccess(_this);
  10471. }
  10472. };
  10473. BABYLON.Tools.LoadImage(url, onload, function () {
  10474. }, scene.database);
  10475. };
  10476. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  10477. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10478. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  10479. return;
  10480. }
  10481. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10482. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10483. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  10484. var position = BABYLON.Vector3.Zero();
  10485. var normal = BABYLON.Vector3.Zero();
  10486. var uv = BABYLON.Vector2.Zero();
  10487. for (var index = 0; index < positions.length; index += 3) {
  10488. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  10489. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  10490. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  10491. // Compute height
  10492. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  10493. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  10494. var pos = (u + v * heightMapWidth) * 4;
  10495. var r = buffer[pos] / 255.0;
  10496. var g = buffer[pos + 1] / 255.0;
  10497. var b = buffer[pos + 2] / 255.0;
  10498. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  10499. normal.normalize();
  10500. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  10501. position = position.add(normal);
  10502. position.toArray(positions, index);
  10503. }
  10504. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  10505. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  10506. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  10507. };
  10508. Mesh.prototype.convertToFlatShadedMesh = function () {
  10509. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  10510. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  10511. var kinds = this.getVerticesDataKinds();
  10512. var vbs = [];
  10513. var data = [];
  10514. var newdata = [];
  10515. var updatableNormals = false;
  10516. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10517. var kind = kinds[kindIndex];
  10518. var vertexBuffer = this.getVertexBuffer(kind);
  10519. if (kind === BABYLON.VertexBuffer.NormalKind) {
  10520. updatableNormals = vertexBuffer.isUpdatable();
  10521. kinds.splice(kindIndex, 1);
  10522. kindIndex--;
  10523. continue;
  10524. }
  10525. vbs[kind] = vertexBuffer;
  10526. data[kind] = vbs[kind].getData();
  10527. newdata[kind] = [];
  10528. }
  10529. // Save previous submeshes
  10530. var previousSubmeshes = this.subMeshes.slice(0);
  10531. var indices = this.getIndices();
  10532. var totalIndices = this.getTotalIndices();
  10533. for (var index = 0; index < totalIndices; index++) {
  10534. var vertexIndex = indices[index];
  10535. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10536. kind = kinds[kindIndex];
  10537. var stride = vbs[kind].getStrideSize();
  10538. for (var offset = 0; offset < stride; offset++) {
  10539. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  10540. }
  10541. }
  10542. }
  10543. // Updating faces & normal
  10544. var normals = [];
  10545. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  10546. for (index = 0; index < totalIndices; index += 3) {
  10547. indices[index] = index;
  10548. indices[index + 1] = index + 1;
  10549. indices[index + 2] = index + 2;
  10550. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  10551. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  10552. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  10553. var p1p2 = p1.subtract(p2);
  10554. var p3p2 = p3.subtract(p2);
  10555. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  10556. for (var localIndex = 0; localIndex < 3; localIndex++) {
  10557. normals.push(normal.x);
  10558. normals.push(normal.y);
  10559. normals.push(normal.z);
  10560. }
  10561. }
  10562. this.setIndices(indices);
  10563. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  10564. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10565. kind = kinds[kindIndex];
  10566. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  10567. }
  10568. // Updating submeshes
  10569. this.releaseSubMeshes();
  10570. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  10571. var previousOne = previousSubmeshes[submeshIndex];
  10572. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  10573. }
  10574. this.synchronizeInstances();
  10575. };
  10576. // Instances
  10577. Mesh.prototype.createInstance = function (name) {
  10578. return new BABYLON.InstancedMesh(name, this);
  10579. };
  10580. Mesh.prototype.synchronizeInstances = function () {
  10581. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  10582. var instance = this.instances[instanceIndex];
  10583. instance._syncSubMeshes();
  10584. }
  10585. };
  10586. /**
  10587. * Simplify the mesh according to the given array of settings.
  10588. * Function will return immediately and will simplify async.
  10589. * @param settings a collection of simplification settings.
  10590. * @param parallelProcessing should all levels calculate parallel or one after the other.
  10591. * @param type the type of simplification to run.
  10592. * successCallback optional success callback to be called after the simplification finished processing all settings.
  10593. */
  10594. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  10595. var _this = this;
  10596. if (parallelProcessing === void 0) { parallelProcessing = true; }
  10597. if (type === void 0) { type = 0 /* QUADRATIC */; }
  10598. var getSimplifier = function () {
  10599. switch (type) {
  10600. case 0 /* QUADRATIC */:
  10601. default:
  10602. return new BABYLON.QuadraticErrorSimplification(_this);
  10603. }
  10604. };
  10605. if (parallelProcessing) {
  10606. //parallel simplifier
  10607. settings.forEach(function (setting) {
  10608. var simplifier = getSimplifier();
  10609. simplifier.simplify(setting, function (newMesh) {
  10610. _this.addLODLevel(setting.distance, newMesh);
  10611. //check if it is the last
  10612. if (setting.quality == settings[settings.length - 1].quality && successCallback) {
  10613. //all done, run the success callback.
  10614. successCallback();
  10615. }
  10616. });
  10617. });
  10618. }
  10619. else {
  10620. //single simplifier.
  10621. var simplifier = getSimplifier();
  10622. var runDecimation = function (setting, callback) {
  10623. simplifier.simplify(setting, function (newMesh) {
  10624. _this.addLODLevel(setting.distance, newMesh);
  10625. //run the next quality level
  10626. callback();
  10627. });
  10628. };
  10629. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  10630. runDecimation(settings[loop.index], function () {
  10631. loop.executeNext();
  10632. });
  10633. }, function () {
  10634. //execution ended, run the success callback.
  10635. if (successCallback) {
  10636. successCallback();
  10637. }
  10638. });
  10639. }
  10640. };
  10641. // Statics
  10642. Mesh.CreateBox = function (name, size, scene, updatable) {
  10643. var box = new Mesh(name, scene);
  10644. var vertexData = BABYLON.VertexData.CreateBox(size);
  10645. vertexData.applyToMesh(box, updatable);
  10646. return box;
  10647. };
  10648. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  10649. var sphere = new Mesh(name, scene);
  10650. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  10651. vertexData.applyToMesh(sphere, updatable);
  10652. return sphere;
  10653. };
  10654. // Cylinder and cone (Code inspired by SharpDX.org)
  10655. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  10656. // subdivisions is a new parameter, we need to support old signature
  10657. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  10658. if (scene !== undefined) {
  10659. updatable = scene;
  10660. }
  10661. scene = subdivisions;
  10662. subdivisions = 1;
  10663. }
  10664. var cylinder = new Mesh(name, scene);
  10665. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  10666. vertexData.applyToMesh(cylinder, updatable);
  10667. return cylinder;
  10668. };
  10669. // Torus (Code from SharpDX.org)
  10670. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  10671. var torus = new Mesh(name, scene);
  10672. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  10673. vertexData.applyToMesh(torus, updatable);
  10674. return torus;
  10675. };
  10676. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  10677. var torusKnot = new Mesh(name, scene);
  10678. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  10679. vertexData.applyToMesh(torusKnot, updatable);
  10680. return torusKnot;
  10681. };
  10682. // Lines
  10683. Mesh.CreateLines = function (name, points, scene, updatable) {
  10684. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  10685. var vertexData = BABYLON.VertexData.CreateLines(points);
  10686. vertexData.applyToMesh(lines, updatable);
  10687. return lines;
  10688. };
  10689. // Plane & ground
  10690. Mesh.CreatePlane = function (name, size, scene, updatable) {
  10691. var plane = new Mesh(name, scene);
  10692. var vertexData = BABYLON.VertexData.CreatePlane(size);
  10693. vertexData.applyToMesh(plane, updatable);
  10694. return plane;
  10695. };
  10696. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10697. var ground = new BABYLON.GroundMesh(name, scene);
  10698. ground._setReady(false);
  10699. ground._subdivisions = subdivisions;
  10700. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10701. vertexData.applyToMesh(ground, updatable);
  10702. ground._setReady(true);
  10703. return ground;
  10704. };
  10705. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10706. var tiledGround = new Mesh(name, scene);
  10707. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10708. vertexData.applyToMesh(tiledGround, updatable);
  10709. return tiledGround;
  10710. };
  10711. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  10712. var ground = new BABYLON.GroundMesh(name, scene);
  10713. ground._subdivisions = subdivisions;
  10714. ground._setReady(false);
  10715. var onload = function (img) {
  10716. // Getting height map data
  10717. var canvas = document.createElement("canvas");
  10718. var context = canvas.getContext("2d");
  10719. var heightMapWidth = img.width;
  10720. var heightMapHeight = img.height;
  10721. canvas.width = heightMapWidth;
  10722. canvas.height = heightMapHeight;
  10723. context.drawImage(img, 0, 0);
  10724. // Create VertexData from map data
  10725. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10726. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10727. vertexData.applyToMesh(ground, updatable);
  10728. ground._setReady(true);
  10729. //execute ready callback, if set
  10730. if (onReady) {
  10731. onReady(ground);
  10732. }
  10733. };
  10734. BABYLON.Tools.LoadImage(url, onload, function () {
  10735. }, scene.database);
  10736. return ground;
  10737. };
  10738. // Tools
  10739. Mesh.MinMax = function (meshes) {
  10740. var minVector = null;
  10741. var maxVector = null;
  10742. for (var i in meshes) {
  10743. var mesh = meshes[i];
  10744. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10745. if (!minVector) {
  10746. minVector = boundingBox.minimumWorld;
  10747. maxVector = boundingBox.maximumWorld;
  10748. continue;
  10749. }
  10750. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10751. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10752. }
  10753. return {
  10754. min: minVector,
  10755. max: maxVector
  10756. };
  10757. };
  10758. Mesh.Center = function (meshesOrMinMaxVector) {
  10759. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  10760. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10761. };
  10762. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10763. if (disposeSource === void 0) { disposeSource = true; }
  10764. var source = meshes[0];
  10765. var material = source.material;
  10766. var scene = source.getScene();
  10767. if (!allow32BitsIndices) {
  10768. var totalVertices = 0;
  10769. for (var index = 0; index < meshes.length; index++) {
  10770. totalVertices += meshes[index].getTotalVertices();
  10771. if (totalVertices > 65536) {
  10772. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  10773. return null;
  10774. }
  10775. }
  10776. }
  10777. // Merge
  10778. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  10779. vertexData.transform(source.getWorldMatrix());
  10780. for (index = 1; index < meshes.length; index++) {
  10781. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  10782. otherVertexData.transform(meshes[index].getWorldMatrix());
  10783. vertexData.merge(otherVertexData);
  10784. }
  10785. var newMesh = new Mesh(source.name + "_merged", scene);
  10786. vertexData.applyToMesh(newMesh);
  10787. // Setting properties
  10788. newMesh.material = material;
  10789. newMesh.checkCollisions = source.checkCollisions;
  10790. // Cleaning
  10791. if (disposeSource) {
  10792. for (index = 0; index < meshes.length; index++) {
  10793. meshes[index].dispose();
  10794. }
  10795. }
  10796. return newMesh;
  10797. };
  10798. return Mesh;
  10799. })(BABYLON.AbstractMesh);
  10800. BABYLON.Mesh = Mesh;
  10801. })(BABYLON || (BABYLON = {}));
  10802. //# sourceMappingURL=babylon.mesh.js.map
  10803. var BABYLON;
  10804. (function (BABYLON) {
  10805. var GroundMesh = (function (_super) {
  10806. __extends(GroundMesh, _super);
  10807. function GroundMesh(name, scene) {
  10808. _super.call(this, name, scene);
  10809. this.generateOctree = false;
  10810. this._worldInverse = new BABYLON.Matrix();
  10811. }
  10812. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  10813. get: function () {
  10814. return this._subdivisions;
  10815. },
  10816. enumerable: true,
  10817. configurable: true
  10818. });
  10819. GroundMesh.prototype.optimize = function (chunksCount) {
  10820. this.subdivide(this._subdivisions);
  10821. this.createOrUpdateSubmeshesOctree(32);
  10822. };
  10823. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  10824. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  10825. this.getWorldMatrix().invertToRef(this._worldInverse);
  10826. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  10827. var pickInfo = this.intersects(ray);
  10828. if (pickInfo.hit) {
  10829. return pickInfo.pickedPoint.y;
  10830. }
  10831. return 0;
  10832. };
  10833. return GroundMesh;
  10834. })(BABYLON.Mesh);
  10835. BABYLON.GroundMesh = GroundMesh;
  10836. })(BABYLON || (BABYLON = {}));
  10837. //# sourceMappingURL=babylon.groundMesh.js.map
  10838. var BABYLON;
  10839. (function (BABYLON) {
  10840. /**
  10841. * Creates an instance based on a source mesh.
  10842. */
  10843. var InstancedMesh = (function (_super) {
  10844. __extends(InstancedMesh, _super);
  10845. function InstancedMesh(name, source) {
  10846. _super.call(this, name, source.getScene());
  10847. source.instances.push(this);
  10848. this._sourceMesh = source;
  10849. this.position.copyFrom(source.position);
  10850. this.rotation.copyFrom(source.rotation);
  10851. this.scaling.copyFrom(source.scaling);
  10852. if (source.rotationQuaternion) {
  10853. this.rotationQuaternion = source.rotationQuaternion.clone();
  10854. }
  10855. this.infiniteDistance = source.infiniteDistance;
  10856. this.setPivotMatrix(source.getPivotMatrix());
  10857. this.refreshBoundingInfo();
  10858. this._syncSubMeshes();
  10859. }
  10860. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  10861. // Methods
  10862. get: function () {
  10863. return this._sourceMesh.receiveShadows;
  10864. },
  10865. enumerable: true,
  10866. configurable: true
  10867. });
  10868. Object.defineProperty(InstancedMesh.prototype, "material", {
  10869. get: function () {
  10870. return this._sourceMesh.material;
  10871. },
  10872. enumerable: true,
  10873. configurable: true
  10874. });
  10875. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  10876. get: function () {
  10877. return this._sourceMesh.visibility;
  10878. },
  10879. enumerable: true,
  10880. configurable: true
  10881. });
  10882. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  10883. get: function () {
  10884. return this._sourceMesh.skeleton;
  10885. },
  10886. enumerable: true,
  10887. configurable: true
  10888. });
  10889. InstancedMesh.prototype.getTotalVertices = function () {
  10890. return this._sourceMesh.getTotalVertices();
  10891. };
  10892. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  10893. get: function () {
  10894. return this._sourceMesh;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. InstancedMesh.prototype.getVerticesData = function (kind) {
  10900. return this._sourceMesh.getVerticesData(kind);
  10901. };
  10902. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  10903. return this._sourceMesh.isVerticesDataPresent(kind);
  10904. };
  10905. InstancedMesh.prototype.getIndices = function () {
  10906. return this._sourceMesh.getIndices();
  10907. };
  10908. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  10909. get: function () {
  10910. return this._sourceMesh._positions;
  10911. },
  10912. enumerable: true,
  10913. configurable: true
  10914. });
  10915. InstancedMesh.prototype.refreshBoundingInfo = function () {
  10916. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10917. if (data) {
  10918. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  10919. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10920. }
  10921. this._updateBoundingInfo();
  10922. };
  10923. InstancedMesh.prototype._preActivate = function () {
  10924. if (this._currentLOD) {
  10925. this._currentLOD._preActivate();
  10926. }
  10927. };
  10928. InstancedMesh.prototype._activate = function (renderId) {
  10929. if (this._currentLOD) {
  10930. this._currentLOD._registerInstanceForRenderId(this, renderId);
  10931. }
  10932. };
  10933. InstancedMesh.prototype.getLOD = function (camera) {
  10934. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  10935. if (this._currentLOD === this.sourceMesh) {
  10936. return this;
  10937. }
  10938. return this._currentLOD;
  10939. };
  10940. InstancedMesh.prototype._syncSubMeshes = function () {
  10941. this.releaseSubMeshes();
  10942. if (this._sourceMesh.subMeshes) {
  10943. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  10944. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  10945. }
  10946. }
  10947. };
  10948. InstancedMesh.prototype._generatePointsArray = function () {
  10949. return this._sourceMesh._generatePointsArray();
  10950. };
  10951. // Clone
  10952. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10953. var result = this._sourceMesh.createInstance(name);
  10954. // Deep copy
  10955. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  10956. // Bounding info
  10957. this.refreshBoundingInfo();
  10958. // Parent
  10959. if (newParent) {
  10960. result.parent = newParent;
  10961. }
  10962. if (!doNotCloneChildren) {
  10963. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10964. var mesh = this.getScene().meshes[index];
  10965. if (mesh.parent === this) {
  10966. mesh.clone(mesh.name, result);
  10967. }
  10968. }
  10969. }
  10970. result.computeWorldMatrix(true);
  10971. return result;
  10972. };
  10973. // Dispoe
  10974. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  10975. // Remove from mesh
  10976. var index = this._sourceMesh.instances.indexOf(this);
  10977. this._sourceMesh.instances.splice(index, 1);
  10978. _super.prototype.dispose.call(this, doNotRecurse);
  10979. };
  10980. return InstancedMesh;
  10981. })(BABYLON.AbstractMesh);
  10982. BABYLON.InstancedMesh = InstancedMesh;
  10983. })(BABYLON || (BABYLON = {}));
  10984. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  10985. (function (BABYLON) {
  10986. var SubMesh = (function () {
  10987. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  10988. if (createBoundingBox === void 0) { createBoundingBox = true; }
  10989. this.materialIndex = materialIndex;
  10990. this.verticesStart = verticesStart;
  10991. this.verticesCount = verticesCount;
  10992. this.indexStart = indexStart;
  10993. this.indexCount = indexCount;
  10994. this._renderId = 0;
  10995. this._mesh = mesh;
  10996. this._renderingMesh = renderingMesh || mesh;
  10997. mesh.subMeshes.push(this);
  10998. this._id = mesh.subMeshes.length - 1;
  10999. if (createBoundingBox) {
  11000. this.refreshBoundingInfo();
  11001. }
  11002. }
  11003. SubMesh.prototype.getBoundingInfo = function () {
  11004. return this._boundingInfo;
  11005. };
  11006. SubMesh.prototype.getMesh = function () {
  11007. return this._mesh;
  11008. };
  11009. SubMesh.prototype.getRenderingMesh = function () {
  11010. return this._renderingMesh;
  11011. };
  11012. SubMesh.prototype.getMaterial = function () {
  11013. var rootMaterial = this._renderingMesh.material;
  11014. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11015. var multiMaterial = rootMaterial;
  11016. return multiMaterial.getSubMaterial(this.materialIndex);
  11017. }
  11018. if (!rootMaterial) {
  11019. return this._mesh.getScene().defaultMaterial;
  11020. }
  11021. return rootMaterial;
  11022. };
  11023. // Methods
  11024. SubMesh.prototype.refreshBoundingInfo = function () {
  11025. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11026. if (!data) {
  11027. this._boundingInfo = this._mesh._boundingInfo;
  11028. return;
  11029. }
  11030. var indices = this._renderingMesh.getIndices();
  11031. var extend;
  11032. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11033. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11034. }
  11035. else {
  11036. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11037. }
  11038. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11039. };
  11040. SubMesh.prototype._checkCollision = function (collider) {
  11041. return this._boundingInfo._checkCollision(collider);
  11042. };
  11043. SubMesh.prototype.updateBoundingInfo = function (world) {
  11044. if (!this._boundingInfo) {
  11045. this.refreshBoundingInfo();
  11046. }
  11047. this._boundingInfo._update(world);
  11048. };
  11049. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11050. return this._boundingInfo.isInFrustum(frustumPlanes);
  11051. };
  11052. SubMesh.prototype.render = function () {
  11053. this._renderingMesh.render(this);
  11054. };
  11055. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11056. if (!this._linesIndexBuffer) {
  11057. var linesIndices = [];
  11058. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11059. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11060. }
  11061. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11062. this.linesIndexCount = linesIndices.length;
  11063. }
  11064. return this._linesIndexBuffer;
  11065. };
  11066. SubMesh.prototype.canIntersects = function (ray) {
  11067. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11068. };
  11069. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11070. var intersectInfo = null;
  11071. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11072. var p0 = positions[indices[index]];
  11073. var p1 = positions[indices[index + 1]];
  11074. var p2 = positions[indices[index + 2]];
  11075. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11076. if (currentIntersectInfo) {
  11077. if (currentIntersectInfo.distance < 0) {
  11078. continue;
  11079. }
  11080. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11081. intersectInfo = currentIntersectInfo;
  11082. intersectInfo.faceId = index / 3;
  11083. if (fastCheck) {
  11084. break;
  11085. }
  11086. }
  11087. }
  11088. }
  11089. return intersectInfo;
  11090. };
  11091. // Clone
  11092. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11093. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11094. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11095. return result;
  11096. };
  11097. // Dispose
  11098. SubMesh.prototype.dispose = function () {
  11099. if (this._linesIndexBuffer) {
  11100. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11101. this._linesIndexBuffer = null;
  11102. }
  11103. // Remove from mesh
  11104. var index = this._mesh.subMeshes.indexOf(this);
  11105. this._mesh.subMeshes.splice(index, 1);
  11106. };
  11107. // Statics
  11108. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11109. var minVertexIndex = Number.MAX_VALUE;
  11110. var maxVertexIndex = -Number.MAX_VALUE;
  11111. renderingMesh = renderingMesh || mesh;
  11112. var indices = renderingMesh.getIndices();
  11113. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11114. var vertexIndex = indices[index];
  11115. if (vertexIndex < minVertexIndex)
  11116. minVertexIndex = vertexIndex;
  11117. if (vertexIndex > maxVertexIndex)
  11118. maxVertexIndex = vertexIndex;
  11119. }
  11120. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11121. };
  11122. return SubMesh;
  11123. })();
  11124. BABYLON.SubMesh = SubMesh;
  11125. })(BABYLON || (BABYLON = {}));
  11126. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11127. (function (BABYLON) {
  11128. var BaseTexture = (function () {
  11129. function BaseTexture(scene) {
  11130. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11131. this.hasAlpha = false;
  11132. this.getAlphaFromRGB = false;
  11133. this.level = 1;
  11134. this.isCube = false;
  11135. this.isRenderTarget = false;
  11136. this.animations = new Array();
  11137. this.coordinatesIndex = 0;
  11138. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11139. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11140. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11141. this.anisotropicFilteringLevel = 4;
  11142. this._scene = scene;
  11143. this._scene.textures.push(this);
  11144. }
  11145. BaseTexture.prototype.getScene = function () {
  11146. return this._scene;
  11147. };
  11148. BaseTexture.prototype.getTextureMatrix = function () {
  11149. return null;
  11150. };
  11151. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11152. return null;
  11153. };
  11154. BaseTexture.prototype.getInternalTexture = function () {
  11155. return this._texture;
  11156. };
  11157. BaseTexture.prototype.isReady = function () {
  11158. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11159. return true;
  11160. }
  11161. if (this._texture) {
  11162. return this._texture.isReady;
  11163. }
  11164. return false;
  11165. };
  11166. BaseTexture.prototype.getSize = function () {
  11167. if (this._texture._width) {
  11168. return { width: this._texture._width, height: this._texture._height };
  11169. }
  11170. if (this._texture._size) {
  11171. return { width: this._texture._size, height: this._texture._size };
  11172. }
  11173. return { width: 0, height: 0 };
  11174. };
  11175. BaseTexture.prototype.getBaseSize = function () {
  11176. if (!this.isReady())
  11177. return { width: 0, height: 0 };
  11178. if (this._texture._size) {
  11179. return { width: this._texture._size, height: this._texture._size };
  11180. }
  11181. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11182. };
  11183. BaseTexture.prototype.scale = function (ratio) {
  11184. };
  11185. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11186. get: function () {
  11187. return false;
  11188. },
  11189. enumerable: true,
  11190. configurable: true
  11191. });
  11192. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11193. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11194. for (var index = 0; index < texturesCache.length; index++) {
  11195. var texturesCacheEntry = texturesCache[index];
  11196. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11197. texturesCache.splice(index, 1);
  11198. return;
  11199. }
  11200. }
  11201. };
  11202. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11203. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11204. for (var index = 0; index < texturesCache.length; index++) {
  11205. var texturesCacheEntry = texturesCache[index];
  11206. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11207. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11208. texturesCacheEntry.references++;
  11209. return texturesCacheEntry;
  11210. }
  11211. }
  11212. }
  11213. return null;
  11214. };
  11215. BaseTexture.prototype.delayLoad = function () {
  11216. };
  11217. BaseTexture.prototype.releaseInternalTexture = function () {
  11218. if (!this._texture) {
  11219. return;
  11220. }
  11221. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11222. this._texture.references--;
  11223. // Final reference ?
  11224. if (this._texture.references === 0) {
  11225. var index = texturesCache.indexOf(this._texture);
  11226. texturesCache.splice(index, 1);
  11227. this._scene.getEngine()._releaseTexture(this._texture);
  11228. delete this._texture;
  11229. }
  11230. };
  11231. BaseTexture.prototype.clone = function () {
  11232. return null;
  11233. };
  11234. BaseTexture.prototype.dispose = function () {
  11235. // Remove from scene
  11236. var index = this._scene.textures.indexOf(this);
  11237. if (index >= 0) {
  11238. this._scene.textures.splice(index, 1);
  11239. }
  11240. if (this._texture === undefined) {
  11241. return;
  11242. }
  11243. this.releaseInternalTexture();
  11244. // Callback
  11245. if (this.onDispose) {
  11246. this.onDispose();
  11247. }
  11248. };
  11249. return BaseTexture;
  11250. })();
  11251. BABYLON.BaseTexture = BaseTexture;
  11252. })(BABYLON || (BABYLON = {}));
  11253. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  11254. (function (BABYLON) {
  11255. var RenderingGroup = (function () {
  11256. function RenderingGroup(index, scene) {
  11257. this.index = index;
  11258. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11259. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11260. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11261. this._scene = scene;
  11262. }
  11263. RenderingGroup.prototype.render = function (customRenderFunction) {
  11264. if (customRenderFunction) {
  11265. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11266. return true;
  11267. }
  11268. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11269. return false;
  11270. }
  11271. var engine = this._scene.getEngine();
  11272. // Opaque
  11273. var subIndex;
  11274. var submesh;
  11275. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11276. submesh = this._opaqueSubMeshes.data[subIndex];
  11277. submesh.render();
  11278. }
  11279. // Alpha test
  11280. engine.setAlphaTesting(true);
  11281. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11282. submesh = this._alphaTestSubMeshes.data[subIndex];
  11283. submesh.render();
  11284. }
  11285. engine.setAlphaTesting(false);
  11286. // Transparent
  11287. if (this._transparentSubMeshes.length) {
  11288. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11289. submesh = this._transparentSubMeshes.data[subIndex];
  11290. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11291. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11292. }
  11293. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11294. sortedArray.sort(function (a, b) {
  11295. // Alpha index first
  11296. if (a._alphaIndex > b._alphaIndex) {
  11297. return 1;
  11298. }
  11299. if (a._alphaIndex < b._alphaIndex) {
  11300. return -1;
  11301. }
  11302. // Then distance to camera
  11303. if (a._distanceToCamera < b._distanceToCamera) {
  11304. return 1;
  11305. }
  11306. if (a._distanceToCamera > b._distanceToCamera) {
  11307. return -1;
  11308. }
  11309. return 0;
  11310. });
  11311. // Rendering
  11312. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11313. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11314. submesh = sortedArray[subIndex];
  11315. submesh.render();
  11316. }
  11317. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11318. }
  11319. return true;
  11320. };
  11321. RenderingGroup.prototype.prepare = function () {
  11322. this._opaqueSubMeshes.reset();
  11323. this._transparentSubMeshes.reset();
  11324. this._alphaTestSubMeshes.reset();
  11325. };
  11326. RenderingGroup.prototype.dispatch = function (subMesh) {
  11327. var material = subMesh.getMaterial();
  11328. var mesh = subMesh.getMesh();
  11329. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11330. this._transparentSubMeshes.push(subMesh);
  11331. }
  11332. else if (material.needAlphaTesting()) {
  11333. this._alphaTestSubMeshes.push(subMesh);
  11334. }
  11335. else {
  11336. this._opaqueSubMeshes.push(subMesh); // Opaque
  11337. }
  11338. };
  11339. return RenderingGroup;
  11340. })();
  11341. BABYLON.RenderingGroup = RenderingGroup;
  11342. })(BABYLON || (BABYLON = {}));
  11343. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  11344. (function (BABYLON) {
  11345. var RenderingManager = (function () {
  11346. function RenderingManager(scene) {
  11347. this._renderingGroups = new Array();
  11348. this._scene = scene;
  11349. }
  11350. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11351. if (this._scene._activeParticleSystems.length === 0) {
  11352. return;
  11353. }
  11354. // Particles
  11355. var beforeParticlesDate = BABYLON.Tools.Now;
  11356. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11357. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11358. if (particleSystem.renderingGroupId !== index) {
  11359. continue;
  11360. }
  11361. this._clearDepthBuffer();
  11362. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11363. this._scene._activeParticles += particleSystem.render();
  11364. }
  11365. }
  11366. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11367. };
  11368. RenderingManager.prototype._renderSprites = function (index) {
  11369. if (this._scene.spriteManagers.length === 0) {
  11370. return;
  11371. }
  11372. // Sprites
  11373. var beforeSpritessDate = BABYLON.Tools.Now;
  11374. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11375. var spriteManager = this._scene.spriteManagers[id];
  11376. if (spriteManager.renderingGroupId === index) {
  11377. this._clearDepthBuffer();
  11378. spriteManager.render();
  11379. }
  11380. }
  11381. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11382. };
  11383. RenderingManager.prototype._clearDepthBuffer = function () {
  11384. if (this._depthBufferAlreadyCleaned) {
  11385. return;
  11386. }
  11387. this._scene.getEngine().clear(0, false, true);
  11388. this._depthBufferAlreadyCleaned = true;
  11389. };
  11390. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11391. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11392. this._depthBufferAlreadyCleaned = false;
  11393. var renderingGroup = this._renderingGroups[index];
  11394. if (renderingGroup) {
  11395. this._clearDepthBuffer();
  11396. if (!renderingGroup.render(customRenderFunction)) {
  11397. this._renderingGroups.splice(index, 1);
  11398. }
  11399. }
  11400. if (renderSprites) {
  11401. this._renderSprites(index);
  11402. }
  11403. if (renderParticles) {
  11404. this._renderParticles(index, activeMeshes);
  11405. }
  11406. }
  11407. };
  11408. RenderingManager.prototype.reset = function () {
  11409. for (var index in this._renderingGroups) {
  11410. var renderingGroup = this._renderingGroups[index];
  11411. renderingGroup.prepare();
  11412. }
  11413. };
  11414. RenderingManager.prototype.dispatch = function (subMesh) {
  11415. var mesh = subMesh.getMesh();
  11416. var renderingGroupId = mesh.renderingGroupId || 0;
  11417. if (!this._renderingGroups[renderingGroupId]) {
  11418. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11419. }
  11420. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11421. };
  11422. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11423. return RenderingManager;
  11424. })();
  11425. BABYLON.RenderingManager = RenderingManager;
  11426. })(BABYLON || (BABYLON = {}));
  11427. //# sourceMappingURL=babylon.renderingManager.js.map
  11428. var BABYLON;
  11429. (function (BABYLON) {
  11430. var Texture = (function (_super) {
  11431. __extends(Texture, _super);
  11432. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  11433. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11434. if (onLoad === void 0) { onLoad = null; }
  11435. if (onError === void 0) { onError = null; }
  11436. if (buffer === void 0) { buffer = null; }
  11437. if (deleteBuffer === void 0) { deleteBuffer = false; }
  11438. _super.call(this, scene);
  11439. this.uOffset = 0;
  11440. this.vOffset = 0;
  11441. this.uScale = 1.0;
  11442. this.vScale = 1.0;
  11443. this.uAng = 0;
  11444. this.vAng = 0;
  11445. this.wAng = 0;
  11446. this.name = url;
  11447. this.url = url;
  11448. this._noMipmap = noMipmap;
  11449. this._invertY = invertY;
  11450. this._samplingMode = samplingMode;
  11451. this._buffer = buffer;
  11452. this._deleteBuffer = deleteBuffer;
  11453. if (!url) {
  11454. return;
  11455. }
  11456. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  11457. if (!this._texture) {
  11458. if (!scene.useDelayedTextureLoading) {
  11459. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  11460. if (deleteBuffer) {
  11461. delete this._buffer;
  11462. }
  11463. }
  11464. else {
  11465. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11466. }
  11467. }
  11468. }
  11469. Texture.prototype.delayLoad = function () {
  11470. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11471. return;
  11472. }
  11473. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11474. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  11475. if (!this._texture) {
  11476. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  11477. if (this._deleteBuffer) {
  11478. delete this._buffer;
  11479. }
  11480. }
  11481. };
  11482. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  11483. x -= this.uOffset + 0.5;
  11484. y -= this.vOffset + 0.5;
  11485. z -= 0.5;
  11486. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  11487. t.x *= this.uScale;
  11488. t.y *= this.vScale;
  11489. t.x += 0.5;
  11490. t.y += 0.5;
  11491. t.z += 0.5;
  11492. };
  11493. Texture.prototype.getTextureMatrix = function () {
  11494. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.uAng === this._cachedUAng && this.vAng === this._cachedVAng && this.wAng === this._cachedWAng) {
  11495. return this._cachedTextureMatrix;
  11496. }
  11497. this._cachedUOffset = this.uOffset;
  11498. this._cachedVOffset = this.vOffset;
  11499. this._cachedUScale = this.uScale;
  11500. this._cachedVScale = this.vScale;
  11501. this._cachedUAng = this.uAng;
  11502. this._cachedVAng = this.vAng;
  11503. this._cachedWAng = this.wAng;
  11504. if (!this._cachedTextureMatrix) {
  11505. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11506. this._rowGenerationMatrix = new BABYLON.Matrix();
  11507. this._t0 = BABYLON.Vector3.Zero();
  11508. this._t1 = BABYLON.Vector3.Zero();
  11509. this._t2 = BABYLON.Vector3.Zero();
  11510. }
  11511. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  11512. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  11513. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  11514. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  11515. this._t1.subtractInPlace(this._t0);
  11516. this._t2.subtractInPlace(this._t0);
  11517. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11518. this._cachedTextureMatrix.m[0] = this._t1.x;
  11519. this._cachedTextureMatrix.m[1] = this._t1.y;
  11520. this._cachedTextureMatrix.m[2] = this._t1.z;
  11521. this._cachedTextureMatrix.m[4] = this._t2.x;
  11522. this._cachedTextureMatrix.m[5] = this._t2.y;
  11523. this._cachedTextureMatrix.m[6] = this._t2.z;
  11524. this._cachedTextureMatrix.m[8] = this._t0.x;
  11525. this._cachedTextureMatrix.m[9] = this._t0.y;
  11526. this._cachedTextureMatrix.m[10] = this._t0.z;
  11527. return this._cachedTextureMatrix;
  11528. };
  11529. Texture.prototype.getReflectionTextureMatrix = function () {
  11530. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  11531. return this._cachedTextureMatrix;
  11532. }
  11533. if (!this._cachedTextureMatrix) {
  11534. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11535. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  11536. }
  11537. this._cachedCoordinatesMode = this.coordinatesMode;
  11538. switch (this.coordinatesMode) {
  11539. case BABYLON.Texture.SPHERICAL_MODE:
  11540. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11541. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  11542. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  11543. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  11544. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  11545. break;
  11546. case BABYLON.Texture.PLANAR_MODE:
  11547. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11548. this._cachedTextureMatrix[0] = this.uScale;
  11549. this._cachedTextureMatrix[5] = this.vScale;
  11550. this._cachedTextureMatrix[12] = this.uOffset;
  11551. this._cachedTextureMatrix[13] = this.vOffset;
  11552. break;
  11553. case BABYLON.Texture.PROJECTION_MODE:
  11554. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  11555. this._projectionModeMatrix.m[0] = 0.5;
  11556. this._projectionModeMatrix.m[5] = -0.5;
  11557. this._projectionModeMatrix.m[10] = 0.0;
  11558. this._projectionModeMatrix.m[12] = 0.5;
  11559. this._projectionModeMatrix.m[13] = 0.5;
  11560. this._projectionModeMatrix.m[14] = 1.0;
  11561. this._projectionModeMatrix.m[15] = 1.0;
  11562. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  11563. break;
  11564. default:
  11565. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11566. break;
  11567. }
  11568. return this._cachedTextureMatrix;
  11569. };
  11570. Texture.prototype.clone = function () {
  11571. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  11572. // Base texture
  11573. newTexture.hasAlpha = this.hasAlpha;
  11574. newTexture.level = this.level;
  11575. newTexture.wrapU = this.wrapU;
  11576. newTexture.wrapV = this.wrapV;
  11577. newTexture.coordinatesIndex = this.coordinatesIndex;
  11578. newTexture.coordinatesMode = this.coordinatesMode;
  11579. // Texture
  11580. newTexture.uOffset = this.uOffset;
  11581. newTexture.vOffset = this.vOffset;
  11582. newTexture.uScale = this.uScale;
  11583. newTexture.vScale = this.vScale;
  11584. newTexture.uAng = this.uAng;
  11585. newTexture.vAng = this.vAng;
  11586. newTexture.wAng = this.wAng;
  11587. return newTexture;
  11588. };
  11589. // Statics
  11590. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  11591. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11592. if (onLoad === void 0) { onLoad = null; }
  11593. if (onError === void 0) { onError = null; }
  11594. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  11595. };
  11596. // Constants
  11597. Texture.NEAREST_SAMPLINGMODE = 1;
  11598. Texture.BILINEAR_SAMPLINGMODE = 2;
  11599. Texture.TRILINEAR_SAMPLINGMODE = 3;
  11600. Texture.EXPLICIT_MODE = 0;
  11601. Texture.SPHERICAL_MODE = 1;
  11602. Texture.PLANAR_MODE = 2;
  11603. Texture.CUBIC_MODE = 3;
  11604. Texture.PROJECTION_MODE = 4;
  11605. Texture.SKYBOX_MODE = 5;
  11606. Texture.CLAMP_ADDRESSMODE = 0;
  11607. Texture.WRAP_ADDRESSMODE = 1;
  11608. Texture.MIRROR_ADDRESSMODE = 2;
  11609. return Texture;
  11610. })(BABYLON.BaseTexture);
  11611. BABYLON.Texture = Texture;
  11612. })(BABYLON || (BABYLON = {}));
  11613. //# sourceMappingURL=babylon.texture.js.map
  11614. var BABYLON;
  11615. (function (BABYLON) {
  11616. var CubeTexture = (function (_super) {
  11617. __extends(CubeTexture, _super);
  11618. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  11619. _super.call(this, scene);
  11620. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  11621. this.name = rootUrl;
  11622. this.url = rootUrl;
  11623. this._noMipmap = noMipmap;
  11624. this.hasAlpha = false;
  11625. this._texture = this._getFromCache(rootUrl, noMipmap);
  11626. if (!extensions) {
  11627. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  11628. }
  11629. this._extensions = extensions;
  11630. if (!this._texture) {
  11631. if (!scene.useDelayedTextureLoading) {
  11632. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  11633. }
  11634. else {
  11635. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11636. }
  11637. }
  11638. this.isCube = true;
  11639. this._textureMatrix = BABYLON.Matrix.Identity();
  11640. }
  11641. CubeTexture.prototype.clone = function () {
  11642. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  11643. // Base texture
  11644. newTexture.level = this.level;
  11645. newTexture.wrapU = this.wrapU;
  11646. newTexture.wrapV = this.wrapV;
  11647. newTexture.coordinatesIndex = this.coordinatesIndex;
  11648. newTexture.coordinatesMode = this.coordinatesMode;
  11649. return newTexture;
  11650. };
  11651. // Methods
  11652. CubeTexture.prototype.delayLoad = function () {
  11653. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11654. return;
  11655. }
  11656. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11657. this._texture = this._getFromCache(this.url, this._noMipmap);
  11658. if (!this._texture) {
  11659. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  11660. }
  11661. };
  11662. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  11663. return this._textureMatrix;
  11664. };
  11665. return CubeTexture;
  11666. })(BABYLON.BaseTexture);
  11667. BABYLON.CubeTexture = CubeTexture;
  11668. })(BABYLON || (BABYLON = {}));
  11669. //# sourceMappingURL=babylon.cubeTexture.js.map
  11670. var BABYLON;
  11671. (function (BABYLON) {
  11672. var RenderTargetTexture = (function (_super) {
  11673. __extends(RenderTargetTexture, _super);
  11674. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  11675. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  11676. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  11677. _super.call(this, null, scene, !generateMipMaps);
  11678. this.renderList = new Array();
  11679. this.renderParticles = true;
  11680. this.renderSprites = false;
  11681. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  11682. this._currentRefreshId = -1;
  11683. this._refreshRate = 1;
  11684. this.name = name;
  11685. this.isRenderTarget = true;
  11686. this._size = size;
  11687. this._generateMipMaps = generateMipMaps;
  11688. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  11689. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  11690. // Rendering groups
  11691. this._renderingManager = new BABYLON.RenderingManager(scene);
  11692. }
  11693. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  11694. this._currentRefreshId = -1;
  11695. };
  11696. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  11697. get: function () {
  11698. return this._refreshRate;
  11699. },
  11700. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11701. set: function (value) {
  11702. this._refreshRate = value;
  11703. this.resetRefreshCounter();
  11704. },
  11705. enumerable: true,
  11706. configurable: true
  11707. });
  11708. RenderTargetTexture.prototype._shouldRender = function () {
  11709. if (this._currentRefreshId === -1) {
  11710. this._currentRefreshId = 1;
  11711. return true;
  11712. }
  11713. if (this.refreshRate === this._currentRefreshId) {
  11714. this._currentRefreshId = 1;
  11715. return true;
  11716. }
  11717. this._currentRefreshId++;
  11718. return false;
  11719. };
  11720. RenderTargetTexture.prototype.isReady = function () {
  11721. if (!this.getScene().renderTargetsEnabled) {
  11722. return false;
  11723. }
  11724. return _super.prototype.isReady.call(this);
  11725. };
  11726. RenderTargetTexture.prototype.getRenderSize = function () {
  11727. return this._size;
  11728. };
  11729. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11730. get: function () {
  11731. return true;
  11732. },
  11733. enumerable: true,
  11734. configurable: true
  11735. });
  11736. RenderTargetTexture.prototype.scale = function (ratio) {
  11737. var newSize = this._size * ratio;
  11738. this.resize(newSize, this._generateMipMaps);
  11739. };
  11740. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11741. this.releaseInternalTexture();
  11742. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11743. };
  11744. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11745. var scene = this.getScene();
  11746. var engine = scene.getEngine();
  11747. if (this._waitingRenderList) {
  11748. this.renderList = [];
  11749. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11750. var id = this._waitingRenderList[index];
  11751. this.renderList.push(scene.getMeshByID(id));
  11752. }
  11753. delete this._waitingRenderList;
  11754. }
  11755. if (this.renderList && this.renderList.length === 0) {
  11756. return;
  11757. }
  11758. // Bind
  11759. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11760. engine.bindFramebuffer(this._texture);
  11761. }
  11762. // Clear
  11763. engine.clear(scene.clearColor, true, true);
  11764. this._renderingManager.reset();
  11765. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  11766. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  11767. var mesh = currentRenderList[meshIndex];
  11768. if (mesh) {
  11769. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  11770. // Reset _currentRefreshId
  11771. this.resetRefreshCounter();
  11772. continue;
  11773. }
  11774. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  11775. mesh._activate(scene.getRenderId());
  11776. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  11777. var subMesh = mesh.subMeshes[subIndex];
  11778. scene._activeVertices += subMesh.indexCount;
  11779. this._renderingManager.dispatch(subMesh);
  11780. }
  11781. }
  11782. }
  11783. }
  11784. if (!this._doNotChangeAspectRatio) {
  11785. scene.updateTransformMatrix(true);
  11786. }
  11787. if (this.onBeforeRender) {
  11788. this.onBeforeRender();
  11789. }
  11790. // Render
  11791. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  11792. if (useCameraPostProcess) {
  11793. scene.postProcessManager._finalizeFrame(false, this._texture);
  11794. }
  11795. if (this.onAfterRender) {
  11796. this.onAfterRender();
  11797. }
  11798. // Unbind
  11799. engine.unBindFramebuffer(this._texture);
  11800. if (!this._doNotChangeAspectRatio) {
  11801. scene.updateTransformMatrix(true);
  11802. }
  11803. };
  11804. RenderTargetTexture.prototype.clone = function () {
  11805. var textureSize = this.getSize();
  11806. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11807. // Base texture
  11808. newTexture.hasAlpha = this.hasAlpha;
  11809. newTexture.level = this.level;
  11810. // RenderTarget Texture
  11811. newTexture.coordinatesMode = this.coordinatesMode;
  11812. newTexture.renderList = this.renderList.slice(0);
  11813. return newTexture;
  11814. };
  11815. return RenderTargetTexture;
  11816. })(BABYLON.Texture);
  11817. BABYLON.RenderTargetTexture = RenderTargetTexture;
  11818. })(BABYLON || (BABYLON = {}));
  11819. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  11820. var BABYLON;
  11821. (function (BABYLON) {
  11822. var ProceduralTexture = (function (_super) {
  11823. __extends(ProceduralTexture, _super);
  11824. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  11825. if (generateMipMaps === void 0) { generateMipMaps = true; }
  11826. _super.call(this, null, scene, !generateMipMaps);
  11827. this._currentRefreshId = -1;
  11828. this._refreshRate = 1;
  11829. this._vertexDeclaration = [2];
  11830. this._vertexStrideSize = 2 * 4;
  11831. this._uniforms = new Array();
  11832. this._samplers = new Array();
  11833. this._textures = new Array();
  11834. this._floats = new Array();
  11835. this._floatsArrays = {};
  11836. this._colors3 = new Array();
  11837. this._colors4 = new Array();
  11838. this._vectors2 = new Array();
  11839. this._vectors3 = new Array();
  11840. this._matrices = new Array();
  11841. this._fallbackTextureUsed = false;
  11842. scene._proceduralTextures.push(this);
  11843. this.name = name;
  11844. this.isRenderTarget = true;
  11845. this._size = size;
  11846. this._generateMipMaps = generateMipMaps;
  11847. this.setFragment(fragment);
  11848. this._fallbackTexture = fallbackTexture;
  11849. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11850. // VBO
  11851. var vertices = [];
  11852. vertices.push(1, 1);
  11853. vertices.push(-1, 1);
  11854. vertices.push(-1, -1);
  11855. vertices.push(1, -1);
  11856. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11857. // Indices
  11858. var indices = [];
  11859. indices.push(0);
  11860. indices.push(1);
  11861. indices.push(2);
  11862. indices.push(0);
  11863. indices.push(2);
  11864. indices.push(3);
  11865. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11866. }
  11867. ProceduralTexture.prototype.reset = function () {
  11868. if (this._effect === undefined) {
  11869. return;
  11870. }
  11871. var engine = this.getScene().getEngine();
  11872. engine._releaseEffect(this._effect);
  11873. };
  11874. ProceduralTexture.prototype.isReady = function () {
  11875. var _this = this;
  11876. var engine = this.getScene().getEngine();
  11877. var shaders;
  11878. if (!this._fragment) {
  11879. return false;
  11880. }
  11881. if (this._fallbackTextureUsed) {
  11882. return true;
  11883. }
  11884. if (this._fragment.fragmentElement !== undefined) {
  11885. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  11886. }
  11887. else {
  11888. shaders = { vertex: "procedural", fragment: this._fragment };
  11889. }
  11890. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  11891. _this.releaseInternalTexture();
  11892. if (_this._fallbackTexture) {
  11893. _this._texture = _this._fallbackTexture._texture;
  11894. _this._texture.references++;
  11895. }
  11896. _this._fallbackTextureUsed = true;
  11897. });
  11898. return this._effect.isReady();
  11899. };
  11900. ProceduralTexture.prototype.resetRefreshCounter = function () {
  11901. this._currentRefreshId = -1;
  11902. };
  11903. ProceduralTexture.prototype.setFragment = function (fragment) {
  11904. this._fragment = fragment;
  11905. };
  11906. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  11907. get: function () {
  11908. return this._refreshRate;
  11909. },
  11910. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11911. set: function (value) {
  11912. this._refreshRate = value;
  11913. this.resetRefreshCounter();
  11914. },
  11915. enumerable: true,
  11916. configurable: true
  11917. });
  11918. ProceduralTexture.prototype._shouldRender = function () {
  11919. if (!this.isReady() || !this._texture) {
  11920. return false;
  11921. }
  11922. if (this._fallbackTextureUsed) {
  11923. return false;
  11924. }
  11925. if (this._currentRefreshId === -1) {
  11926. this._currentRefreshId = 1;
  11927. return true;
  11928. }
  11929. if (this.refreshRate === this._currentRefreshId) {
  11930. this._currentRefreshId = 1;
  11931. return true;
  11932. }
  11933. this._currentRefreshId++;
  11934. return false;
  11935. };
  11936. ProceduralTexture.prototype.getRenderSize = function () {
  11937. return this._size;
  11938. };
  11939. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  11940. if (this._fallbackTextureUsed) {
  11941. return;
  11942. }
  11943. this.releaseInternalTexture();
  11944. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11945. };
  11946. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  11947. if (this._uniforms.indexOf(uniformName) === -1) {
  11948. this._uniforms.push(uniformName);
  11949. }
  11950. };
  11951. ProceduralTexture.prototype.setTexture = function (name, texture) {
  11952. if (this._samplers.indexOf(name) === -1) {
  11953. this._samplers.push(name);
  11954. }
  11955. this._textures[name] = texture;
  11956. return this;
  11957. };
  11958. ProceduralTexture.prototype.setFloat = function (name, value) {
  11959. this._checkUniform(name);
  11960. this._floats[name] = value;
  11961. return this;
  11962. };
  11963. ProceduralTexture.prototype.setFloats = function (name, value) {
  11964. this._checkUniform(name);
  11965. this._floatsArrays[name] = value;
  11966. return this;
  11967. };
  11968. ProceduralTexture.prototype.setColor3 = function (name, value) {
  11969. this._checkUniform(name);
  11970. this._colors3[name] = value;
  11971. return this;
  11972. };
  11973. ProceduralTexture.prototype.setColor4 = function (name, value) {
  11974. this._checkUniform(name);
  11975. this._colors4[name] = value;
  11976. return this;
  11977. };
  11978. ProceduralTexture.prototype.setVector2 = function (name, value) {
  11979. this._checkUniform(name);
  11980. this._vectors2[name] = value;
  11981. return this;
  11982. };
  11983. ProceduralTexture.prototype.setVector3 = function (name, value) {
  11984. this._checkUniform(name);
  11985. this._vectors3[name] = value;
  11986. return this;
  11987. };
  11988. ProceduralTexture.prototype.setMatrix = function (name, value) {
  11989. this._checkUniform(name);
  11990. this._matrices[name] = value;
  11991. return this;
  11992. };
  11993. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11994. var scene = this.getScene();
  11995. var engine = scene.getEngine();
  11996. engine.bindFramebuffer(this._texture);
  11997. // Clear
  11998. engine.clear(scene.clearColor, true, true);
  11999. // Render
  12000. engine.enableEffect(this._effect);
  12001. engine.setState(false);
  12002. for (var name in this._textures) {
  12003. this._effect.setTexture(name, this._textures[name]);
  12004. }
  12005. for (name in this._floats) {
  12006. this._effect.setFloat(name, this._floats[name]);
  12007. }
  12008. for (name in this._floatsArrays) {
  12009. this._effect.setArray(name, this._floatsArrays[name]);
  12010. }
  12011. for (name in this._colors3) {
  12012. this._effect.setColor3(name, this._colors3[name]);
  12013. }
  12014. for (name in this._colors4) {
  12015. var color = this._colors4[name];
  12016. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12017. }
  12018. for (name in this._vectors2) {
  12019. this._effect.setVector2(name, this._vectors2[name]);
  12020. }
  12021. for (name in this._vectors3) {
  12022. this._effect.setVector3(name, this._vectors3[name]);
  12023. }
  12024. for (name in this._matrices) {
  12025. this._effect.setMatrix(name, this._matrices[name]);
  12026. }
  12027. // VBOs
  12028. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12029. // Draw order
  12030. engine.draw(true, 0, 6);
  12031. // Unbind
  12032. engine.unBindFramebuffer(this._texture);
  12033. };
  12034. ProceduralTexture.prototype.clone = function () {
  12035. var textureSize = this.getSize();
  12036. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12037. // Base texture
  12038. newTexture.hasAlpha = this.hasAlpha;
  12039. newTexture.level = this.level;
  12040. // RenderTarget Texture
  12041. newTexture.coordinatesMode = this.coordinatesMode;
  12042. return newTexture;
  12043. };
  12044. ProceduralTexture.prototype.dispose = function () {
  12045. var index = this.getScene()._proceduralTextures.indexOf(this);
  12046. if (index >= 0) {
  12047. this.getScene()._proceduralTextures.splice(index, 1);
  12048. }
  12049. _super.prototype.dispose.call(this);
  12050. };
  12051. return ProceduralTexture;
  12052. })(BABYLON.Texture);
  12053. BABYLON.ProceduralTexture = ProceduralTexture;
  12054. })(BABYLON || (BABYLON = {}));
  12055. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12056. var BABYLON;
  12057. (function (BABYLON) {
  12058. var WoodProceduralTexture = (function (_super) {
  12059. __extends(WoodProceduralTexture, _super);
  12060. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12061. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12062. this._ampScale = 100.0;
  12063. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12064. this.updateShaderUniforms();
  12065. this.refreshRate = 0;
  12066. }
  12067. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12068. this.setFloat("ampScale", this._ampScale);
  12069. this.setColor3("woodColor", this._woodColor);
  12070. };
  12071. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12072. get: function () {
  12073. return this._ampScale;
  12074. },
  12075. set: function (value) {
  12076. this._ampScale = value;
  12077. this.updateShaderUniforms();
  12078. },
  12079. enumerable: true,
  12080. configurable: true
  12081. });
  12082. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12083. get: function () {
  12084. return this._woodColor;
  12085. },
  12086. set: function (value) {
  12087. this._woodColor = value;
  12088. this.updateShaderUniforms();
  12089. },
  12090. enumerable: true,
  12091. configurable: true
  12092. });
  12093. return WoodProceduralTexture;
  12094. })(BABYLON.ProceduralTexture);
  12095. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12096. var FireProceduralTexture = (function (_super) {
  12097. __extends(FireProceduralTexture, _super);
  12098. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12099. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12100. this._time = 0.0;
  12101. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12102. this._shift = 1.6;
  12103. this._autoGenerateTime = true;
  12104. this._alphaThreshold = 0.5;
  12105. this._fireColors = FireProceduralTexture.RedFireColors;
  12106. this.updateShaderUniforms();
  12107. this.refreshRate = 1;
  12108. }
  12109. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12110. this.setFloat("time", this._time);
  12111. this.setVector2("speed", this._speed);
  12112. this.setFloat("shift", this._shift);
  12113. this.setColor3("c1", this._fireColors[0]);
  12114. this.setColor3("c2", this._fireColors[1]);
  12115. this.setColor3("c3", this._fireColors[2]);
  12116. this.setColor3("c4", this._fireColors[3]);
  12117. this.setColor3("c5", this._fireColors[4]);
  12118. this.setColor3("c6", this._fireColors[5]);
  12119. this.setFloat("alphaThreshold", this._alphaThreshold);
  12120. };
  12121. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12122. if (this._autoGenerateTime) {
  12123. this._time += this.getScene().getAnimationRatio() * 0.03;
  12124. this.updateShaderUniforms();
  12125. }
  12126. _super.prototype.render.call(this, useCameraPostProcess);
  12127. };
  12128. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12129. get: function () {
  12130. return [
  12131. new BABYLON.Color3(0.5, 0.0, 1.0),
  12132. new BABYLON.Color3(0.9, 0.0, 1.0),
  12133. new BABYLON.Color3(0.2, 0.0, 1.0),
  12134. new BABYLON.Color3(1.0, 0.9, 1.0),
  12135. new BABYLON.Color3(0.1, 0.1, 1.0),
  12136. new BABYLON.Color3(0.9, 0.9, 1.0)
  12137. ];
  12138. },
  12139. enumerable: true,
  12140. configurable: true
  12141. });
  12142. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12143. get: function () {
  12144. return [
  12145. new BABYLON.Color3(0.5, 1.0, 0.0),
  12146. new BABYLON.Color3(0.5, 1.0, 0.0),
  12147. new BABYLON.Color3(0.3, 0.4, 0.0),
  12148. new BABYLON.Color3(0.5, 1.0, 0.0),
  12149. new BABYLON.Color3(0.2, 0.0, 0.0),
  12150. new BABYLON.Color3(0.5, 1.0, 0.0)
  12151. ];
  12152. },
  12153. enumerable: true,
  12154. configurable: true
  12155. });
  12156. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12157. get: function () {
  12158. return [
  12159. new BABYLON.Color3(0.5, 0.0, 0.1),
  12160. new BABYLON.Color3(0.9, 0.0, 0.0),
  12161. new BABYLON.Color3(0.2, 0.0, 0.0),
  12162. new BABYLON.Color3(1.0, 0.9, 0.0),
  12163. new BABYLON.Color3(0.1, 0.1, 0.1),
  12164. new BABYLON.Color3(0.9, 0.9, 0.9)
  12165. ];
  12166. },
  12167. enumerable: true,
  12168. configurable: true
  12169. });
  12170. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12171. get: function () {
  12172. return [
  12173. new BABYLON.Color3(0.1, 0.0, 0.5),
  12174. new BABYLON.Color3(0.0, 0.0, 0.5),
  12175. new BABYLON.Color3(0.1, 0.0, 0.2),
  12176. new BABYLON.Color3(0.0, 0.0, 1.0),
  12177. new BABYLON.Color3(0.1, 0.2, 0.3),
  12178. new BABYLON.Color3(0.0, 0.2, 0.9)
  12179. ];
  12180. },
  12181. enumerable: true,
  12182. configurable: true
  12183. });
  12184. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12185. get: function () {
  12186. return this._fireColors;
  12187. },
  12188. set: function (value) {
  12189. this._fireColors = value;
  12190. this.updateShaderUniforms();
  12191. },
  12192. enumerable: true,
  12193. configurable: true
  12194. });
  12195. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12196. get: function () {
  12197. return this._time;
  12198. },
  12199. set: function (value) {
  12200. this._time = value;
  12201. this.updateShaderUniforms();
  12202. },
  12203. enumerable: true,
  12204. configurable: true
  12205. });
  12206. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12207. get: function () {
  12208. return this._speed;
  12209. },
  12210. set: function (value) {
  12211. this._speed = value;
  12212. this.updateShaderUniforms();
  12213. },
  12214. enumerable: true,
  12215. configurable: true
  12216. });
  12217. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12218. get: function () {
  12219. return this._shift;
  12220. },
  12221. set: function (value) {
  12222. this._shift = value;
  12223. this.updateShaderUniforms();
  12224. },
  12225. enumerable: true,
  12226. configurable: true
  12227. });
  12228. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12229. get: function () {
  12230. return this._alphaThreshold;
  12231. },
  12232. set: function (value) {
  12233. this._alphaThreshold = value;
  12234. this.updateShaderUniforms();
  12235. },
  12236. enumerable: true,
  12237. configurable: true
  12238. });
  12239. return FireProceduralTexture;
  12240. })(BABYLON.ProceduralTexture);
  12241. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12242. var CloudProceduralTexture = (function (_super) {
  12243. __extends(CloudProceduralTexture, _super);
  12244. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12245. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12246. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12247. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12248. this.updateShaderUniforms();
  12249. this.refreshRate = 0;
  12250. }
  12251. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12252. this.setColor3("skyColor", this._skyColor);
  12253. this.setColor3("cloudColor", this._cloudColor);
  12254. };
  12255. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12256. get: function () {
  12257. return this._skyColor;
  12258. },
  12259. set: function (value) {
  12260. this._skyColor = value;
  12261. this.updateShaderUniforms();
  12262. },
  12263. enumerable: true,
  12264. configurable: true
  12265. });
  12266. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  12267. get: function () {
  12268. return this._cloudColor;
  12269. },
  12270. set: function (value) {
  12271. this._cloudColor = value;
  12272. this.updateShaderUniforms();
  12273. },
  12274. enumerable: true,
  12275. configurable: true
  12276. });
  12277. return CloudProceduralTexture;
  12278. })(BABYLON.ProceduralTexture);
  12279. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12280. var GrassProceduralTexture = (function (_super) {
  12281. __extends(GrassProceduralTexture, _super);
  12282. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12283. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12284. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12285. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12286. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12287. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12288. this._grassColors = [
  12289. new BABYLON.Color3(0.29, 0.38, 0.02),
  12290. new BABYLON.Color3(0.36, 0.49, 0.09),
  12291. new BABYLON.Color3(0.51, 0.6, 0.28)
  12292. ];
  12293. this.updateShaderUniforms();
  12294. this.refreshRate = 0;
  12295. }
  12296. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  12297. this.setColor3("herb1Color", this._grassColors[0]);
  12298. this.setColor3("herb2Color", this._grassColors[1]);
  12299. this.setColor3("herb3Color", this._grassColors[2]);
  12300. this.setColor3("groundColor", this._groundColor);
  12301. };
  12302. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  12303. get: function () {
  12304. return this._grassColors;
  12305. },
  12306. set: function (value) {
  12307. this._grassColors = value;
  12308. this.updateShaderUniforms();
  12309. },
  12310. enumerable: true,
  12311. configurable: true
  12312. });
  12313. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  12314. get: function () {
  12315. return this._groundColor;
  12316. },
  12317. set: function (value) {
  12318. this.groundColor = value;
  12319. this.updateShaderUniforms();
  12320. },
  12321. enumerable: true,
  12322. configurable: true
  12323. });
  12324. return GrassProceduralTexture;
  12325. })(BABYLON.ProceduralTexture);
  12326. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  12327. var RoadProceduralTexture = (function (_super) {
  12328. __extends(RoadProceduralTexture, _super);
  12329. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12330. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  12331. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  12332. this.updateShaderUniforms();
  12333. this.refreshRate = 0;
  12334. }
  12335. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  12336. this.setColor3("roadColor", this._roadColor);
  12337. };
  12338. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  12339. get: function () {
  12340. return this._roadColor;
  12341. },
  12342. set: function (value) {
  12343. this._roadColor = value;
  12344. this.updateShaderUniforms();
  12345. },
  12346. enumerable: true,
  12347. configurable: true
  12348. });
  12349. return RoadProceduralTexture;
  12350. })(BABYLON.ProceduralTexture);
  12351. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  12352. var BrickProceduralTexture = (function (_super) {
  12353. __extends(BrickProceduralTexture, _super);
  12354. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12355. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  12356. this._numberOfBricksHeight = 15;
  12357. this._numberOfBricksWidth = 5;
  12358. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12359. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12360. this.updateShaderUniforms();
  12361. this.refreshRate = 0;
  12362. }
  12363. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  12364. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  12365. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  12366. this.setColor3("brickColor", this._brickColor);
  12367. this.setColor3("jointColor", this._jointColor);
  12368. };
  12369. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  12370. get: function () {
  12371. return this._numberOfBricksHeight;
  12372. },
  12373. enumerable: true,
  12374. configurable: true
  12375. });
  12376. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  12377. set: function (value) {
  12378. this._numberOfBricksHeight = value;
  12379. this.updateShaderUniforms();
  12380. },
  12381. enumerable: true,
  12382. configurable: true
  12383. });
  12384. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  12385. get: function () {
  12386. return this._numberOfBricksWidth;
  12387. },
  12388. set: function (value) {
  12389. this._numberOfBricksHeight = value;
  12390. this.updateShaderUniforms();
  12391. },
  12392. enumerable: true,
  12393. configurable: true
  12394. });
  12395. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  12396. get: function () {
  12397. return this._jointColor;
  12398. },
  12399. set: function (value) {
  12400. this._jointColor = value;
  12401. this.updateShaderUniforms();
  12402. },
  12403. enumerable: true,
  12404. configurable: true
  12405. });
  12406. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  12407. get: function () {
  12408. return this._brickColor;
  12409. },
  12410. set: function (value) {
  12411. this._brickColor = value;
  12412. this.updateShaderUniforms();
  12413. },
  12414. enumerable: true,
  12415. configurable: true
  12416. });
  12417. return BrickProceduralTexture;
  12418. })(BABYLON.ProceduralTexture);
  12419. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  12420. var MarbleProceduralTexture = (function (_super) {
  12421. __extends(MarbleProceduralTexture, _super);
  12422. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12423. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  12424. this._numberOfTilesHeight = 3;
  12425. this._numberOfTilesWidth = 3;
  12426. this._amplitude = 9.0;
  12427. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12428. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12429. this.updateShaderUniforms();
  12430. this.refreshRate = 0;
  12431. }
  12432. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  12433. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  12434. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  12435. this.setFloat("amplitude", this._amplitude);
  12436. this.setColor3("marbleColor", this._marbleColor);
  12437. this.setColor3("jointColor", this._jointColor);
  12438. };
  12439. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  12440. get: function () {
  12441. return this._numberOfTilesHeight;
  12442. },
  12443. set: function (value) {
  12444. this._numberOfTilesHeight = value;
  12445. this.updateShaderUniforms();
  12446. },
  12447. enumerable: true,
  12448. configurable: true
  12449. });
  12450. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  12451. get: function () {
  12452. return this._numberOfTilesWidth;
  12453. },
  12454. set: function (value) {
  12455. this._numberOfTilesWidth = value;
  12456. this.updateShaderUniforms();
  12457. },
  12458. enumerable: true,
  12459. configurable: true
  12460. });
  12461. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  12462. get: function () {
  12463. return this._jointColor;
  12464. },
  12465. set: function (value) {
  12466. this._jointColor = value;
  12467. this.updateShaderUniforms();
  12468. },
  12469. enumerable: true,
  12470. configurable: true
  12471. });
  12472. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  12473. get: function () {
  12474. return this._marbleColor;
  12475. },
  12476. set: function (value) {
  12477. this._marbleColor = value;
  12478. this.updateShaderUniforms();
  12479. },
  12480. enumerable: true,
  12481. configurable: true
  12482. });
  12483. return MarbleProceduralTexture;
  12484. })(BABYLON.ProceduralTexture);
  12485. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  12486. })(BABYLON || (BABYLON = {}));
  12487. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  12488. var BABYLON;
  12489. (function (BABYLON) {
  12490. var CustomProceduralTexture = (function (_super) {
  12491. __extends(CustomProceduralTexture, _super);
  12492. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  12493. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  12494. this._animate = true;
  12495. this._time = 0;
  12496. this._texturePath = texturePath;
  12497. //Try to load json
  12498. this.loadJson(texturePath);
  12499. this.refreshRate = 1;
  12500. }
  12501. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  12502. var _this = this;
  12503. var that = this;
  12504. function noConfigFile() {
  12505. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  12506. try {
  12507. that.setFragment(that._texturePath);
  12508. }
  12509. catch (ex) {
  12510. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  12511. }
  12512. }
  12513. var configFileUrl = jsonUrl + "/config.json";
  12514. var xhr = new XMLHttpRequest();
  12515. xhr.open("GET", configFileUrl, true);
  12516. xhr.addEventListener("load", function () {
  12517. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12518. try {
  12519. _this._config = JSON.parse(xhr.response);
  12520. _this.updateShaderUniforms();
  12521. _this.updateTextures();
  12522. _this.setFragment(_this._texturePath + "/custom");
  12523. _this._animate = _this._config.animate;
  12524. _this.refreshRate = _this._config.refreshrate;
  12525. }
  12526. catch (ex) {
  12527. noConfigFile();
  12528. }
  12529. }
  12530. else {
  12531. noConfigFile();
  12532. }
  12533. }, false);
  12534. xhr.addEventListener("error", function (event) {
  12535. noConfigFile();
  12536. }, false);
  12537. try {
  12538. xhr.send();
  12539. }
  12540. catch (ex) {
  12541. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  12542. }
  12543. };
  12544. CustomProceduralTexture.prototype.isReady = function () {
  12545. if (!_super.prototype.isReady.call(this)) {
  12546. return false;
  12547. }
  12548. for (var name in this._textures) {
  12549. var texture = this._textures[name];
  12550. if (!texture.isReady()) {
  12551. return false;
  12552. }
  12553. }
  12554. return true;
  12555. };
  12556. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12557. if (this._animate) {
  12558. this._time += this.getScene().getAnimationRatio() * 0.03;
  12559. this.updateShaderUniforms();
  12560. }
  12561. _super.prototype.render.call(this, useCameraPostProcess);
  12562. };
  12563. CustomProceduralTexture.prototype.updateTextures = function () {
  12564. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  12565. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  12566. }
  12567. };
  12568. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  12569. if (this._config) {
  12570. for (var j = 0; j < this._config.uniforms.length; j++) {
  12571. var uniform = this._config.uniforms[j];
  12572. switch (uniform.type) {
  12573. case "float":
  12574. this.setFloat(uniform.name, uniform.value);
  12575. break;
  12576. case "color3":
  12577. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  12578. break;
  12579. case "color4":
  12580. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  12581. break;
  12582. case "vector2":
  12583. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  12584. break;
  12585. case "vector3":
  12586. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  12587. break;
  12588. }
  12589. }
  12590. }
  12591. this.setFloat("time", this._time);
  12592. };
  12593. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  12594. get: function () {
  12595. return this._animate;
  12596. },
  12597. set: function (value) {
  12598. this._animate = value;
  12599. },
  12600. enumerable: true,
  12601. configurable: true
  12602. });
  12603. return CustomProceduralTexture;
  12604. })(BABYLON.ProceduralTexture);
  12605. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  12606. })(BABYLON || (BABYLON = {}));
  12607. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  12608. var BABYLON;
  12609. (function (BABYLON) {
  12610. var MirrorTexture = (function (_super) {
  12611. __extends(MirrorTexture, _super);
  12612. function MirrorTexture(name, size, scene, generateMipMaps) {
  12613. var _this = this;
  12614. _super.call(this, name, size, scene, generateMipMaps, true);
  12615. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  12616. this._transformMatrix = BABYLON.Matrix.Zero();
  12617. this._mirrorMatrix = BABYLON.Matrix.Zero();
  12618. this.onBeforeRender = function () {
  12619. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  12620. _this._savedViewMatrix = scene.getViewMatrix();
  12621. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  12622. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  12623. scene.clipPlane = _this.mirrorPlane;
  12624. scene.getEngine().cullBackFaces = false;
  12625. };
  12626. this.onAfterRender = function () {
  12627. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  12628. scene.getEngine().cullBackFaces = true;
  12629. delete scene.clipPlane;
  12630. };
  12631. }
  12632. MirrorTexture.prototype.clone = function () {
  12633. var textureSize = this.getSize();
  12634. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12635. // Base texture
  12636. newTexture.hasAlpha = this.hasAlpha;
  12637. newTexture.level = this.level;
  12638. // Mirror Texture
  12639. newTexture.mirrorPlane = this.mirrorPlane.clone();
  12640. newTexture.renderList = this.renderList.slice(0);
  12641. return newTexture;
  12642. };
  12643. return MirrorTexture;
  12644. })(BABYLON.RenderTargetTexture);
  12645. BABYLON.MirrorTexture = MirrorTexture;
  12646. })(BABYLON || (BABYLON = {}));
  12647. //# sourceMappingURL=babylon.mirrorTexture.js.map
  12648. var BABYLON;
  12649. (function (BABYLON) {
  12650. var DynamicTexture = (function (_super) {
  12651. __extends(DynamicTexture, _super);
  12652. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  12653. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12654. _super.call(this, null, scene, !generateMipMaps);
  12655. this.name = name;
  12656. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12657. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12658. this._generateMipMaps = generateMipMaps;
  12659. if (options.getContext) {
  12660. this._canvas = options;
  12661. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12662. }
  12663. else {
  12664. this._canvas = document.createElement("canvas");
  12665. if (options.width) {
  12666. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12667. }
  12668. else {
  12669. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  12670. }
  12671. }
  12672. var textureSize = this.getSize();
  12673. this._canvas.width = textureSize.width;
  12674. this._canvas.height = textureSize.height;
  12675. this._context = this._canvas.getContext("2d");
  12676. }
  12677. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  12678. get: function () {
  12679. return true;
  12680. },
  12681. enumerable: true,
  12682. configurable: true
  12683. });
  12684. DynamicTexture.prototype.scale = function (ratio) {
  12685. var textureSize = this.getSize();
  12686. textureSize.width *= ratio;
  12687. textureSize.height *= ratio;
  12688. this._canvas.width = textureSize.width;
  12689. this._canvas.height = textureSize.height;
  12690. this.releaseInternalTexture();
  12691. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  12692. };
  12693. DynamicTexture.prototype.getContext = function () {
  12694. return this._context;
  12695. };
  12696. DynamicTexture.prototype.clear = function () {
  12697. var size = this.getSize();
  12698. this._context.fillRect(0, 0, size.width, size.height);
  12699. };
  12700. DynamicTexture.prototype.update = function (invertY) {
  12701. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  12702. };
  12703. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  12704. if (update === void 0) { update = true; }
  12705. var size = this.getSize();
  12706. if (clearColor) {
  12707. this._context.fillStyle = clearColor;
  12708. this._context.fillRect(0, 0, size.width, size.height);
  12709. }
  12710. this._context.font = font;
  12711. if (x === null) {
  12712. var textSize = this._context.measureText(text);
  12713. x = (size.width - textSize.width) / 2;
  12714. }
  12715. this._context.fillStyle = color;
  12716. this._context.fillText(text, x, y);
  12717. if (update) {
  12718. this.update(invertY);
  12719. }
  12720. };
  12721. DynamicTexture.prototype.clone = function () {
  12722. var textureSize = this.getSize();
  12723. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12724. // Base texture
  12725. newTexture.hasAlpha = this.hasAlpha;
  12726. newTexture.level = this.level;
  12727. // Dynamic Texture
  12728. newTexture.wrapU = this.wrapU;
  12729. newTexture.wrapV = this.wrapV;
  12730. return newTexture;
  12731. };
  12732. return DynamicTexture;
  12733. })(BABYLON.Texture);
  12734. BABYLON.DynamicTexture = DynamicTexture;
  12735. })(BABYLON || (BABYLON = {}));
  12736. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12737. var BABYLON;
  12738. (function (BABYLON) {
  12739. var VideoTexture = (function (_super) {
  12740. __extends(VideoTexture, _super);
  12741. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12742. var _this = this;
  12743. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12744. _super.call(this, null, scene, !generateMipMaps, invertY);
  12745. this._autoLaunch = true;
  12746. this.name = name;
  12747. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12748. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12749. var requiredWidth = size.width || size;
  12750. var requiredHeight = size.height || size;
  12751. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12752. var textureSize = this.getSize();
  12753. this.video = document.createElement("video");
  12754. this.video.width = textureSize.width;
  12755. this.video.height = textureSize.height;
  12756. this.video.autoplay = false;
  12757. this.video.loop = true;
  12758. this.video.addEventListener("canplaythrough", function () {
  12759. if (_this._texture) {
  12760. _this._texture.isReady = true;
  12761. }
  12762. });
  12763. urls.forEach(function (url) {
  12764. var source = document.createElement("source");
  12765. source.src = url;
  12766. _this.video.appendChild(source);
  12767. });
  12768. this._lastUpdate = BABYLON.Tools.Now;
  12769. }
  12770. VideoTexture.prototype.update = function () {
  12771. if (this._autoLaunch) {
  12772. this._autoLaunch = false;
  12773. this.video.play();
  12774. }
  12775. var now = BABYLON.Tools.Now;
  12776. if (now - this._lastUpdate < 15) {
  12777. return false;
  12778. }
  12779. this._lastUpdate = now;
  12780. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  12781. return true;
  12782. };
  12783. return VideoTexture;
  12784. })(BABYLON.Texture);
  12785. BABYLON.VideoTexture = VideoTexture;
  12786. })(BABYLON || (BABYLON = {}));
  12787. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  12788. (function (BABYLON) {
  12789. var EffectFallbacks = (function () {
  12790. function EffectFallbacks() {
  12791. this._defines = {};
  12792. this._currentRank = 32;
  12793. this._maxRank = -1;
  12794. }
  12795. EffectFallbacks.prototype.addFallback = function (rank, define) {
  12796. if (!this._defines[rank]) {
  12797. if (rank < this._currentRank) {
  12798. this._currentRank = rank;
  12799. }
  12800. if (rank > this._maxRank) {
  12801. this._maxRank = rank;
  12802. }
  12803. this._defines[rank] = new Array();
  12804. }
  12805. this._defines[rank].push(define);
  12806. };
  12807. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  12808. get: function () {
  12809. return this._currentRank <= this._maxRank;
  12810. },
  12811. enumerable: true,
  12812. configurable: true
  12813. });
  12814. EffectFallbacks.prototype.reduce = function (currentDefines) {
  12815. var currentFallbacks = this._defines[this._currentRank];
  12816. for (var index = 0; index < currentFallbacks.length; index++) {
  12817. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  12818. }
  12819. this._currentRank++;
  12820. return currentDefines;
  12821. };
  12822. return EffectFallbacks;
  12823. })();
  12824. BABYLON.EffectFallbacks = EffectFallbacks;
  12825. var Effect = (function () {
  12826. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  12827. var _this = this;
  12828. this._isReady = false;
  12829. this._compilationError = "";
  12830. this._valueCache = [];
  12831. this._engine = engine;
  12832. this.name = baseName;
  12833. this.defines = defines;
  12834. this._uniformsNames = uniformsNames.concat(samplers);
  12835. this._samplers = samplers;
  12836. this._attributesNames = attributesNames;
  12837. this.onError = onError;
  12838. this.onCompiled = onCompiled;
  12839. var vertexSource;
  12840. var fragmentSource;
  12841. if (baseName.vertexElement) {
  12842. vertexSource = document.getElementById(baseName.vertexElement);
  12843. if (!vertexSource) {
  12844. vertexSource = baseName.vertexElement;
  12845. }
  12846. }
  12847. else {
  12848. vertexSource = baseName.vertex || baseName;
  12849. }
  12850. if (baseName.fragmentElement) {
  12851. fragmentSource = document.getElementById(baseName.fragmentElement);
  12852. if (!fragmentSource) {
  12853. fragmentSource = baseName.fragmentElement;
  12854. }
  12855. }
  12856. else {
  12857. fragmentSource = baseName.fragment || baseName;
  12858. }
  12859. this._loadVertexShader(vertexSource, function (vertexCode) {
  12860. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  12861. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  12862. });
  12863. });
  12864. }
  12865. // Properties
  12866. Effect.prototype.isReady = function () {
  12867. return this._isReady;
  12868. };
  12869. Effect.prototype.getProgram = function () {
  12870. return this._program;
  12871. };
  12872. Effect.prototype.getAttributesNames = function () {
  12873. return this._attributesNames;
  12874. };
  12875. Effect.prototype.getAttributeLocation = function (index) {
  12876. return this._attributes[index];
  12877. };
  12878. Effect.prototype.getAttributeLocationByName = function (name) {
  12879. var index = this._attributesNames.indexOf(name);
  12880. return this._attributes[index];
  12881. };
  12882. Effect.prototype.getAttributesCount = function () {
  12883. return this._attributes.length;
  12884. };
  12885. Effect.prototype.getUniformIndex = function (uniformName) {
  12886. return this._uniformsNames.indexOf(uniformName);
  12887. };
  12888. Effect.prototype.getUniform = function (uniformName) {
  12889. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  12890. };
  12891. Effect.prototype.getSamplers = function () {
  12892. return this._samplers;
  12893. };
  12894. Effect.prototype.getCompilationError = function () {
  12895. return this._compilationError;
  12896. };
  12897. // Methods
  12898. Effect.prototype._loadVertexShader = function (vertex, callback) {
  12899. // DOM element ?
  12900. if (vertex instanceof HTMLElement) {
  12901. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  12902. callback(vertexCode);
  12903. return;
  12904. }
  12905. // Is in local store ?
  12906. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  12907. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  12908. return;
  12909. }
  12910. var vertexShaderUrl;
  12911. if (vertex[0] === ".") {
  12912. vertexShaderUrl = vertex;
  12913. }
  12914. else {
  12915. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  12916. }
  12917. // Vertex shader
  12918. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  12919. };
  12920. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  12921. // DOM element ?
  12922. if (fragment instanceof HTMLElement) {
  12923. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  12924. callback(fragmentCode);
  12925. return;
  12926. }
  12927. // Is in local store ?
  12928. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  12929. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  12930. return;
  12931. }
  12932. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  12933. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  12934. return;
  12935. }
  12936. var fragmentShaderUrl;
  12937. if (fragment[0] === ".") {
  12938. fragmentShaderUrl = fragment;
  12939. }
  12940. else {
  12941. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  12942. }
  12943. // Fragment shader
  12944. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  12945. };
  12946. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  12947. try {
  12948. var engine = this._engine;
  12949. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  12950. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  12951. this._attributes = engine.getAttributes(this._program, attributesNames);
  12952. for (var index = 0; index < this._samplers.length; index++) {
  12953. var sampler = this.getUniform(this._samplers[index]);
  12954. if (sampler == null) {
  12955. this._samplers.splice(index, 1);
  12956. index--;
  12957. }
  12958. }
  12959. engine.bindSamplers(this);
  12960. this._isReady = true;
  12961. if (this.onCompiled) {
  12962. this.onCompiled(this);
  12963. }
  12964. }
  12965. catch (e) {
  12966. // Is it a problem with precision?
  12967. if (e.message.indexOf("highp") !== -1) {
  12968. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  12969. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  12970. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12971. return;
  12972. }
  12973. // Let's go through fallbacks then
  12974. if (fallbacks && fallbacks.isMoreFallbacks) {
  12975. defines = fallbacks.reduce(defines);
  12976. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12977. }
  12978. else {
  12979. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  12980. BABYLON.Tools.Error("Defines: " + defines);
  12981. BABYLON.Tools.Error("Error: " + e.message);
  12982. this._compilationError = e.message;
  12983. if (this.onError) {
  12984. this.onError(this, this._compilationError);
  12985. }
  12986. }
  12987. }
  12988. };
  12989. Effect.prototype._bindTexture = function (channel, texture) {
  12990. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  12991. };
  12992. Effect.prototype.setTexture = function (channel, texture) {
  12993. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  12994. };
  12995. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12996. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  12997. };
  12998. //public _cacheMatrix(uniformName, matrix) {
  12999. // if (!this._valueCache[uniformName]) {
  13000. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13001. // }
  13002. // for (var index = 0; index < 16; index++) {
  13003. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13004. // }
  13005. //};
  13006. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13007. if (!this._valueCache[uniformName]) {
  13008. this._valueCache[uniformName] = [x, y];
  13009. return;
  13010. }
  13011. this._valueCache[uniformName][0] = x;
  13012. this._valueCache[uniformName][1] = y;
  13013. };
  13014. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13015. if (!this._valueCache[uniformName]) {
  13016. this._valueCache[uniformName] = [x, y, z];
  13017. return;
  13018. }
  13019. this._valueCache[uniformName][0] = x;
  13020. this._valueCache[uniformName][1] = y;
  13021. this._valueCache[uniformName][2] = z;
  13022. };
  13023. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13024. if (!this._valueCache[uniformName]) {
  13025. this._valueCache[uniformName] = [x, y, z, w];
  13026. return;
  13027. }
  13028. this._valueCache[uniformName][0] = x;
  13029. this._valueCache[uniformName][1] = y;
  13030. this._valueCache[uniformName][2] = z;
  13031. this._valueCache[uniformName][3] = w;
  13032. };
  13033. Effect.prototype.setArray = function (uniformName, array) {
  13034. this._engine.setArray(this.getUniform(uniformName), array);
  13035. return this;
  13036. };
  13037. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13038. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13039. return this;
  13040. };
  13041. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13042. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13043. // return;
  13044. //this._cacheMatrix(uniformName, matrix);
  13045. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13046. return this;
  13047. };
  13048. Effect.prototype.setFloat = function (uniformName, value) {
  13049. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13050. return this;
  13051. this._valueCache[uniformName] = value;
  13052. this._engine.setFloat(this.getUniform(uniformName), value);
  13053. return this;
  13054. };
  13055. Effect.prototype.setBool = function (uniformName, bool) {
  13056. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13057. return this;
  13058. this._valueCache[uniformName] = bool;
  13059. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13060. return this;
  13061. };
  13062. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13063. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13064. return this;
  13065. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13066. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13067. return this;
  13068. };
  13069. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13070. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13071. return this;
  13072. this._cacheFloat2(uniformName, x, y);
  13073. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13074. return this;
  13075. };
  13076. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13077. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13078. return this;
  13079. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13080. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13081. return this;
  13082. };
  13083. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13084. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13085. return this;
  13086. this._cacheFloat3(uniformName, x, y, z);
  13087. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13088. return this;
  13089. };
  13090. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13091. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13092. return this;
  13093. this._cacheFloat4(uniformName, x, y, z, w);
  13094. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13095. return this;
  13096. };
  13097. Effect.prototype.setColor3 = function (uniformName, color3) {
  13098. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13099. return this;
  13100. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13101. this._engine.setColor3(this.getUniform(uniformName), color3);
  13102. return this;
  13103. };
  13104. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13105. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b && this._valueCache[uniformName][3] === alpha)
  13106. return this;
  13107. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13108. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13109. return this;
  13110. };
  13111. // Statics
  13112. Effect.ShadersStore={anaglyphPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\n\nvoid main(void)\n{\n vec4 leftFrag = texture2D(leftSampler, vUV);\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\n\n vec4 rightFrag = texture2D(textureSampler, vUV);\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\n\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\n}",
  13113. blackAndWhitePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n float luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\n gl_FragColor = vec4(luminance, luminance, luminance, 1.0);\n}",
  13114. blurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Parameters\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nvoid main(void)\n{\n float weights[7];\n weights[0] = 0.05;\n weights[1] = 0.1;\n weights[2] = 0.2;\n weights[3] = 0.3;\n weights[4] = 0.2;\n weights[5] = 0.1;\n weights[6] = 0.05;\n\n vec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\n vec2 texelStep = texelSize * direction * blurWidth;\n vec2 start = vUV - 3.0 * texelStep;\n\n vec4 baseColor = vec4(0., 0., 0., 0.);\n vec2 texelOffset = vec2(0., 0.);\n\n for (int i = 0; i < 7; i++)\n {\n baseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\n texelOffset += texelStep;\n }\n\n gl_FragColor = baseColor;\n}",
  13115. brickPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfBricksHeight;\nuniform float numberOfBricksWidth;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvoid main(void)\n{\n float brickW = 1.0 / numberOfBricksWidth;\n float brickH = 1.0 / numberOfBricksHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.05;\n vec3 color = brickColor;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\n\n if (brickColorSwitch == 0.0)\n color = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\n else if (brickColorSwitch == 2.0)\n color = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\n }\n\n gl_FragColor = vec4(color, 1.0);\n}",
  13116. cloudPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\n\nuniform vec3 skyColor;\nuniform vec3 cloudColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n\n vec2 p = vUV * 12.0;\n vec3 c = mix(skyColor, cloudColor, fbm(p));\n gl_FragColor = vec4(c, 1);\n\n}",
  13117. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13118. colorVertexShader:"precision highp float;\n\n// Attributes\nattribute vec3 position;\n\n// Uniforms\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  13119. convolutionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform float kernel[9];\n\nvoid main(void)\n{\n vec2 onePixel = vec2(1.0, 1.0) / screenSize;\n vec4 colorSum =\n texture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\n\n float kernelWeight =\n kernel[0] +\n kernel[1] +\n kernel[2] +\n kernel[3] +\n kernel[4] +\n kernel[5] +\n kernel[6] +\n kernel[7] +\n kernel[8];\n\n if (kernelWeight <= 0.0) {\n kernelWeight = 1.0;\n }\n\n gl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\n}",
  13120. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / 1500.0)) < depth.z) visibility -= 0.2;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  13121. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#else\n finalWorld = finalWorld * (m0 + m1 + m2);\n#endif \n\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n\n // Point size\n#ifdef POINTSIZE\n gl_PointSize = pointSize;\n#endif\n}",
  13122. depthPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nuniform float far;\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n float depth = gl_FragCoord.z / far;\n gl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\n}",
  13123. depthVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  13124. displayPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(passSampler, vUV);\n}",
  13125. filterPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform mat4 kernelMatrix;\n\nvoid main(void)\n{\n vec3 baseColor = texture2D(textureSampler, vUV).rgb;\n vec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\n\n gl_FragColor = vec4(updatedColor, 1.0);\n}",
  13126. firePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform float time;\nuniform vec3 c1;\nuniform vec3 c2;\nuniform vec3 c3;\nuniform vec3 c4;\nuniform vec3 c5;\nuniform vec3 c6;\nuniform vec2 speed;\nuniform float shift;\nuniform float alphaThreshold;\n\nvarying vec2 vUV;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n vec2 p = vUV * 8.0;\n float q = fbm(p - time * 0.1);\n vec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\n vec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\n vec3 color = c * cos(shift * vUV.y);\n float luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\n\n gl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\n}",
  13127. fxaaPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\n\nvoid main(){\n vec2 localTexelSize = texelSize;\n vec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\n vec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\n vec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\n vec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\n vec4 rgbM = texture2D(textureSampler, vUV);\n vec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n vec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\n\n float dirReduce = max(\n (lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\n FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * localTexelSize;\n\n vec4 rgbA = 0.5 * (\n texture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\n texture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\n\n vec4 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(textureSampler, vUV + dir * -0.5) +\n texture2D(textureSampler, vUV + dir * 0.5));\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax)) {\n gl_FragColor = rgbA;\n }\n else {\n gl_FragColor = rgbB;\n }\n}",
  13128. grassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform vec3 herb1Color;\nuniform vec3 herb2Color;\nuniform vec3 herb3Color;\nuniform vec3 groundColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n vec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\n color = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\n color = mix(color, herb3Color, rand(gl_FragCoord.xy));\n color = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\n gl_FragColor = vec4(color, 1.0);\n}",
  13129. layerPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  13130. layerVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 textureMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  13131. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return 0.;\n }\n return 1.;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW;\n if (lightData.w == 0.)\n {\n lightVectorW = normalize(lightData.xyz - vPositionW);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\n result[0] = ndl * diffuseColor.rgb;\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = ndl * spotAtten * diffuseColor.rgb;\n result[1] = specComp * specularColor * spotAtten;\n result[2] = vec3(0.);\n\n return result;\n }\n\n result[0] = vec3(0.);\n result[1] = vec3(0.);\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\n mat3 result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = mix(groundColor, diffuseColor.rgb, ndl);\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n mat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\n mat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n mat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  13132. legacydefaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return position;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n finalWorld = world;\n#endif\n\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef REFLECTION\n vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  13133. lensFlarePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  13134. lensFlareVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 viewportMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\n}",
  13135. marblePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfTilesHeight;\nuniform float numberOfTilesWidth;\nuniform float amplitude;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat turbulence(vec2 P)\n{\n float val = 0.0;\n float freq = 1.0;\n for (int i = 0; i < 4; i++)\n {\n val += abs(noise(P*freq) / freq);\n freq *= 2.07;\n }\n return val;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvec3 marble_color(float x)\n{\n vec3 col;\n x = 0.5*(x + 1.);\n x = sqrt(x); \n x = sqrt(x);\n x = sqrt(x);\n col = vec3(.2 + .75*x); \n col.b *= 0.95; \n return col;\n}\n\nvoid main()\n{\n float brickW = 1.0 / numberOfTilesWidth;\n float brickH = 1.0 / numberOfTilesHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.01;\n vec3 color = brickColor;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\n t += amplitude * turbulence(brickvUV.xy);\n t = sin(t);\n color = marble_color(t);\n }\n\n gl_FragColor = vec4(color, 0.0);\n}",
  13136. oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\n\nvec2 HmdWarp(vec2 in01) {\n\n vec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\n float rSq = theta.x * theta.x + theta.y * theta.y;\n vec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\n return LensCenter + Scale * rvector;\n}\n\nvoid main(void)\n{\n vec2 tc = HmdWarp(vUV);\n if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n else{\n gl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n }\n}",
  13137. outlinePixelShader:"precision highp float;\n\nuniform vec4 color;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void) {\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n gl_FragColor = color;\n}",
  13138. outlineVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\nattribute vec3 normal;\n\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\nuniform float offset;\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n vec3 offsetPosition = position + normal * offset;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  13139. particlesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\nvoid main(void) {\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n gl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\n}",
  13140. particlesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\n// Uniforms\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n float size = options.y;\n float angle = options.x;\n vec2 offset = options.zw;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n \n vColor = color;\n vUV = offset;\n\n // Clip plane\n#ifdef CLIPPLANE\n vec4 worldPos = invView * vec4(viewPos, 1.0);\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n}",
  13141. passPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n gl_FragColor = texture2D(textureSampler, vUV);\n}",
  13142. postprocessVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  13143. proceduralVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Output\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n vPosition = position;\n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  13144. refractionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\n// Parameters\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\n\nvoid main() {\n float ref = 1.0 - texture2D(refractionSampler, vUV).r;\n\n vec2 uv = vUV - vec2(0.5);\n vec2 offset = uv * depth * ref;\n vec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\n\n gl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\n}",
  13145. roadPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV; \nuniform vec3 roadColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\n vec3 color = roadColor * ratioy;\n gl_FragColor = vec4(color, 1.0);\n}",
  13146. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bitOffset = vec4(255. * 255. * 255., 255. * 255., 255., 1.);\n const vec4 bitMask = vec4(0., 1. / 255., 1. / 255., 1. / 255.);\n \n vec4 comp = mod(depth * bitOffset * vec4(254.), vec4(255.)) / vec4(254.);\n comp -= comp.xxyz * bitMask;\n \n return comp;\n}\n\n// Thanks to http://devmaster.net/\nvec2 packHalf(float depth) \n{ \n const vec2 bitOffset = vec2(1.0 / 255., 0.);\n vec2 color = vec2(depth, fract(depth * 255.));\n\n return color - (color.yy * bitOffset);\n}\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n#ifdef VSM\n float moment1 = gl_FragCoord.z / gl_FragCoord.w;\n float moment2 = moment1 * moment1;\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(vPosition.z / vPosition.w);\n#endif\n}",
  13147. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n#ifndef VSM\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  13148. spritesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform bool alphaTest;\n\nvarying vec4 vColor;\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return min(1., max(0., fogCoeff));\n}\n#endif\n\n\nvoid main(void) {\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n if (alphaTest) \n {\n if (baseColor.a < 0.95)\n discard;\n }\n\n baseColor *= vColor;\n\n#ifdef FOG\n float fog = CalcFogFactor();\n baseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = baseColor;\n}",
  13149. spritesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\n// Uniforms\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n \n float angle = options.x;\n float size = options.y;\n vec2 offset = options.zw;\n vec2 uvScale = textureInfos.xy;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n\n // Color\n vColor = color;\n \n // Texture\n vec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n\n vUV = (uvOffset + cellInfo.zw) * uvScale;\n\n // Fog\n#ifdef FOG\n fFogDistance = viewPos.z;\n#endif\n}",
  13150. woodPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float ampScale;\nuniform vec3 woodColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\n vec3 wood = woodColor * ratioy;\n gl_FragColor = vec4(wood, 1.0);\n}",
  13151. };
  13152. return Effect;
  13153. })();
  13154. BABYLON.Effect = Effect;
  13155. })(BABYLON || (BABYLON = {}));
  13156. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13157. (function (BABYLON) {
  13158. var Material = (function () {
  13159. function Material(name, scene, doNotAdd) {
  13160. this.name = name;
  13161. this.checkReadyOnEveryCall = true;
  13162. this.checkReadyOnlyOnce = false;
  13163. this.state = "";
  13164. this.alpha = 1.0;
  13165. this.backFaceCulling = true;
  13166. this._wasPreviouslyReady = false;
  13167. this._fillMode = Material.TriangleFillMode;
  13168. this.pointSize = 1.0;
  13169. this.id = name;
  13170. this._scene = scene;
  13171. if (!doNotAdd) {
  13172. scene.materials.push(this);
  13173. }
  13174. }
  13175. Object.defineProperty(Material, "TriangleFillMode", {
  13176. get: function () {
  13177. return Material._TriangleFillMode;
  13178. },
  13179. enumerable: true,
  13180. configurable: true
  13181. });
  13182. Object.defineProperty(Material, "WireFrameFillMode", {
  13183. get: function () {
  13184. return Material._WireFrameFillMode;
  13185. },
  13186. enumerable: true,
  13187. configurable: true
  13188. });
  13189. Object.defineProperty(Material, "PointFillMode", {
  13190. get: function () {
  13191. return Material._PointFillMode;
  13192. },
  13193. enumerable: true,
  13194. configurable: true
  13195. });
  13196. Object.defineProperty(Material.prototype, "wireframe", {
  13197. get: function () {
  13198. return this._fillMode === Material.WireFrameFillMode;
  13199. },
  13200. set: function (value) {
  13201. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13202. },
  13203. enumerable: true,
  13204. configurable: true
  13205. });
  13206. Object.defineProperty(Material.prototype, "pointsCloud", {
  13207. get: function () {
  13208. return this._fillMode === Material.PointFillMode;
  13209. },
  13210. set: function (value) {
  13211. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13212. },
  13213. enumerable: true,
  13214. configurable: true
  13215. });
  13216. Object.defineProperty(Material.prototype, "fillMode", {
  13217. get: function () {
  13218. return this._fillMode;
  13219. },
  13220. set: function (value) {
  13221. this._fillMode = value;
  13222. },
  13223. enumerable: true,
  13224. configurable: true
  13225. });
  13226. Material.prototype.isReady = function (mesh, useInstances) {
  13227. return true;
  13228. };
  13229. Material.prototype.getEffect = function () {
  13230. return this._effect;
  13231. };
  13232. Material.prototype.getScene = function () {
  13233. return this._scene;
  13234. };
  13235. Material.prototype.needAlphaBlending = function () {
  13236. return (this.alpha < 1.0);
  13237. };
  13238. Material.prototype.needAlphaTesting = function () {
  13239. return false;
  13240. };
  13241. Material.prototype.getAlphaTestTexture = function () {
  13242. return null;
  13243. };
  13244. Material.prototype.trackCreation = function (onCompiled, onError) {
  13245. };
  13246. Material.prototype._preBind = function () {
  13247. var engine = this._scene.getEngine();
  13248. engine.enableEffect(this._effect);
  13249. engine.setState(this.backFaceCulling);
  13250. };
  13251. Material.prototype.bind = function (world, mesh) {
  13252. this._scene._cachedMaterial = this;
  13253. if (this.onBind) {
  13254. this.onBind(this);
  13255. }
  13256. };
  13257. Material.prototype.bindOnlyWorldMatrix = function (world) {
  13258. };
  13259. Material.prototype.unbind = function () {
  13260. };
  13261. Material.prototype.dispose = function (forceDisposeEffect) {
  13262. // Remove from scene
  13263. var index = this._scene.materials.indexOf(this);
  13264. this._scene.materials.splice(index, 1);
  13265. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  13266. if (forceDisposeEffect && this._effect) {
  13267. this._scene.getEngine()._releaseEffect(this._effect);
  13268. this._effect = null;
  13269. }
  13270. // Callback
  13271. if (this.onDispose) {
  13272. this.onDispose();
  13273. }
  13274. };
  13275. Material._TriangleFillMode = 0;
  13276. Material._WireFrameFillMode = 1;
  13277. Material._PointFillMode = 2;
  13278. return Material;
  13279. })();
  13280. BABYLON.Material = Material;
  13281. })(BABYLON || (BABYLON = {}));
  13282. //# sourceMappingURL=babylon.material.js.map
  13283. var BABYLON;
  13284. (function (BABYLON) {
  13285. var maxSimultaneousLights = 4;
  13286. var FresnelParameters = (function () {
  13287. function FresnelParameters() {
  13288. this.isEnabled = true;
  13289. this.leftColor = BABYLON.Color3.White();
  13290. this.rightColor = BABYLON.Color3.Black();
  13291. this.bias = 0;
  13292. this.power = 1;
  13293. }
  13294. return FresnelParameters;
  13295. })();
  13296. BABYLON.FresnelParameters = FresnelParameters;
  13297. var StandardMaterial = (function (_super) {
  13298. __extends(StandardMaterial, _super);
  13299. function StandardMaterial(name, scene) {
  13300. var _this = this;
  13301. _super.call(this, name, scene);
  13302. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13303. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  13304. this.specularColor = new BABYLON.Color3(1, 1, 1);
  13305. this.specularPower = 64;
  13306. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  13307. this.useAlphaFromDiffuseTexture = false;
  13308. this.useSpecularOverAlpha = true;
  13309. this.fogEnabled = true;
  13310. this._cachedDefines = null;
  13311. this._renderTargets = new BABYLON.SmartArray(16);
  13312. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  13313. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  13314. this._scaledDiffuse = new BABYLON.Color3();
  13315. this._scaledSpecular = new BABYLON.Color3();
  13316. this.getRenderTargetTextures = function () {
  13317. _this._renderTargets.reset();
  13318. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  13319. _this._renderTargets.push(_this.reflectionTexture);
  13320. }
  13321. return _this._renderTargets;
  13322. };
  13323. }
  13324. StandardMaterial.prototype.needAlphaBlending = function () {
  13325. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  13326. };
  13327. StandardMaterial.prototype.needAlphaTesting = function () {
  13328. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  13329. };
  13330. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  13331. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  13332. };
  13333. StandardMaterial.prototype.getAlphaTestTexture = function () {
  13334. return this.diffuseTexture;
  13335. };
  13336. // Methods
  13337. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  13338. if (this.checkReadyOnlyOnce) {
  13339. if (this._wasPreviouslyReady) {
  13340. return true;
  13341. }
  13342. }
  13343. var scene = this.getScene();
  13344. if (!this.checkReadyOnEveryCall) {
  13345. if (this._renderId === scene.getRenderId()) {
  13346. return true;
  13347. }
  13348. }
  13349. var engine = scene.getEngine();
  13350. var defines = [];
  13351. var fallbacks = new BABYLON.EffectFallbacks();
  13352. // Textures
  13353. if (scene.texturesEnabled) {
  13354. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13355. if (!this.diffuseTexture.isReady()) {
  13356. return false;
  13357. }
  13358. else {
  13359. defines.push("#define DIFFUSE");
  13360. }
  13361. }
  13362. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13363. if (!this.ambientTexture.isReady()) {
  13364. return false;
  13365. }
  13366. else {
  13367. defines.push("#define AMBIENT");
  13368. }
  13369. }
  13370. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13371. if (!this.opacityTexture.isReady()) {
  13372. return false;
  13373. }
  13374. else {
  13375. defines.push("#define OPACITY");
  13376. if (this.opacityTexture.getAlphaFromRGB) {
  13377. defines.push("#define OPACITYRGB");
  13378. }
  13379. }
  13380. }
  13381. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13382. if (!this.reflectionTexture.isReady()) {
  13383. return false;
  13384. }
  13385. else {
  13386. defines.push("#define REFLECTION");
  13387. fallbacks.addFallback(0, "REFLECTION");
  13388. }
  13389. }
  13390. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13391. if (!this.emissiveTexture.isReady()) {
  13392. return false;
  13393. }
  13394. else {
  13395. defines.push("#define EMISSIVE");
  13396. }
  13397. }
  13398. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13399. if (!this.specularTexture.isReady()) {
  13400. return false;
  13401. }
  13402. else {
  13403. defines.push("#define SPECULAR");
  13404. fallbacks.addFallback(0, "SPECULAR");
  13405. }
  13406. }
  13407. }
  13408. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  13409. if (!this.bumpTexture.isReady()) {
  13410. return false;
  13411. }
  13412. else {
  13413. defines.push("#define BUMP");
  13414. fallbacks.addFallback(0, "BUMP");
  13415. }
  13416. }
  13417. // Effect
  13418. if (this.useSpecularOverAlpha) {
  13419. defines.push("#define SPECULAROVERALPHA");
  13420. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  13421. }
  13422. if (scene.clipPlane) {
  13423. defines.push("#define CLIPPLANE");
  13424. }
  13425. if (engine.getAlphaTesting()) {
  13426. defines.push("#define ALPHATEST");
  13427. }
  13428. if (this._shouldUseAlphaFromDiffuseTexture()) {
  13429. defines.push("#define ALPHAFROMDIFFUSE");
  13430. }
  13431. // Point size
  13432. if (this.pointsCloud || scene.forcePointsCloud) {
  13433. defines.push("#define POINTSIZE");
  13434. }
  13435. // Fog
  13436. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13437. defines.push("#define FOG");
  13438. fallbacks.addFallback(1, "FOG");
  13439. }
  13440. var shadowsActivated = false;
  13441. var lightIndex = 0;
  13442. if (scene.lightsEnabled) {
  13443. for (var index = 0; index < scene.lights.length; index++) {
  13444. var light = scene.lights[index];
  13445. if (!light.isEnabled()) {
  13446. continue;
  13447. }
  13448. // Excluded check
  13449. if (light._excludedMeshesIds.length > 0) {
  13450. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  13451. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  13452. if (excludedMesh) {
  13453. light.excludedMeshes.push(excludedMesh);
  13454. }
  13455. }
  13456. light._excludedMeshesIds = [];
  13457. }
  13458. // Included check
  13459. if (light._includedOnlyMeshesIds.length > 0) {
  13460. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  13461. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  13462. if (includedOnlyMesh) {
  13463. light.includedOnlyMeshes.push(includedOnlyMesh);
  13464. }
  13465. }
  13466. light._includedOnlyMeshesIds = [];
  13467. }
  13468. if (!light.canAffectMesh(mesh)) {
  13469. continue;
  13470. }
  13471. defines.push("#define LIGHT" + lightIndex);
  13472. if (lightIndex > 0) {
  13473. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  13474. }
  13475. var type;
  13476. if (light instanceof BABYLON.SpotLight) {
  13477. type = "#define SPOTLIGHT" + lightIndex;
  13478. }
  13479. else if (light instanceof BABYLON.HemisphericLight) {
  13480. type = "#define HEMILIGHT" + lightIndex;
  13481. }
  13482. else {
  13483. type = "#define POINTDIRLIGHT" + lightIndex;
  13484. }
  13485. defines.push(type);
  13486. if (lightIndex > 0) {
  13487. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  13488. }
  13489. // Shadows
  13490. if (scene.shadowsEnabled) {
  13491. var shadowGenerator = light.getShadowGenerator();
  13492. if (mesh && mesh.receiveShadows && shadowGenerator) {
  13493. defines.push("#define SHADOW" + lightIndex);
  13494. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  13495. if (!shadowsActivated) {
  13496. defines.push("#define SHADOWS");
  13497. shadowsActivated = true;
  13498. }
  13499. if (shadowGenerator.useVarianceShadowMap) {
  13500. defines.push("#define SHADOWVSM" + lightIndex);
  13501. if (lightIndex > 0) {
  13502. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  13503. }
  13504. }
  13505. if (shadowGenerator.usePoissonSampling) {
  13506. defines.push("#define SHADOWPCF" + lightIndex);
  13507. if (lightIndex > 0) {
  13508. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  13509. }
  13510. }
  13511. }
  13512. }
  13513. lightIndex++;
  13514. if (lightIndex === maxSimultaneousLights)
  13515. break;
  13516. }
  13517. }
  13518. if (StandardMaterial.FresnelEnabled) {
  13519. // Fresnel
  13520. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13521. var fresnelRank = 1;
  13522. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13523. defines.push("#define DIFFUSEFRESNEL");
  13524. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  13525. fresnelRank++;
  13526. }
  13527. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13528. defines.push("#define OPACITYFRESNEL");
  13529. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  13530. fresnelRank++;
  13531. }
  13532. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13533. defines.push("#define REFLECTIONFRESNEL");
  13534. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  13535. fresnelRank++;
  13536. }
  13537. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13538. defines.push("#define EMISSIVEFRESNEL");
  13539. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  13540. fresnelRank++;
  13541. }
  13542. defines.push("#define FRESNEL");
  13543. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  13544. }
  13545. }
  13546. // Attribs
  13547. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  13548. if (mesh) {
  13549. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13550. attribs.push(BABYLON.VertexBuffer.UVKind);
  13551. defines.push("#define UV1");
  13552. }
  13553. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13554. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  13555. defines.push("#define UV2");
  13556. }
  13557. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13558. attribs.push(BABYLON.VertexBuffer.ColorKind);
  13559. defines.push("#define VERTEXCOLOR");
  13560. if (mesh.hasVertexAlpha) {
  13561. defines.push("#define VERTEXALPHA");
  13562. }
  13563. }
  13564. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13565. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13566. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13567. defines.push("#define BONES");
  13568. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13569. defines.push("#define BONES4");
  13570. fallbacks.addFallback(0, "BONES4");
  13571. }
  13572. // Instances
  13573. if (useInstances) {
  13574. defines.push("#define INSTANCES");
  13575. attribs.push("world0");
  13576. attribs.push("world1");
  13577. attribs.push("world2");
  13578. attribs.push("world3");
  13579. }
  13580. }
  13581. // Get correct effect
  13582. var join = defines.join("\n");
  13583. if (this._cachedDefines !== join) {
  13584. this._cachedDefines = join;
  13585. scene.resetCachedMaterial();
  13586. // Legacy browser patch
  13587. var shaderName = "default";
  13588. if (!scene.getEngine().getCaps().standardDerivatives) {
  13589. shaderName = "legacydefault";
  13590. }
  13591. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0", "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1", "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2", "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "mBones", "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "darkness0", "darkness1", "darkness2", "darkness3", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"], join, fallbacks, this.onCompiled, this.onError);
  13592. }
  13593. if (!this._effect.isReady()) {
  13594. return false;
  13595. }
  13596. this._renderId = scene.getRenderId();
  13597. this._wasPreviouslyReady = true;
  13598. return true;
  13599. };
  13600. StandardMaterial.prototype.unbind = function () {
  13601. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  13602. this._effect.setTexture("reflection2DSampler", null);
  13603. }
  13604. };
  13605. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  13606. this._effect.setMatrix("world", world);
  13607. };
  13608. StandardMaterial.prototype.bind = function (world, mesh) {
  13609. var scene = this.getScene();
  13610. // Matrices
  13611. this.bindOnlyWorldMatrix(world);
  13612. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  13613. // Bones
  13614. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13615. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  13616. }
  13617. if (scene.getCachedMaterial() !== this) {
  13618. if (StandardMaterial.FresnelEnabled) {
  13619. // Fresnel
  13620. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13621. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  13622. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  13623. }
  13624. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13625. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  13626. }
  13627. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13628. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  13629. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  13630. }
  13631. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13632. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  13633. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  13634. }
  13635. }
  13636. // Textures
  13637. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13638. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  13639. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  13640. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  13641. }
  13642. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13643. this._effect.setTexture("ambientSampler", this.ambientTexture);
  13644. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  13645. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  13646. }
  13647. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13648. this._effect.setTexture("opacitySampler", this.opacityTexture);
  13649. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  13650. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  13651. }
  13652. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13653. if (this.reflectionTexture.isCube) {
  13654. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  13655. }
  13656. else {
  13657. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  13658. }
  13659. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  13660. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  13661. }
  13662. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13663. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  13664. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  13665. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  13666. }
  13667. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13668. this._effect.setTexture("specularSampler", this.specularTexture);
  13669. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  13670. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  13671. }
  13672. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  13673. this._effect.setTexture("bumpSampler", this.bumpTexture);
  13674. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  13675. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  13676. }
  13677. // Clip plane
  13678. if (scene.clipPlane) {
  13679. var clipPlane = scene.clipPlane;
  13680. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13681. }
  13682. // Point size
  13683. if (this.pointsCloud) {
  13684. this._effect.setFloat("pointSize", this.pointSize);
  13685. }
  13686. // Colors
  13687. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  13688. // Scaling down color according to emissive
  13689. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13690. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13691. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13692. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  13693. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  13694. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  13695. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  13696. }
  13697. // Scaling down color according to emissive
  13698. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13699. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13700. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13701. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  13702. if (scene.lightsEnabled) {
  13703. var lightIndex = 0;
  13704. for (var index = 0; index < scene.lights.length; index++) {
  13705. var light = scene.lights[index];
  13706. if (!light.isEnabled()) {
  13707. continue;
  13708. }
  13709. if (!light.canAffectMesh(mesh)) {
  13710. continue;
  13711. }
  13712. if (light instanceof BABYLON.PointLight) {
  13713. // Point Light
  13714. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13715. }
  13716. else if (light instanceof BABYLON.DirectionalLight) {
  13717. // Directional Light
  13718. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13719. }
  13720. else if (light instanceof BABYLON.SpotLight) {
  13721. // Spot Light
  13722. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  13723. }
  13724. else if (light instanceof BABYLON.HemisphericLight) {
  13725. // Hemispheric Light
  13726. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  13727. }
  13728. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  13729. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  13730. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  13731. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  13732. // Shadows
  13733. if (scene.shadowsEnabled) {
  13734. var shadowGenerator = light.getShadowGenerator();
  13735. if (mesh.receiveShadows && shadowGenerator) {
  13736. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13737. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13738. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13739. }
  13740. }
  13741. lightIndex++;
  13742. if (lightIndex === maxSimultaneousLights)
  13743. break;
  13744. }
  13745. }
  13746. // View
  13747. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13748. this._effect.setMatrix("view", scene.getViewMatrix());
  13749. }
  13750. // Fog
  13751. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13752. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13753. this._effect.setColor3("vFogColor", scene.fogColor);
  13754. }
  13755. _super.prototype.bind.call(this, world, mesh);
  13756. };
  13757. StandardMaterial.prototype.getAnimatables = function () {
  13758. var results = [];
  13759. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  13760. results.push(this.diffuseTexture);
  13761. }
  13762. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  13763. results.push(this.ambientTexture);
  13764. }
  13765. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  13766. results.push(this.opacityTexture);
  13767. }
  13768. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  13769. results.push(this.reflectionTexture);
  13770. }
  13771. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  13772. results.push(this.emissiveTexture);
  13773. }
  13774. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  13775. results.push(this.specularTexture);
  13776. }
  13777. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  13778. results.push(this.bumpTexture);
  13779. }
  13780. return results;
  13781. };
  13782. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  13783. if (this.diffuseTexture) {
  13784. this.diffuseTexture.dispose();
  13785. }
  13786. if (this.ambientTexture) {
  13787. this.ambientTexture.dispose();
  13788. }
  13789. if (this.opacityTexture) {
  13790. this.opacityTexture.dispose();
  13791. }
  13792. if (this.reflectionTexture) {
  13793. this.reflectionTexture.dispose();
  13794. }
  13795. if (this.emissiveTexture) {
  13796. this.emissiveTexture.dispose();
  13797. }
  13798. if (this.specularTexture) {
  13799. this.specularTexture.dispose();
  13800. }
  13801. if (this.bumpTexture) {
  13802. this.bumpTexture.dispose();
  13803. }
  13804. _super.prototype.dispose.call(this, forceDisposeEffect);
  13805. };
  13806. StandardMaterial.prototype.clone = function (name) {
  13807. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  13808. // Base material
  13809. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  13810. newStandardMaterial.alpha = this.alpha;
  13811. newStandardMaterial.fillMode = this.fillMode;
  13812. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  13813. // Standard material
  13814. if (this.diffuseTexture && this.diffuseTexture.clone) {
  13815. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  13816. }
  13817. if (this.ambientTexture && this.ambientTexture.clone) {
  13818. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  13819. }
  13820. if (this.opacityTexture && this.opacityTexture.clone) {
  13821. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  13822. }
  13823. if (this.reflectionTexture && this.reflectionTexture.clone) {
  13824. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  13825. }
  13826. if (this.emissiveTexture && this.emissiveTexture.clone) {
  13827. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  13828. }
  13829. if (this.specularTexture && this.specularTexture.clone) {
  13830. newStandardMaterial.specularTexture = this.specularTexture.clone();
  13831. }
  13832. if (this.bumpTexture && this.bumpTexture.clone) {
  13833. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  13834. }
  13835. newStandardMaterial.ambientColor = this.ambientColor.clone();
  13836. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  13837. newStandardMaterial.specularColor = this.specularColor.clone();
  13838. newStandardMaterial.specularPower = this.specularPower;
  13839. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  13840. return newStandardMaterial;
  13841. };
  13842. // Statics
  13843. // Flags used to enable or disable a type of texture for all Standard Materials
  13844. StandardMaterial.DiffuseTextureEnabled = true;
  13845. StandardMaterial.AmbientTextureEnabled = true;
  13846. StandardMaterial.OpacityTextureEnabled = true;
  13847. StandardMaterial.ReflectionTextureEnabled = true;
  13848. StandardMaterial.EmissiveTextureEnabled = true;
  13849. StandardMaterial.SpecularTextureEnabled = true;
  13850. StandardMaterial.BumpTextureEnabled = true;
  13851. StandardMaterial.FresnelEnabled = true;
  13852. return StandardMaterial;
  13853. })(BABYLON.Material);
  13854. BABYLON.StandardMaterial = StandardMaterial;
  13855. })(BABYLON || (BABYLON = {}));
  13856. //# sourceMappingURL=babylon.standardMaterial.js.map
  13857. var BABYLON;
  13858. (function (BABYLON) {
  13859. var MultiMaterial = (function (_super) {
  13860. __extends(MultiMaterial, _super);
  13861. function MultiMaterial(name, scene) {
  13862. _super.call(this, name, scene, true);
  13863. this.subMaterials = new Array();
  13864. scene.multiMaterials.push(this);
  13865. }
  13866. // Properties
  13867. MultiMaterial.prototype.getSubMaterial = function (index) {
  13868. if (index < 0 || index >= this.subMaterials.length) {
  13869. return this.getScene().defaultMaterial;
  13870. }
  13871. return this.subMaterials[index];
  13872. };
  13873. // Methods
  13874. MultiMaterial.prototype.isReady = function (mesh) {
  13875. for (var index = 0; index < this.subMaterials.length; index++) {
  13876. var subMaterial = this.subMaterials[index];
  13877. if (subMaterial) {
  13878. if (!this.subMaterials[index].isReady(mesh)) {
  13879. return false;
  13880. }
  13881. }
  13882. }
  13883. return true;
  13884. };
  13885. return MultiMaterial;
  13886. })(BABYLON.Material);
  13887. BABYLON.MultiMaterial = MultiMaterial;
  13888. })(BABYLON || (BABYLON = {}));
  13889. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  13890. (function (BABYLON) {
  13891. var Database = (function () {
  13892. function Database(urlToScene, callbackManifestChecked) {
  13893. // Handling various flavors of prefixed version of IndexedDB
  13894. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  13895. this.callbackManifestChecked = callbackManifestChecked;
  13896. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  13897. this.db = null;
  13898. this.enableSceneOffline = false;
  13899. this.enableTexturesOffline = false;
  13900. this.manifestVersionFound = 0;
  13901. this.mustUpdateRessources = false;
  13902. this.hasReachedQuota = false;
  13903. this.checkManifestFile();
  13904. }
  13905. Database.prototype.checkManifestFile = function () {
  13906. var _this = this;
  13907. function noManifestFile() {
  13908. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  13909. that.enableSceneOffline = false;
  13910. that.enableTexturesOffline = false;
  13911. that.callbackManifestChecked(false);
  13912. }
  13913. var that = this;
  13914. var manifestURL = this.currentSceneUrl + ".manifest";
  13915. var xhr = new XMLHttpRequest();
  13916. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  13917. xhr.open("GET", manifestURLTimeStamped, true);
  13918. xhr.addEventListener("load", function () {
  13919. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13920. try {
  13921. var manifestFile = JSON.parse(xhr.response);
  13922. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  13923. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  13924. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  13925. _this.manifestVersionFound = manifestFile.version;
  13926. }
  13927. if (_this.callbackManifestChecked) {
  13928. _this.callbackManifestChecked(true);
  13929. }
  13930. }
  13931. catch (ex) {
  13932. noManifestFile();
  13933. }
  13934. }
  13935. else {
  13936. noManifestFile();
  13937. }
  13938. }, false);
  13939. xhr.addEventListener("error", function (event) {
  13940. noManifestFile();
  13941. }, false);
  13942. try {
  13943. xhr.send();
  13944. }
  13945. catch (ex) {
  13946. BABYLON.Tools.Error("Error on XHR send request.");
  13947. that.callbackManifestChecked(false);
  13948. }
  13949. };
  13950. Database.prototype.openAsync = function (successCallback, errorCallback) {
  13951. var _this = this;
  13952. function handleError() {
  13953. that.isSupported = false;
  13954. if (errorCallback)
  13955. errorCallback();
  13956. }
  13957. var that = this;
  13958. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  13959. // Your browser doesn't support IndexedDB
  13960. this.isSupported = false;
  13961. if (errorCallback)
  13962. errorCallback();
  13963. }
  13964. else {
  13965. // If the DB hasn't been opened or created yet
  13966. if (!this.db) {
  13967. this.hasReachedQuota = false;
  13968. this.isSupported = true;
  13969. var request = this.idbFactory.open("babylonjs", 1);
  13970. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  13971. request.onerror = function (event) {
  13972. handleError();
  13973. };
  13974. // executes when a version change transaction cannot complete due to other active transactions
  13975. request.onblocked = function (event) {
  13976. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  13977. handleError();
  13978. };
  13979. // DB has been opened successfully
  13980. request.onsuccess = function (event) {
  13981. _this.db = request.result;
  13982. successCallback();
  13983. };
  13984. // Initialization of the DB. Creating Scenes & Textures stores
  13985. request.onupgradeneeded = function (event) {
  13986. _this.db = (event.target).result;
  13987. try {
  13988. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  13989. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  13990. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  13991. }
  13992. catch (ex) {
  13993. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  13994. handleError();
  13995. }
  13996. };
  13997. }
  13998. else {
  13999. if (successCallback)
  14000. successCallback();
  14001. }
  14002. }
  14003. };
  14004. Database.prototype.loadImageFromDB = function (url, image) {
  14005. var _this = this;
  14006. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  14007. var saveAndLoadImage = function () {
  14008. if (!_this.hasReachedQuota && _this.db !== null) {
  14009. // the texture is not yet in the DB, let's try to save it
  14010. _this._saveImageIntoDBAsync(completeURL, image);
  14011. }
  14012. else {
  14013. image.src = url;
  14014. }
  14015. };
  14016. if (!this.mustUpdateRessources) {
  14017. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14018. }
  14019. else {
  14020. saveAndLoadImage();
  14021. }
  14022. };
  14023. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14024. if (this.isSupported && this.db !== null) {
  14025. var texture;
  14026. var transaction = this.db.transaction(["textures"]);
  14027. transaction.onabort = function (event) {
  14028. image.src = url;
  14029. };
  14030. transaction.oncomplete = function (event) {
  14031. var blobTextureURL;
  14032. if (texture) {
  14033. var URL = window.URL || window.webkitURL;
  14034. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14035. image.onerror = function () {
  14036. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14037. image.src = url;
  14038. };
  14039. image.src = blobTextureURL;
  14040. }
  14041. else {
  14042. notInDBCallback();
  14043. }
  14044. };
  14045. var getRequest = transaction.objectStore("textures").get(url);
  14046. getRequest.onsuccess = function (event) {
  14047. texture = (event.target).result;
  14048. };
  14049. getRequest.onerror = function (event) {
  14050. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14051. image.src = url;
  14052. };
  14053. }
  14054. else {
  14055. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14056. image.src = url;
  14057. }
  14058. };
  14059. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14060. var _this = this;
  14061. if (this.isSupported) {
  14062. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14063. var generateBlobUrl = function () {
  14064. var blobTextureURL;
  14065. if (blob) {
  14066. var URL = window.URL || window.webkitURL;
  14067. try {
  14068. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14069. }
  14070. catch (ex) {
  14071. blobTextureURL = URL.createObjectURL(blob);
  14072. }
  14073. }
  14074. image.src = blobTextureURL;
  14075. };
  14076. if (BABYLON.Database.isUASupportingBlobStorage) {
  14077. var xhr = new XMLHttpRequest(), blob;
  14078. xhr.open("GET", url, true);
  14079. xhr.responseType = "blob";
  14080. xhr.addEventListener("load", function () {
  14081. if (xhr.status === 200) {
  14082. // Blob as response (XHR2)
  14083. blob = xhr.response;
  14084. var transaction = _this.db.transaction(["textures"], "readwrite");
  14085. // the transaction could abort because of a QuotaExceededError error
  14086. transaction.onabort = function (event) {
  14087. try {
  14088. if (event.srcElement.error.name === "QuotaExceededError") {
  14089. this.hasReachedQuota = true;
  14090. }
  14091. }
  14092. catch (ex) {
  14093. }
  14094. generateBlobUrl();
  14095. };
  14096. transaction.oncomplete = function (event) {
  14097. generateBlobUrl();
  14098. };
  14099. var newTexture = { textureUrl: url, data: blob };
  14100. try {
  14101. // Put the blob into the dabase
  14102. var addRequest = transaction.objectStore("textures").put(newTexture);
  14103. addRequest.onsuccess = function (event) {
  14104. };
  14105. addRequest.onerror = function (event) {
  14106. generateBlobUrl();
  14107. };
  14108. }
  14109. catch (ex) {
  14110. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14111. if (ex.code === 25) {
  14112. BABYLON.Database.isUASupportingBlobStorage = false;
  14113. }
  14114. image.src = url;
  14115. }
  14116. }
  14117. else {
  14118. image.src = url;
  14119. }
  14120. }, false);
  14121. xhr.addEventListener("error", function (event) {
  14122. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14123. image.src = url;
  14124. }, false);
  14125. xhr.send();
  14126. }
  14127. else {
  14128. image.src = url;
  14129. }
  14130. }
  14131. else {
  14132. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14133. image.src = url;
  14134. }
  14135. };
  14136. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14137. var _this = this;
  14138. var updateVersion = function (event) {
  14139. // the version is not yet in the DB or we need to update it
  14140. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14141. };
  14142. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14143. };
  14144. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14145. var _this = this;
  14146. if (this.isSupported) {
  14147. var version;
  14148. try {
  14149. var transaction = this.db.transaction(["versions"]);
  14150. transaction.oncomplete = function (event) {
  14151. if (version) {
  14152. // If the version in the JSON file is > than the version in DB
  14153. if (_this.manifestVersionFound > version.data) {
  14154. _this.mustUpdateRessources = true;
  14155. updateInDBCallback();
  14156. }
  14157. else {
  14158. callback(version.data);
  14159. }
  14160. }
  14161. else {
  14162. _this.mustUpdateRessources = true;
  14163. updateInDBCallback();
  14164. }
  14165. };
  14166. transaction.onabort = function (event) {
  14167. callback(-1);
  14168. };
  14169. var getRequest = transaction.objectStore("versions").get(url);
  14170. getRequest.onsuccess = function (event) {
  14171. version = (event.target).result;
  14172. };
  14173. getRequest.onerror = function (event) {
  14174. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14175. callback(-1);
  14176. };
  14177. }
  14178. catch (ex) {
  14179. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14180. callback(-1);
  14181. }
  14182. }
  14183. else {
  14184. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14185. callback(-1);
  14186. }
  14187. };
  14188. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14189. var _this = this;
  14190. if (this.isSupported && !this.hasReachedQuota) {
  14191. try {
  14192. // Open a transaction to the database
  14193. var transaction = this.db.transaction(["versions"], "readwrite");
  14194. // the transaction could abort because of a QuotaExceededError error
  14195. transaction.onabort = function (event) {
  14196. try {
  14197. if (event.srcElement.error.name === "QuotaExceededError") {
  14198. _this.hasReachedQuota = true;
  14199. }
  14200. }
  14201. catch (ex) {
  14202. }
  14203. callback(-1);
  14204. };
  14205. transaction.oncomplete = function (event) {
  14206. callback(_this.manifestVersionFound);
  14207. };
  14208. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14209. // Put the scene into the database
  14210. var addRequest = transaction.objectStore("versions").put(newVersion);
  14211. addRequest.onsuccess = function (event) {
  14212. };
  14213. addRequest.onerror = function (event) {
  14214. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14215. };
  14216. }
  14217. catch (ex) {
  14218. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14219. callback(-1);
  14220. }
  14221. }
  14222. else {
  14223. callback(-1);
  14224. }
  14225. };
  14226. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  14227. var _this = this;
  14228. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  14229. var saveAndLoadFile = function (event) {
  14230. // the scene is not yet in the DB, let's try to save it
  14231. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  14232. };
  14233. this._checkVersionFromDB(completeUrl, function (version) {
  14234. if (version !== -1) {
  14235. if (!_this.mustUpdateRessources) {
  14236. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  14237. }
  14238. else {
  14239. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  14240. }
  14241. }
  14242. else {
  14243. errorCallback();
  14244. }
  14245. });
  14246. };
  14247. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  14248. if (this.isSupported) {
  14249. var targetStore;
  14250. if (url.indexOf(".babylon") !== -1) {
  14251. targetStore = "scenes";
  14252. }
  14253. else {
  14254. targetStore = "textures";
  14255. }
  14256. var file;
  14257. var transaction = this.db.transaction([targetStore]);
  14258. transaction.oncomplete = function (event) {
  14259. if (file) {
  14260. callback(file.data);
  14261. }
  14262. else {
  14263. notInDBCallback();
  14264. }
  14265. };
  14266. transaction.onabort = function (event) {
  14267. notInDBCallback();
  14268. };
  14269. var getRequest = transaction.objectStore(targetStore).get(url);
  14270. getRequest.onsuccess = function (event) {
  14271. file = (event.target).result;
  14272. };
  14273. getRequest.onerror = function (event) {
  14274. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  14275. notInDBCallback();
  14276. };
  14277. }
  14278. else {
  14279. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14280. callback();
  14281. }
  14282. };
  14283. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  14284. var _this = this;
  14285. if (this.isSupported) {
  14286. var targetStore;
  14287. if (url.indexOf(".babylon") !== -1) {
  14288. targetStore = "scenes";
  14289. }
  14290. else {
  14291. targetStore = "textures";
  14292. }
  14293. // Create XHR
  14294. var xhr = new XMLHttpRequest(), fileData;
  14295. xhr.open("GET", url, true);
  14296. if (useArrayBuffer) {
  14297. xhr.responseType = "arraybuffer";
  14298. }
  14299. xhr.onprogress = progressCallback;
  14300. xhr.addEventListener("load", function () {
  14301. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  14302. // Blob as response (XHR2)
  14303. //fileData = xhr.responseText;
  14304. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  14305. if (!_this.hasReachedQuota) {
  14306. // Open a transaction to the database
  14307. var transaction = _this.db.transaction([targetStore], "readwrite");
  14308. // the transaction could abort because of a QuotaExceededError error
  14309. transaction.onabort = function (event) {
  14310. try {
  14311. if (event.srcElement.error.name === "QuotaExceededError") {
  14312. this.hasReachedQuota = true;
  14313. }
  14314. }
  14315. catch (ex) {
  14316. }
  14317. callback(fileData);
  14318. };
  14319. transaction.oncomplete = function (event) {
  14320. callback(fileData);
  14321. };
  14322. var newFile;
  14323. if (targetStore === "scenes") {
  14324. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  14325. }
  14326. else {
  14327. newFile = { textureUrl: url, data: fileData };
  14328. }
  14329. try {
  14330. // Put the scene into the database
  14331. var addRequest = transaction.objectStore(targetStore).put(newFile);
  14332. addRequest.onsuccess = function (event) {
  14333. };
  14334. addRequest.onerror = function (event) {
  14335. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  14336. };
  14337. }
  14338. catch (ex) {
  14339. callback(fileData);
  14340. }
  14341. }
  14342. else {
  14343. callback(fileData);
  14344. }
  14345. }
  14346. else {
  14347. callback();
  14348. }
  14349. }, false);
  14350. xhr.addEventListener("error", function (event) {
  14351. BABYLON.Tools.Error("error on XHR request.");
  14352. callback();
  14353. }, false);
  14354. xhr.send();
  14355. }
  14356. else {
  14357. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14358. callback();
  14359. }
  14360. };
  14361. Database.isUASupportingBlobStorage = true;
  14362. Database.parseURL = function (url) {
  14363. var a = document.createElement('a');
  14364. a.href = url;
  14365. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  14366. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  14367. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  14368. return absLocation;
  14369. };
  14370. Database.ReturnFullUrlLocation = function (url) {
  14371. if (url.indexOf("http:/") === -1) {
  14372. return (BABYLON.Database.parseURL(window.location.href) + url);
  14373. }
  14374. else {
  14375. return url;
  14376. }
  14377. };
  14378. return Database;
  14379. })();
  14380. BABYLON.Database = Database;
  14381. })(BABYLON || (BABYLON = {}));
  14382. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  14383. (function (BABYLON) {
  14384. var SpriteManager = (function () {
  14385. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  14386. this.name = name;
  14387. this.cellSize = cellSize;
  14388. this.sprites = new Array();
  14389. this.renderingGroupId = 0;
  14390. this.fogEnabled = true;
  14391. this._vertexDeclaration = [3, 4, 4, 4];
  14392. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  14393. this._capacity = capacity;
  14394. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  14395. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14396. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14397. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  14398. this._scene = scene;
  14399. this._scene.spriteManagers.push(this);
  14400. // VBO
  14401. this._vertexDeclaration = [3, 4, 4, 4];
  14402. this._vertexStrideSize = 15 * 4;
  14403. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14404. var indices = [];
  14405. var index = 0;
  14406. for (var count = 0; count < capacity; count++) {
  14407. indices.push(index);
  14408. indices.push(index + 1);
  14409. indices.push(index + 2);
  14410. indices.push(index);
  14411. indices.push(index + 2);
  14412. indices.push(index + 3);
  14413. index += 4;
  14414. }
  14415. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14416. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14417. // Effects
  14418. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  14419. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  14420. }
  14421. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  14422. var arrayOffset = index * 15;
  14423. if (offsetX == 0)
  14424. offsetX = this._epsilon;
  14425. else if (offsetX == 1)
  14426. offsetX = 1 - this._epsilon;
  14427. if (offsetY == 0)
  14428. offsetY = this._epsilon;
  14429. else if (offsetY == 1)
  14430. offsetY = 1 - this._epsilon;
  14431. this._vertices[arrayOffset] = sprite.position.x;
  14432. this._vertices[arrayOffset + 1] = sprite.position.y;
  14433. this._vertices[arrayOffset + 2] = sprite.position.z;
  14434. this._vertices[arrayOffset + 3] = sprite.angle;
  14435. this._vertices[arrayOffset + 4] = sprite.size;
  14436. this._vertices[arrayOffset + 5] = offsetX;
  14437. this._vertices[arrayOffset + 6] = offsetY;
  14438. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  14439. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  14440. var offset = (sprite.cellIndex / rowSize) >> 0;
  14441. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  14442. this._vertices[arrayOffset + 10] = offset;
  14443. // Color
  14444. this._vertices[arrayOffset + 11] = sprite.color.r;
  14445. this._vertices[arrayOffset + 12] = sprite.color.g;
  14446. this._vertices[arrayOffset + 13] = sprite.color.b;
  14447. this._vertices[arrayOffset + 14] = sprite.color.a;
  14448. };
  14449. SpriteManager.prototype.render = function () {
  14450. // Check
  14451. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  14452. return;
  14453. var engine = this._scene.getEngine();
  14454. var baseSize = this._spriteTexture.getBaseSize();
  14455. // Sprites
  14456. var deltaTime = engine.getDeltaTime();
  14457. var max = Math.min(this._capacity, this.sprites.length);
  14458. var rowSize = baseSize.width / this.cellSize;
  14459. var offset = 0;
  14460. for (var index = 0; index < max; index++) {
  14461. var sprite = this.sprites[index];
  14462. if (!sprite) {
  14463. continue;
  14464. }
  14465. sprite._animate(deltaTime);
  14466. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  14467. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  14468. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  14469. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  14470. }
  14471. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14472. // Render
  14473. var effect = this._effectBase;
  14474. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14475. effect = this._effectFog;
  14476. }
  14477. engine.enableEffect(effect);
  14478. var viewMatrix = this._scene.getViewMatrix();
  14479. effect.setTexture("diffuseSampler", this._spriteTexture);
  14480. effect.setMatrix("view", viewMatrix);
  14481. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14482. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  14483. // Fog
  14484. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14485. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  14486. effect.setColor3("vFogColor", this._scene.fogColor);
  14487. }
  14488. // VBOs
  14489. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14490. // Draw order
  14491. effect.setBool("alphaTest", true);
  14492. engine.setColorWrite(false);
  14493. engine.draw(true, 0, max * 6);
  14494. engine.setColorWrite(true);
  14495. effect.setBool("alphaTest", false);
  14496. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14497. engine.draw(true, 0, max * 6);
  14498. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14499. };
  14500. SpriteManager.prototype.dispose = function () {
  14501. if (this._vertexBuffer) {
  14502. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14503. this._vertexBuffer = null;
  14504. }
  14505. if (this._indexBuffer) {
  14506. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14507. this._indexBuffer = null;
  14508. }
  14509. if (this._spriteTexture) {
  14510. this._spriteTexture.dispose();
  14511. this._spriteTexture = null;
  14512. }
  14513. // Remove from scene
  14514. var index = this._scene.spriteManagers.indexOf(this);
  14515. this._scene.spriteManagers.splice(index, 1);
  14516. // Callback
  14517. if (this.onDispose) {
  14518. this.onDispose();
  14519. }
  14520. };
  14521. return SpriteManager;
  14522. })();
  14523. BABYLON.SpriteManager = SpriteManager;
  14524. })(BABYLON || (BABYLON = {}));
  14525. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  14526. (function (BABYLON) {
  14527. var Sprite = (function () {
  14528. function Sprite(name, manager) {
  14529. this.name = name;
  14530. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14531. this.size = 1.0;
  14532. this.angle = 0;
  14533. this.cellIndex = 0;
  14534. this.invertU = 0;
  14535. this.invertV = 0;
  14536. this.animations = new Array();
  14537. this._animationStarted = false;
  14538. this._loopAnimation = false;
  14539. this._fromIndex = 0;
  14540. this._toIndex = 0;
  14541. this._delay = 0;
  14542. this._direction = 1;
  14543. this._frameCount = 0;
  14544. this._time = 0;
  14545. this._manager = manager;
  14546. this._manager.sprites.push(this);
  14547. this.position = BABYLON.Vector3.Zero();
  14548. }
  14549. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  14550. this._fromIndex = from;
  14551. this._toIndex = to;
  14552. this._loopAnimation = loop;
  14553. this._delay = delay;
  14554. this._animationStarted = true;
  14555. this._direction = from < to ? 1 : -1;
  14556. this.cellIndex = from;
  14557. this._time = 0;
  14558. };
  14559. Sprite.prototype.stopAnimation = function () {
  14560. this._animationStarted = false;
  14561. };
  14562. Sprite.prototype._animate = function (deltaTime) {
  14563. if (!this._animationStarted)
  14564. return;
  14565. this._time += deltaTime;
  14566. if (this._time > this._delay) {
  14567. this._time = this._time % this._delay;
  14568. this.cellIndex += this._direction;
  14569. if (this.cellIndex == this._toIndex) {
  14570. if (this._loopAnimation) {
  14571. this.cellIndex = this._fromIndex;
  14572. }
  14573. else {
  14574. this._animationStarted = false;
  14575. if (this.disposeWhenFinishedAnimating) {
  14576. this.dispose();
  14577. }
  14578. }
  14579. }
  14580. }
  14581. };
  14582. Sprite.prototype.dispose = function () {
  14583. for (var i = 0; i < this._manager.sprites.length; i++) {
  14584. if (this._manager.sprites[i] == this) {
  14585. this._manager.sprites.splice(i, 1);
  14586. }
  14587. }
  14588. };
  14589. return Sprite;
  14590. })();
  14591. BABYLON.Sprite = Sprite;
  14592. })(BABYLON || (BABYLON = {}));
  14593. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  14594. (function (BABYLON) {
  14595. var Layer = (function () {
  14596. function Layer(name, imgUrl, scene, isBackground, color) {
  14597. this.name = name;
  14598. this._vertexDeclaration = [2];
  14599. this._vertexStrideSize = 2 * 4;
  14600. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  14601. this.isBackground = isBackground === undefined ? true : isBackground;
  14602. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  14603. this._scene = scene;
  14604. this._scene.layers.push(this);
  14605. // VBO
  14606. var vertices = [];
  14607. vertices.push(1, 1);
  14608. vertices.push(-1, 1);
  14609. vertices.push(-1, -1);
  14610. vertices.push(1, -1);
  14611. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14612. // Indices
  14613. var indices = [];
  14614. indices.push(0);
  14615. indices.push(1);
  14616. indices.push(2);
  14617. indices.push(0);
  14618. indices.push(2);
  14619. indices.push(3);
  14620. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14621. // Effects
  14622. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  14623. }
  14624. Layer.prototype.render = function () {
  14625. // Check
  14626. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  14627. return;
  14628. var engine = this._scene.getEngine();
  14629. // Render
  14630. engine.enableEffect(this._effect);
  14631. engine.setState(false);
  14632. // Texture
  14633. this._effect.setTexture("textureSampler", this.texture);
  14634. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  14635. // Color
  14636. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  14637. // VBOs
  14638. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14639. // Draw order
  14640. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14641. engine.draw(true, 0, 6);
  14642. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14643. };
  14644. Layer.prototype.dispose = function () {
  14645. if (this._vertexBuffer) {
  14646. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14647. this._vertexBuffer = null;
  14648. }
  14649. if (this._indexBuffer) {
  14650. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14651. this._indexBuffer = null;
  14652. }
  14653. if (this.texture) {
  14654. this.texture.dispose();
  14655. this.texture = null;
  14656. }
  14657. // Remove from scene
  14658. var index = this._scene.layers.indexOf(this);
  14659. this._scene.layers.splice(index, 1);
  14660. // Callback
  14661. if (this.onDispose) {
  14662. this.onDispose();
  14663. }
  14664. };
  14665. return Layer;
  14666. })();
  14667. BABYLON.Layer = Layer;
  14668. })(BABYLON || (BABYLON = {}));
  14669. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  14670. (function (BABYLON) {
  14671. var Particle = (function () {
  14672. function Particle() {
  14673. this.position = BABYLON.Vector3.Zero();
  14674. this.direction = BABYLON.Vector3.Zero();
  14675. this.color = new BABYLON.Color4(0, 0, 0, 0);
  14676. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  14677. this.lifeTime = 1.0;
  14678. this.age = 0;
  14679. this.size = 0;
  14680. this.angle = 0;
  14681. this.angularSpeed = 0;
  14682. }
  14683. Particle.prototype.copyTo = function (other) {
  14684. other.position.copyFrom(this.position);
  14685. other.direction.copyFrom(this.direction);
  14686. other.color.copyFrom(this.color);
  14687. other.colorStep.copyFrom(this.colorStep);
  14688. other.lifeTime = this.lifeTime;
  14689. other.age = this.age;
  14690. other.size = this.size;
  14691. other.angle = this.angle;
  14692. other.angularSpeed = this.angularSpeed;
  14693. };
  14694. return Particle;
  14695. })();
  14696. BABYLON.Particle = Particle;
  14697. })(BABYLON || (BABYLON = {}));
  14698. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  14699. (function (BABYLON) {
  14700. var randomNumber = function (min, max) {
  14701. if (min === max) {
  14702. return (min);
  14703. }
  14704. var random = Math.random();
  14705. return ((random * (max - min)) + min);
  14706. };
  14707. var ParticleSystem = (function () {
  14708. function ParticleSystem(name, capacity, scene, customEffect) {
  14709. var _this = this;
  14710. this.name = name;
  14711. this.renderingGroupId = 0;
  14712. this.emitter = null;
  14713. this.emitRate = 10;
  14714. this.manualEmitCount = -1;
  14715. this.updateSpeed = 0.01;
  14716. this.targetStopDuration = 0;
  14717. this.disposeOnStop = false;
  14718. this.minEmitPower = 1;
  14719. this.maxEmitPower = 1;
  14720. this.minLifeTime = 1;
  14721. this.maxLifeTime = 1;
  14722. this.minSize = 1;
  14723. this.maxSize = 1;
  14724. this.minAngularSpeed = 0;
  14725. this.maxAngularSpeed = 0;
  14726. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  14727. this.forceDepthWrite = false;
  14728. this.gravity = BABYLON.Vector3.Zero();
  14729. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  14730. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  14731. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  14732. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14733. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14734. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14735. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  14736. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14737. this.particles = new Array();
  14738. this._vertexDeclaration = [3, 4, 4];
  14739. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  14740. this._stockParticles = new Array();
  14741. this._newPartsExcess = 0;
  14742. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  14743. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  14744. this._scaledDirection = BABYLON.Vector3.Zero();
  14745. this._scaledGravity = BABYLON.Vector3.Zero();
  14746. this._currentRenderId = -1;
  14747. this._started = false;
  14748. this._stopped = false;
  14749. this._actualFrame = 0;
  14750. this.id = name;
  14751. this._capacity = capacity;
  14752. this._scene = scene;
  14753. this._customEffect = customEffect;
  14754. scene.particleSystems.push(this);
  14755. // VBO
  14756. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14757. var indices = [];
  14758. var index = 0;
  14759. for (var count = 0; count < capacity; count++) {
  14760. indices.push(index);
  14761. indices.push(index + 1);
  14762. indices.push(index + 2);
  14763. indices.push(index);
  14764. indices.push(index + 2);
  14765. indices.push(index + 3);
  14766. index += 4;
  14767. }
  14768. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14769. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14770. // Default behaviors
  14771. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  14772. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  14773. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  14774. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  14775. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  14776. };
  14777. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  14778. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  14779. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  14780. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  14781. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  14782. };
  14783. this.updateFunction = function (particles) {
  14784. for (var index = 0; index < particles.length; index++) {
  14785. var particle = particles[index];
  14786. particle.age += _this._scaledUpdateSpeed;
  14787. if (particle.age >= particle.lifeTime) {
  14788. _this.recycleParticle(particle);
  14789. index--;
  14790. continue;
  14791. }
  14792. else {
  14793. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  14794. particle.color.addInPlace(_this._scaledColorStep);
  14795. if (particle.color.a < 0)
  14796. particle.color.a = 0;
  14797. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  14798. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  14799. particle.position.addInPlace(_this._scaledDirection);
  14800. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  14801. particle.direction.addInPlace(_this._scaledGravity);
  14802. }
  14803. }
  14804. };
  14805. }
  14806. ParticleSystem.prototype.recycleParticle = function (particle) {
  14807. var lastParticle = this.particles.pop();
  14808. if (lastParticle !== particle) {
  14809. lastParticle.copyTo(particle);
  14810. this._stockParticles.push(lastParticle);
  14811. }
  14812. };
  14813. ParticleSystem.prototype.getCapacity = function () {
  14814. return this._capacity;
  14815. };
  14816. ParticleSystem.prototype.isAlive = function () {
  14817. return this._alive;
  14818. };
  14819. ParticleSystem.prototype.isStarted = function () {
  14820. return this._started;
  14821. };
  14822. ParticleSystem.prototype.start = function () {
  14823. this._started = true;
  14824. this._stopped = false;
  14825. this._actualFrame = 0;
  14826. };
  14827. ParticleSystem.prototype.stop = function () {
  14828. this._stopped = true;
  14829. };
  14830. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  14831. var offset = index * 11;
  14832. this._vertices[offset] = particle.position.x;
  14833. this._vertices[offset + 1] = particle.position.y;
  14834. this._vertices[offset + 2] = particle.position.z;
  14835. this._vertices[offset + 3] = particle.color.r;
  14836. this._vertices[offset + 4] = particle.color.g;
  14837. this._vertices[offset + 5] = particle.color.b;
  14838. this._vertices[offset + 6] = particle.color.a;
  14839. this._vertices[offset + 7] = particle.angle;
  14840. this._vertices[offset + 8] = particle.size;
  14841. this._vertices[offset + 9] = offsetX;
  14842. this._vertices[offset + 10] = offsetY;
  14843. };
  14844. ParticleSystem.prototype._update = function (newParticles) {
  14845. // Update current
  14846. this._alive = this.particles.length > 0;
  14847. this.updateFunction(this.particles);
  14848. // Add new ones
  14849. var worldMatrix;
  14850. if (this.emitter.position) {
  14851. worldMatrix = this.emitter.getWorldMatrix();
  14852. }
  14853. else {
  14854. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  14855. }
  14856. for (var index = 0; index < newParticles; index++) {
  14857. if (this.particles.length === this._capacity) {
  14858. break;
  14859. }
  14860. if (this._stockParticles.length !== 0) {
  14861. var particle = this._stockParticles.pop();
  14862. particle.age = 0;
  14863. }
  14864. else {
  14865. particle = new BABYLON.Particle();
  14866. }
  14867. this.particles.push(particle);
  14868. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  14869. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  14870. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  14871. particle.size = randomNumber(this.minSize, this.maxSize);
  14872. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  14873. this.startPositionFunction(worldMatrix, particle.position);
  14874. var step = randomNumber(0, 1.0);
  14875. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  14876. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  14877. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  14878. }
  14879. };
  14880. ParticleSystem.prototype._getEffect = function () {
  14881. if (this._customEffect) {
  14882. return this._customEffect;
  14883. }
  14884. ;
  14885. var defines = [];
  14886. if (this._scene.clipPlane) {
  14887. defines.push("#define CLIPPLANE");
  14888. }
  14889. // Effect
  14890. var join = defines.join("\n");
  14891. if (this._cachedDefines !== join) {
  14892. this._cachedDefines = join;
  14893. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  14894. }
  14895. return this._effect;
  14896. };
  14897. ParticleSystem.prototype.animate = function () {
  14898. if (!this._started)
  14899. return;
  14900. var effect = this._getEffect();
  14901. // Check
  14902. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  14903. return;
  14904. if (this._currentRenderId === this._scene.getRenderId()) {
  14905. return;
  14906. }
  14907. this._currentRenderId = this._scene.getRenderId();
  14908. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  14909. // determine the number of particles we need to create
  14910. var emitCout;
  14911. if (this.manualEmitCount > -1) {
  14912. emitCout = this.manualEmitCount;
  14913. this.manualEmitCount = 0;
  14914. }
  14915. else {
  14916. emitCout = this.emitRate;
  14917. }
  14918. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  14919. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  14920. if (this._newPartsExcess > 1.0) {
  14921. newParticles += this._newPartsExcess >> 0;
  14922. this._newPartsExcess -= this._newPartsExcess >> 0;
  14923. }
  14924. this._alive = false;
  14925. if (!this._stopped) {
  14926. this._actualFrame += this._scaledUpdateSpeed;
  14927. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  14928. this.stop();
  14929. }
  14930. else {
  14931. newParticles = 0;
  14932. }
  14933. this._update(newParticles);
  14934. // Stopped?
  14935. if (this._stopped) {
  14936. if (!this._alive) {
  14937. this._started = false;
  14938. if (this.disposeOnStop) {
  14939. this._scene._toBeDisposed.push(this);
  14940. }
  14941. }
  14942. }
  14943. // Update VBO
  14944. var offset = 0;
  14945. for (var index = 0; index < this.particles.length; index++) {
  14946. var particle = this.particles[index];
  14947. this._appendParticleVertex(offset++, particle, 0, 0);
  14948. this._appendParticleVertex(offset++, particle, 1, 0);
  14949. this._appendParticleVertex(offset++, particle, 1, 1);
  14950. this._appendParticleVertex(offset++, particle, 0, 1);
  14951. }
  14952. var engine = this._scene.getEngine();
  14953. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14954. };
  14955. ParticleSystem.prototype.render = function () {
  14956. var effect = this._getEffect();
  14957. // Check
  14958. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  14959. return 0;
  14960. var engine = this._scene.getEngine();
  14961. // Render
  14962. engine.enableEffect(effect);
  14963. engine.setState(false);
  14964. var viewMatrix = this._scene.getViewMatrix();
  14965. effect.setTexture("diffuseSampler", this.particleTexture);
  14966. effect.setMatrix("view", viewMatrix);
  14967. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14968. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  14969. if (this._scene.clipPlane) {
  14970. var clipPlane = this._scene.clipPlane;
  14971. var invView = viewMatrix.clone();
  14972. invView.invert();
  14973. effect.setMatrix("invView", invView);
  14974. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14975. }
  14976. // VBOs
  14977. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14978. // Draw order
  14979. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  14980. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14981. }
  14982. else {
  14983. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14984. }
  14985. if (this.forceDepthWrite) {
  14986. engine.setDepthWrite(true);
  14987. }
  14988. engine.draw(true, 0, this.particles.length * 6);
  14989. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14990. return this.particles.length;
  14991. };
  14992. ParticleSystem.prototype.dispose = function () {
  14993. if (this._vertexBuffer) {
  14994. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14995. this._vertexBuffer = null;
  14996. }
  14997. if (this._indexBuffer) {
  14998. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14999. this._indexBuffer = null;
  15000. }
  15001. if (this.particleTexture) {
  15002. this.particleTexture.dispose();
  15003. this.particleTexture = null;
  15004. }
  15005. // Remove from scene
  15006. var index = this._scene.particleSystems.indexOf(this);
  15007. this._scene.particleSystems.splice(index, 1);
  15008. // Callback
  15009. if (this.onDispose) {
  15010. this.onDispose();
  15011. }
  15012. };
  15013. // Clone
  15014. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15015. var result = new ParticleSystem(name, this._capacity, this._scene);
  15016. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15017. if (newEmitter === undefined) {
  15018. newEmitter = this.emitter;
  15019. }
  15020. result.emitter = newEmitter;
  15021. if (this.particleTexture) {
  15022. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15023. }
  15024. result.start();
  15025. return result;
  15026. };
  15027. // Statics
  15028. ParticleSystem.BLENDMODE_ONEONE = 0;
  15029. ParticleSystem.BLENDMODE_STANDARD = 1;
  15030. return ParticleSystem;
  15031. })();
  15032. BABYLON.ParticleSystem = ParticleSystem;
  15033. })(BABYLON || (BABYLON = {}));
  15034. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15035. (function (BABYLON) {
  15036. var Animation = (function () {
  15037. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15038. this.name = name;
  15039. this.targetProperty = targetProperty;
  15040. this.framePerSecond = framePerSecond;
  15041. this.dataType = dataType;
  15042. this.loopMode = loopMode;
  15043. this._offsetsCache = {};
  15044. this._highLimitsCache = {};
  15045. this._stopped = false;
  15046. this.targetPropertyPath = targetProperty.split(".");
  15047. this.dataType = dataType;
  15048. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15049. }
  15050. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15051. var dataType = undefined;
  15052. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15053. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15054. }
  15055. else if (from instanceof BABYLON.Quaternion) {
  15056. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15057. }
  15058. else if (from instanceof BABYLON.Vector3) {
  15059. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15060. }
  15061. else if (from instanceof BABYLON.Vector2) {
  15062. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15063. }
  15064. else if (from instanceof BABYLON.Color3) {
  15065. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15066. }
  15067. if (dataType == undefined) {
  15068. return;
  15069. }
  15070. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15071. var keys = [];
  15072. keys.push({ frame: 0, value: from });
  15073. keys.push({ frame: totalFrame, value: to });
  15074. animation.setKeys(keys);
  15075. mesh.animations.push(animation);
  15076. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15077. };
  15078. // Methods
  15079. Animation.prototype.isStopped = function () {
  15080. return this._stopped;
  15081. };
  15082. Animation.prototype.getKeys = function () {
  15083. return this._keys;
  15084. };
  15085. Animation.prototype.getEasingFunction = function () {
  15086. return this._easingFunction;
  15087. };
  15088. Animation.prototype.setEasingFunction = function (easingFunction) {
  15089. this._easingFunction = easingFunction;
  15090. };
  15091. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15092. return startValue + (endValue - startValue) * gradient;
  15093. };
  15094. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15095. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15096. };
  15097. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15098. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15099. };
  15100. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15101. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15102. };
  15103. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15104. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15105. };
  15106. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15107. var startScale = new BABYLON.Vector3(0, 0, 0);
  15108. var startRotation = new BABYLON.Quaternion();
  15109. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15110. startValue.decompose(startScale, startRotation, startTranslation);
  15111. var endScale = new BABYLON.Vector3(0, 0, 0);
  15112. var endRotation = new BABYLON.Quaternion();
  15113. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15114. endValue.decompose(endScale, endRotation, endTranslation);
  15115. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15116. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15117. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15118. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15119. return result;
  15120. };
  15121. Animation.prototype.clone = function () {
  15122. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15123. clone.setKeys(this._keys);
  15124. return clone;
  15125. };
  15126. Animation.prototype.setKeys = function (values) {
  15127. this._keys = values.slice(0);
  15128. this._offsetsCache = {};
  15129. this._highLimitsCache = {};
  15130. };
  15131. Animation.prototype._getKeyValue = function (value) {
  15132. if (typeof value === "function") {
  15133. return value();
  15134. }
  15135. return value;
  15136. };
  15137. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15138. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15139. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15140. }
  15141. this.currentFrame = currentFrame;
  15142. for (var key = 0; key < this._keys.length; key++) {
  15143. // for each frame, we need the key just before the frame superior
  15144. if (this._keys[key + 1].frame >= currentFrame) {
  15145. var startValue = this._getKeyValue(this._keys[key].value);
  15146. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15147. // gradient : percent of currentFrame between the frame inf and the frame sup
  15148. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15149. // check for easingFunction and correction of gradient
  15150. if (this._easingFunction != null) {
  15151. gradient = this._easingFunction.ease(gradient);
  15152. }
  15153. switch (this.dataType) {
  15154. case Animation.ANIMATIONTYPE_FLOAT:
  15155. switch (loopMode) {
  15156. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15157. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15158. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15159. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15160. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15161. }
  15162. break;
  15163. case Animation.ANIMATIONTYPE_QUATERNION:
  15164. var quaternion = null;
  15165. switch (loopMode) {
  15166. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15167. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15168. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15169. break;
  15170. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15171. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15172. break;
  15173. }
  15174. return quaternion;
  15175. case Animation.ANIMATIONTYPE_VECTOR3:
  15176. switch (loopMode) {
  15177. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15178. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15179. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15180. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15181. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15182. }
  15183. case Animation.ANIMATIONTYPE_VECTOR2:
  15184. switch (loopMode) {
  15185. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15186. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15187. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15188. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15189. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15190. }
  15191. case Animation.ANIMATIONTYPE_COLOR3:
  15192. switch (loopMode) {
  15193. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15194. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15195. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15196. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15197. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15198. }
  15199. case Animation.ANIMATIONTYPE_MATRIX:
  15200. switch (loopMode) {
  15201. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15202. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15203. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15204. return startValue;
  15205. }
  15206. default:
  15207. break;
  15208. }
  15209. break;
  15210. }
  15211. }
  15212. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15213. };
  15214. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15215. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15216. this._stopped = true;
  15217. return false;
  15218. }
  15219. var returnValue = true;
  15220. // Adding a start key at frame 0 if missing
  15221. if (this._keys[0].frame !== 0) {
  15222. var newKey = { frame: 0, value: this._keys[0].value };
  15223. this._keys.splice(0, 0, newKey);
  15224. }
  15225. // Check limits
  15226. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  15227. from = this._keys[0].frame;
  15228. }
  15229. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  15230. to = this._keys[this._keys.length - 1].frame;
  15231. }
  15232. // Compute ratio
  15233. var range = to - from;
  15234. var offsetValue;
  15235. // ratio represents the frame delta between from and to
  15236. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  15237. var highLimitValue = 0;
  15238. if (ratio > range && !loop) {
  15239. returnValue = false;
  15240. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  15241. }
  15242. else {
  15243. // Get max value if required
  15244. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  15245. var keyOffset = to.toString() + from.toString();
  15246. if (!this._offsetsCache[keyOffset]) {
  15247. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15248. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15249. switch (this.dataType) {
  15250. case Animation.ANIMATIONTYPE_FLOAT:
  15251. this._offsetsCache[keyOffset] = toValue - fromValue;
  15252. break;
  15253. case Animation.ANIMATIONTYPE_QUATERNION:
  15254. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15255. break;
  15256. case Animation.ANIMATIONTYPE_VECTOR3:
  15257. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15258. case Animation.ANIMATIONTYPE_VECTOR2:
  15259. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15260. case Animation.ANIMATIONTYPE_COLOR3:
  15261. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15262. default:
  15263. break;
  15264. }
  15265. this._highLimitsCache[keyOffset] = toValue;
  15266. }
  15267. highLimitValue = this._highLimitsCache[keyOffset];
  15268. offsetValue = this._offsetsCache[keyOffset];
  15269. }
  15270. }
  15271. if (offsetValue === undefined) {
  15272. switch (this.dataType) {
  15273. case Animation.ANIMATIONTYPE_FLOAT:
  15274. offsetValue = 0;
  15275. break;
  15276. case Animation.ANIMATIONTYPE_QUATERNION:
  15277. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  15278. break;
  15279. case Animation.ANIMATIONTYPE_VECTOR3:
  15280. offsetValue = BABYLON.Vector3.Zero();
  15281. break;
  15282. case Animation.ANIMATIONTYPE_VECTOR2:
  15283. offsetValue = BABYLON.Vector2.Zero();
  15284. break;
  15285. case Animation.ANIMATIONTYPE_COLOR3:
  15286. offsetValue = BABYLON.Color3.Black();
  15287. }
  15288. }
  15289. // Compute value
  15290. var repeatCount = (ratio / range) >> 0;
  15291. var currentFrame = returnValue ? from + ratio % range : to;
  15292. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  15293. // Set value
  15294. if (this.targetPropertyPath.length > 1) {
  15295. var property = this._target[this.targetPropertyPath[0]];
  15296. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  15297. property = property[this.targetPropertyPath[index]];
  15298. }
  15299. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  15300. }
  15301. else {
  15302. this._target[this.targetPropertyPath[0]] = currentValue;
  15303. }
  15304. if (this._target.markAsDirty) {
  15305. this._target.markAsDirty(this.targetProperty);
  15306. }
  15307. if (!returnValue) {
  15308. this._stopped = true;
  15309. }
  15310. return returnValue;
  15311. };
  15312. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  15313. get: function () {
  15314. return Animation._ANIMATIONTYPE_FLOAT;
  15315. },
  15316. enumerable: true,
  15317. configurable: true
  15318. });
  15319. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  15320. get: function () {
  15321. return Animation._ANIMATIONTYPE_VECTOR3;
  15322. },
  15323. enumerable: true,
  15324. configurable: true
  15325. });
  15326. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  15327. get: function () {
  15328. return Animation._ANIMATIONTYPE_VECTOR2;
  15329. },
  15330. enumerable: true,
  15331. configurable: true
  15332. });
  15333. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  15334. get: function () {
  15335. return Animation._ANIMATIONTYPE_QUATERNION;
  15336. },
  15337. enumerable: true,
  15338. configurable: true
  15339. });
  15340. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  15341. get: function () {
  15342. return Animation._ANIMATIONTYPE_MATRIX;
  15343. },
  15344. enumerable: true,
  15345. configurable: true
  15346. });
  15347. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  15348. get: function () {
  15349. return Animation._ANIMATIONTYPE_COLOR3;
  15350. },
  15351. enumerable: true,
  15352. configurable: true
  15353. });
  15354. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  15355. get: function () {
  15356. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  15357. },
  15358. enumerable: true,
  15359. configurable: true
  15360. });
  15361. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  15362. get: function () {
  15363. return Animation._ANIMATIONLOOPMODE_CYCLE;
  15364. },
  15365. enumerable: true,
  15366. configurable: true
  15367. });
  15368. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  15369. get: function () {
  15370. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  15371. },
  15372. enumerable: true,
  15373. configurable: true
  15374. });
  15375. // Statics
  15376. Animation._ANIMATIONTYPE_FLOAT = 0;
  15377. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  15378. Animation._ANIMATIONTYPE_QUATERNION = 2;
  15379. Animation._ANIMATIONTYPE_MATRIX = 3;
  15380. Animation._ANIMATIONTYPE_COLOR3 = 4;
  15381. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  15382. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  15383. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  15384. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  15385. return Animation;
  15386. })();
  15387. BABYLON.Animation = Animation;
  15388. })(BABYLON || (BABYLON = {}));
  15389. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  15390. (function (BABYLON) {
  15391. var Animatable = (function () {
  15392. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  15393. if (fromFrame === void 0) { fromFrame = 0; }
  15394. if (toFrame === void 0) { toFrame = 100; }
  15395. if (loopAnimation === void 0) { loopAnimation = false; }
  15396. if (speedRatio === void 0) { speedRatio = 1.0; }
  15397. this.target = target;
  15398. this.fromFrame = fromFrame;
  15399. this.toFrame = toFrame;
  15400. this.loopAnimation = loopAnimation;
  15401. this.speedRatio = speedRatio;
  15402. this.onAnimationEnd = onAnimationEnd;
  15403. this._animations = new Array();
  15404. this._paused = false;
  15405. this.animationStarted = false;
  15406. if (animations) {
  15407. this.appendAnimations(target, animations);
  15408. }
  15409. this._scene = scene;
  15410. scene._activeAnimatables.push(this);
  15411. }
  15412. // Methods
  15413. Animatable.prototype.appendAnimations = function (target, animations) {
  15414. for (var index = 0; index < animations.length; index++) {
  15415. var animation = animations[index];
  15416. animation._target = target;
  15417. this._animations.push(animation);
  15418. }
  15419. };
  15420. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  15421. var animations = this._animations;
  15422. for (var index = 0; index < animations.length; index++) {
  15423. if (animations[index].targetProperty === property) {
  15424. return animations[index];
  15425. }
  15426. }
  15427. return null;
  15428. };
  15429. Animatable.prototype.pause = function () {
  15430. if (this._paused) {
  15431. return;
  15432. }
  15433. this._paused = true;
  15434. };
  15435. Animatable.prototype.restart = function () {
  15436. this._paused = false;
  15437. };
  15438. Animatable.prototype.stop = function () {
  15439. var index = this._scene._activeAnimatables.indexOf(this);
  15440. if (index > -1) {
  15441. this._scene._activeAnimatables.splice(index, 1);
  15442. }
  15443. if (this.onAnimationEnd) {
  15444. this.onAnimationEnd();
  15445. }
  15446. };
  15447. Animatable.prototype._animate = function (delay) {
  15448. if (this._paused) {
  15449. if (!this._pausedDelay) {
  15450. this._pausedDelay = delay;
  15451. }
  15452. return true;
  15453. }
  15454. if (!this._localDelayOffset) {
  15455. this._localDelayOffset = delay;
  15456. }
  15457. else if (this._pausedDelay) {
  15458. this._localDelayOffset += delay - this._pausedDelay;
  15459. this._pausedDelay = null;
  15460. }
  15461. // Animating
  15462. var running = false;
  15463. var animations = this._animations;
  15464. for (var index = 0; index < animations.length; index++) {
  15465. var animation = animations[index];
  15466. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  15467. running = running || isRunning;
  15468. }
  15469. if (!running && this.onAnimationEnd) {
  15470. this.onAnimationEnd();
  15471. }
  15472. return running;
  15473. };
  15474. return Animatable;
  15475. })();
  15476. BABYLON.Animatable = Animatable;
  15477. })(BABYLON || (BABYLON = {}));
  15478. //# sourceMappingURL=babylon.animatable.js.map
  15479. var BABYLON;
  15480. (function (BABYLON) {
  15481. var EasingFunction = (function () {
  15482. function EasingFunction() {
  15483. // Properties
  15484. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  15485. }
  15486. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  15487. get: function () {
  15488. return EasingFunction._EASINGMODE_EASEIN;
  15489. },
  15490. enumerable: true,
  15491. configurable: true
  15492. });
  15493. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  15494. get: function () {
  15495. return EasingFunction._EASINGMODE_EASEOUT;
  15496. },
  15497. enumerable: true,
  15498. configurable: true
  15499. });
  15500. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  15501. get: function () {
  15502. return EasingFunction._EASINGMODE_EASEINOUT;
  15503. },
  15504. enumerable: true,
  15505. configurable: true
  15506. });
  15507. EasingFunction.prototype.setEasingMode = function (easingMode) {
  15508. var n = Math.min(Math.max(easingMode, 0), 2);
  15509. this._easingMode = n;
  15510. };
  15511. EasingFunction.prototype.getEasingMode = function () {
  15512. return this._easingMode;
  15513. };
  15514. EasingFunction.prototype.easeInCore = function (gradient) {
  15515. throw new Error('You must implement this method');
  15516. };
  15517. EasingFunction.prototype.ease = function (gradient) {
  15518. switch (this._easingMode) {
  15519. case EasingFunction.EASINGMODE_EASEIN:
  15520. return this.easeInCore(gradient);
  15521. case EasingFunction.EASINGMODE_EASEOUT:
  15522. return (1 - this.easeInCore(1 - gradient));
  15523. }
  15524. if (gradient >= 0.5) {
  15525. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  15526. }
  15527. return (this.easeInCore(gradient * 2) * 0.5);
  15528. };
  15529. //Statics
  15530. EasingFunction._EASINGMODE_EASEIN = 0;
  15531. EasingFunction._EASINGMODE_EASEOUT = 1;
  15532. EasingFunction._EASINGMODE_EASEINOUT = 2;
  15533. return EasingFunction;
  15534. })();
  15535. BABYLON.EasingFunction = EasingFunction;
  15536. var CircleEase = (function (_super) {
  15537. __extends(CircleEase, _super);
  15538. function CircleEase() {
  15539. _super.apply(this, arguments);
  15540. }
  15541. CircleEase.prototype.easeInCore = function (gradient) {
  15542. gradient = Math.max(0, Math.min(1, gradient));
  15543. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  15544. };
  15545. return CircleEase;
  15546. })(EasingFunction);
  15547. BABYLON.CircleEase = CircleEase;
  15548. var BackEase = (function (_super) {
  15549. __extends(BackEase, _super);
  15550. function BackEase(amplitude) {
  15551. if (amplitude === void 0) { amplitude = 1; }
  15552. _super.call(this);
  15553. this.amplitude = amplitude;
  15554. }
  15555. BackEase.prototype.easeInCore = function (gradient) {
  15556. var num = Math.max(0, this.amplitude);
  15557. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  15558. };
  15559. return BackEase;
  15560. })(EasingFunction);
  15561. BABYLON.BackEase = BackEase;
  15562. var BounceEase = (function (_super) {
  15563. __extends(BounceEase, _super);
  15564. function BounceEase(bounces, bounciness) {
  15565. if (bounces === void 0) { bounces = 3; }
  15566. if (bounciness === void 0) { bounciness = 2; }
  15567. _super.call(this);
  15568. this.bounces = bounces;
  15569. this.bounciness = bounciness;
  15570. }
  15571. BounceEase.prototype.easeInCore = function (gradient) {
  15572. var y = Math.max(0.0, this.bounces);
  15573. var bounciness = this.bounciness;
  15574. if (bounciness <= 1.0) {
  15575. bounciness = 1.001;
  15576. }
  15577. var num9 = Math.pow(bounciness, y);
  15578. var num5 = 1.0 - bounciness;
  15579. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  15580. var num15 = gradient * num4;
  15581. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  15582. var num3 = Math.floor(num65);
  15583. var num13 = num3 + 1.0;
  15584. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  15585. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  15586. var num7 = (num8 + num12) * 0.5;
  15587. var num6 = gradient - num7;
  15588. var num2 = num7 - num8;
  15589. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  15590. };
  15591. return BounceEase;
  15592. })(EasingFunction);
  15593. BABYLON.BounceEase = BounceEase;
  15594. var CubicEase = (function (_super) {
  15595. __extends(CubicEase, _super);
  15596. function CubicEase() {
  15597. _super.apply(this, arguments);
  15598. }
  15599. CubicEase.prototype.easeInCore = function (gradient) {
  15600. return (gradient * gradient * gradient);
  15601. };
  15602. return CubicEase;
  15603. })(EasingFunction);
  15604. BABYLON.CubicEase = CubicEase;
  15605. var ElasticEase = (function (_super) {
  15606. __extends(ElasticEase, _super);
  15607. function ElasticEase(oscillations, springiness) {
  15608. if (oscillations === void 0) { oscillations = 3; }
  15609. if (springiness === void 0) { springiness = 3; }
  15610. _super.call(this);
  15611. this.oscillations = oscillations;
  15612. this.springiness = springiness;
  15613. }
  15614. ElasticEase.prototype.easeInCore = function (gradient) {
  15615. var num2;
  15616. var num3 = Math.max(0.0, this.oscillations);
  15617. var num = Math.max(0.0, this.springiness);
  15618. if (num == 0) {
  15619. num2 = gradient;
  15620. }
  15621. else {
  15622. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  15623. }
  15624. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  15625. };
  15626. return ElasticEase;
  15627. })(EasingFunction);
  15628. BABYLON.ElasticEase = ElasticEase;
  15629. var ExponentialEase = (function (_super) {
  15630. __extends(ExponentialEase, _super);
  15631. function ExponentialEase(exponent) {
  15632. if (exponent === void 0) { exponent = 2; }
  15633. _super.call(this);
  15634. this.exponent = exponent;
  15635. }
  15636. ExponentialEase.prototype.easeInCore = function (gradient) {
  15637. if (this.exponent <= 0) {
  15638. return gradient;
  15639. }
  15640. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  15641. };
  15642. return ExponentialEase;
  15643. })(EasingFunction);
  15644. BABYLON.ExponentialEase = ExponentialEase;
  15645. var PowerEase = (function (_super) {
  15646. __extends(PowerEase, _super);
  15647. function PowerEase(power) {
  15648. if (power === void 0) { power = 2; }
  15649. _super.call(this);
  15650. this.power = power;
  15651. }
  15652. PowerEase.prototype.easeInCore = function (gradient) {
  15653. var y = Math.max(0.0, this.power);
  15654. return Math.pow(gradient, y);
  15655. };
  15656. return PowerEase;
  15657. })(EasingFunction);
  15658. BABYLON.PowerEase = PowerEase;
  15659. var QuadraticEase = (function (_super) {
  15660. __extends(QuadraticEase, _super);
  15661. function QuadraticEase() {
  15662. _super.apply(this, arguments);
  15663. }
  15664. QuadraticEase.prototype.easeInCore = function (gradient) {
  15665. return (gradient * gradient);
  15666. };
  15667. return QuadraticEase;
  15668. })(EasingFunction);
  15669. BABYLON.QuadraticEase = QuadraticEase;
  15670. var QuarticEase = (function (_super) {
  15671. __extends(QuarticEase, _super);
  15672. function QuarticEase() {
  15673. _super.apply(this, arguments);
  15674. }
  15675. QuarticEase.prototype.easeInCore = function (gradient) {
  15676. return (gradient * gradient * gradient * gradient);
  15677. };
  15678. return QuarticEase;
  15679. })(EasingFunction);
  15680. BABYLON.QuarticEase = QuarticEase;
  15681. var QuinticEase = (function (_super) {
  15682. __extends(QuinticEase, _super);
  15683. function QuinticEase() {
  15684. _super.apply(this, arguments);
  15685. }
  15686. QuinticEase.prototype.easeInCore = function (gradient) {
  15687. return (gradient * gradient * gradient * gradient * gradient);
  15688. };
  15689. return QuinticEase;
  15690. })(EasingFunction);
  15691. BABYLON.QuinticEase = QuinticEase;
  15692. var SineEase = (function (_super) {
  15693. __extends(SineEase, _super);
  15694. function SineEase() {
  15695. _super.apply(this, arguments);
  15696. }
  15697. SineEase.prototype.easeInCore = function (gradient) {
  15698. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  15699. };
  15700. return SineEase;
  15701. })(EasingFunction);
  15702. BABYLON.SineEase = SineEase;
  15703. var BezierCurveEase = (function (_super) {
  15704. __extends(BezierCurveEase, _super);
  15705. function BezierCurveEase(x1, y1, x2, y2) {
  15706. if (x1 === void 0) { x1 = 0; }
  15707. if (y1 === void 0) { y1 = 0; }
  15708. if (x2 === void 0) { x2 = 1; }
  15709. if (y2 === void 0) { y2 = 1; }
  15710. _super.call(this);
  15711. this.x1 = x1;
  15712. this.y1 = y1;
  15713. this.x2 = x2;
  15714. this.y2 = y2;
  15715. }
  15716. BezierCurveEase.prototype.easeInCore = function (gradient) {
  15717. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  15718. };
  15719. return BezierCurveEase;
  15720. })(EasingFunction);
  15721. BABYLON.BezierCurveEase = BezierCurveEase;
  15722. })(BABYLON || (BABYLON = {}));
  15723. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  15724. (function (BABYLON) {
  15725. var Octree = (function () {
  15726. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  15727. if (maxDepth === void 0) { maxDepth = 2; }
  15728. this.maxDepth = maxDepth;
  15729. this.dynamicContent = new Array();
  15730. this._maxBlockCapacity = maxBlockCapacity || 64;
  15731. this._selectionContent = new BABYLON.SmartArray(1024);
  15732. this._creationFunc = creationFunc;
  15733. }
  15734. // Methods
  15735. Octree.prototype.update = function (worldMin, worldMax, entries) {
  15736. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  15737. };
  15738. Octree.prototype.addMesh = function (entry) {
  15739. for (var index = 0; index < this.blocks.length; index++) {
  15740. var block = this.blocks[index];
  15741. block.addEntry(entry);
  15742. }
  15743. };
  15744. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  15745. this._selectionContent.reset();
  15746. for (var index = 0; index < this.blocks.length; index++) {
  15747. var block = this.blocks[index];
  15748. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  15749. }
  15750. if (allowDuplicate) {
  15751. this._selectionContent.concat(this.dynamicContent);
  15752. }
  15753. else {
  15754. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15755. }
  15756. return this._selectionContent;
  15757. };
  15758. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  15759. this._selectionContent.reset();
  15760. for (var index = 0; index < this.blocks.length; index++) {
  15761. var block = this.blocks[index];
  15762. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  15763. }
  15764. if (allowDuplicate) {
  15765. this._selectionContent.concat(this.dynamicContent);
  15766. }
  15767. else {
  15768. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15769. }
  15770. return this._selectionContent;
  15771. };
  15772. Octree.prototype.intersectsRay = function (ray) {
  15773. this._selectionContent.reset();
  15774. for (var index = 0; index < this.blocks.length; index++) {
  15775. var block = this.blocks[index];
  15776. block.intersectsRay(ray, this._selectionContent);
  15777. }
  15778. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15779. return this._selectionContent;
  15780. };
  15781. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  15782. target.blocks = new Array();
  15783. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  15784. for (var x = 0; x < 2; x++) {
  15785. for (var y = 0; y < 2; y++) {
  15786. for (var z = 0; z < 2; z++) {
  15787. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  15788. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  15789. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  15790. block.addEntries(entries);
  15791. target.blocks.push(block);
  15792. }
  15793. }
  15794. }
  15795. };
  15796. Octree.CreationFuncForMeshes = function (entry, block) {
  15797. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15798. block.entries.push(entry);
  15799. }
  15800. };
  15801. Octree.CreationFuncForSubMeshes = function (entry, block) {
  15802. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15803. block.entries.push(entry);
  15804. }
  15805. };
  15806. return Octree;
  15807. })();
  15808. BABYLON.Octree = Octree;
  15809. })(BABYLON || (BABYLON = {}));
  15810. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  15811. (function (BABYLON) {
  15812. var OctreeBlock = (function () {
  15813. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  15814. this.entries = new Array();
  15815. this._boundingVectors = new Array();
  15816. this._capacity = capacity;
  15817. this._depth = depth;
  15818. this._maxDepth = maxDepth;
  15819. this._creationFunc = creationFunc;
  15820. this._minPoint = minPoint;
  15821. this._maxPoint = maxPoint;
  15822. this._boundingVectors.push(minPoint.clone());
  15823. this._boundingVectors.push(maxPoint.clone());
  15824. this._boundingVectors.push(minPoint.clone());
  15825. this._boundingVectors[2].x = maxPoint.x;
  15826. this._boundingVectors.push(minPoint.clone());
  15827. this._boundingVectors[3].y = maxPoint.y;
  15828. this._boundingVectors.push(minPoint.clone());
  15829. this._boundingVectors[4].z = maxPoint.z;
  15830. this._boundingVectors.push(maxPoint.clone());
  15831. this._boundingVectors[5].z = minPoint.z;
  15832. this._boundingVectors.push(maxPoint.clone());
  15833. this._boundingVectors[6].x = minPoint.x;
  15834. this._boundingVectors.push(maxPoint.clone());
  15835. this._boundingVectors[7].y = minPoint.y;
  15836. }
  15837. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  15838. // Property
  15839. get: function () {
  15840. return this._capacity;
  15841. },
  15842. enumerable: true,
  15843. configurable: true
  15844. });
  15845. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  15846. get: function () {
  15847. return this._minPoint;
  15848. },
  15849. enumerable: true,
  15850. configurable: true
  15851. });
  15852. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  15853. get: function () {
  15854. return this._maxPoint;
  15855. },
  15856. enumerable: true,
  15857. configurable: true
  15858. });
  15859. // Methods
  15860. OctreeBlock.prototype.addEntry = function (entry) {
  15861. if (this.blocks) {
  15862. for (var index = 0; index < this.blocks.length; index++) {
  15863. var block = this.blocks[index];
  15864. block.addEntry(entry);
  15865. }
  15866. return;
  15867. }
  15868. this._creationFunc(entry, this);
  15869. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  15870. this.createInnerBlocks();
  15871. }
  15872. };
  15873. OctreeBlock.prototype.addEntries = function (entries) {
  15874. for (var index = 0; index < entries.length; index++) {
  15875. var mesh = entries[index];
  15876. this.addEntry(mesh);
  15877. }
  15878. };
  15879. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  15880. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  15881. if (this.blocks) {
  15882. for (var index = 0; index < this.blocks.length; index++) {
  15883. var block = this.blocks[index];
  15884. block.select(frustumPlanes, selection, allowDuplicate);
  15885. }
  15886. return;
  15887. }
  15888. if (allowDuplicate) {
  15889. selection.concat(this.entries);
  15890. }
  15891. else {
  15892. selection.concatWithNoDuplicate(this.entries);
  15893. }
  15894. }
  15895. };
  15896. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  15897. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  15898. if (this.blocks) {
  15899. for (var index = 0; index < this.blocks.length; index++) {
  15900. var block = this.blocks[index];
  15901. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  15902. }
  15903. return;
  15904. }
  15905. if (allowDuplicate) {
  15906. selection.concat(this.entries);
  15907. }
  15908. else {
  15909. selection.concatWithNoDuplicate(this.entries);
  15910. }
  15911. }
  15912. };
  15913. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  15914. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  15915. if (this.blocks) {
  15916. for (var index = 0; index < this.blocks.length; index++) {
  15917. var block = this.blocks[index];
  15918. block.intersectsRay(ray, selection);
  15919. }
  15920. return;
  15921. }
  15922. selection.concatWithNoDuplicate(this.entries);
  15923. }
  15924. };
  15925. OctreeBlock.prototype.createInnerBlocks = function () {
  15926. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  15927. };
  15928. return OctreeBlock;
  15929. })();
  15930. BABYLON.OctreeBlock = OctreeBlock;
  15931. })(BABYLON || (BABYLON = {}));
  15932. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  15933. (function (BABYLON) {
  15934. var Bone = (function () {
  15935. function Bone(name, skeleton, parentBone, matrix) {
  15936. this.name = name;
  15937. this.children = new Array();
  15938. this.animations = new Array();
  15939. this._worldTransform = new BABYLON.Matrix();
  15940. this._absoluteTransform = new BABYLON.Matrix();
  15941. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  15942. this._skeleton = skeleton;
  15943. this._matrix = matrix;
  15944. this._baseMatrix = matrix;
  15945. skeleton.bones.push(this);
  15946. if (parentBone) {
  15947. this._parent = parentBone;
  15948. parentBone.children.push(this);
  15949. }
  15950. else {
  15951. this._parent = null;
  15952. }
  15953. this._updateDifferenceMatrix();
  15954. }
  15955. // Members
  15956. Bone.prototype.getParent = function () {
  15957. return this._parent;
  15958. };
  15959. Bone.prototype.getLocalMatrix = function () {
  15960. return this._matrix;
  15961. };
  15962. Bone.prototype.getBaseMatrix = function () {
  15963. return this._baseMatrix;
  15964. };
  15965. Bone.prototype.getWorldMatrix = function () {
  15966. return this._worldTransform;
  15967. };
  15968. Bone.prototype.getInvertedAbsoluteTransform = function () {
  15969. return this._invertedAbsoluteTransform;
  15970. };
  15971. Bone.prototype.getAbsoluteMatrix = function () {
  15972. var matrix = this._matrix.clone();
  15973. var parent = this._parent;
  15974. while (parent) {
  15975. matrix = matrix.multiply(parent.getLocalMatrix());
  15976. parent = parent.getParent();
  15977. }
  15978. return matrix;
  15979. };
  15980. // Methods
  15981. Bone.prototype.updateMatrix = function (matrix) {
  15982. this._matrix = matrix;
  15983. this._skeleton._markAsDirty();
  15984. this._updateDifferenceMatrix();
  15985. };
  15986. Bone.prototype._updateDifferenceMatrix = function () {
  15987. if (this._parent) {
  15988. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  15989. }
  15990. else {
  15991. this._absoluteTransform.copyFrom(this._matrix);
  15992. }
  15993. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  15994. for (var index = 0; index < this.children.length; index++) {
  15995. this.children[index]._updateDifferenceMatrix();
  15996. }
  15997. };
  15998. Bone.prototype.markAsDirty = function () {
  15999. this._skeleton._markAsDirty();
  16000. };
  16001. return Bone;
  16002. })();
  16003. BABYLON.Bone = Bone;
  16004. })(BABYLON || (BABYLON = {}));
  16005. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16006. (function (BABYLON) {
  16007. var Skeleton = (function () {
  16008. function Skeleton(name, id, scene) {
  16009. this.name = name;
  16010. this.id = id;
  16011. this.bones = new Array();
  16012. this._isDirty = true;
  16013. this._identity = BABYLON.Matrix.Identity();
  16014. this.bones = [];
  16015. this._scene = scene;
  16016. scene.skeletons.push(this);
  16017. }
  16018. // Members
  16019. Skeleton.prototype.getTransformMatrices = function () {
  16020. return this._transformMatrices;
  16021. };
  16022. // Methods
  16023. Skeleton.prototype._markAsDirty = function () {
  16024. this._isDirty = true;
  16025. };
  16026. Skeleton.prototype.prepare = function () {
  16027. if (!this._isDirty) {
  16028. return;
  16029. }
  16030. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16031. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16032. }
  16033. for (var index = 0; index < this.bones.length; index++) {
  16034. var bone = this.bones[index];
  16035. var parentBone = bone.getParent();
  16036. if (parentBone) {
  16037. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16038. }
  16039. else {
  16040. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16041. }
  16042. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16043. }
  16044. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16045. this._isDirty = false;
  16046. };
  16047. Skeleton.prototype.getAnimatables = function () {
  16048. if (!this._animatables || this._animatables.length != this.bones.length) {
  16049. this._animatables = [];
  16050. for (var index = 0; index < this.bones.length; index++) {
  16051. this._animatables.push(this.bones[index]);
  16052. }
  16053. }
  16054. return this._animatables;
  16055. };
  16056. Skeleton.prototype.clone = function (name, id) {
  16057. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  16058. for (var index = 0; index < this.bones.length; index++) {
  16059. var source = this.bones[index];
  16060. var parentBone = null;
  16061. if (source.getParent()) {
  16062. var parentIndex = this.bones.indexOf(source.getParent());
  16063. parentBone = result.bones[parentIndex];
  16064. }
  16065. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16066. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16067. }
  16068. return result;
  16069. };
  16070. return Skeleton;
  16071. })();
  16072. BABYLON.Skeleton = Skeleton;
  16073. })(BABYLON || (BABYLON = {}));
  16074. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16075. (function (BABYLON) {
  16076. var PostProcess = (function () {
  16077. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  16078. this.name = name;
  16079. this.width = -1;
  16080. this.height = -1;
  16081. this._reusable = false;
  16082. this._textures = new BABYLON.SmartArray(2);
  16083. this._currentRenderTextureInd = 0;
  16084. if (camera != null) {
  16085. this._camera = camera;
  16086. this._scene = camera.getScene();
  16087. camera.attachPostProcess(this);
  16088. this._engine = this._scene.getEngine();
  16089. }
  16090. else {
  16091. this._engine = engine;
  16092. }
  16093. this._renderRatio = ratio;
  16094. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16095. this._reusable = reusable || false;
  16096. samplers = samplers || [];
  16097. samplers.push("textureSampler");
  16098. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  16099. }
  16100. PostProcess.prototype.isReusable = function () {
  16101. return this._reusable;
  16102. };
  16103. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16104. camera = camera || this._camera;
  16105. var scene = camera.getScene();
  16106. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16107. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16108. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16109. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16110. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16111. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16112. if (this._textures.length > 0) {
  16113. for (var i = 0; i < this._textures.length; i++) {
  16114. this._engine._releaseTexture(this._textures.data[i]);
  16115. }
  16116. this._textures.reset();
  16117. }
  16118. this.width = desiredWidth;
  16119. this.height = desiredHeight;
  16120. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode }));
  16121. if (this._reusable) {
  16122. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode }));
  16123. }
  16124. if (this.onSizeChanged) {
  16125. this.onSizeChanged();
  16126. }
  16127. }
  16128. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16129. if (this.onActivate) {
  16130. this.onActivate(camera);
  16131. }
  16132. // Clear
  16133. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16134. if (this._reusable) {
  16135. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16136. }
  16137. };
  16138. PostProcess.prototype.apply = function () {
  16139. // Check
  16140. if (!this._effect.isReady())
  16141. return null;
  16142. // States
  16143. this._engine.enableEffect(this._effect);
  16144. this._engine.setState(false);
  16145. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16146. this._engine.setDepthBuffer(false);
  16147. this._engine.setDepthWrite(false);
  16148. // Texture
  16149. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16150. // Parameters
  16151. if (this.onApply) {
  16152. this.onApply(this._effect);
  16153. }
  16154. return this._effect;
  16155. };
  16156. PostProcess.prototype.dispose = function (camera) {
  16157. camera = camera || this._camera;
  16158. if (this._textures.length > 0) {
  16159. for (var i = 0; i < this._textures.length; i++) {
  16160. this._engine._releaseTexture(this._textures.data[i]);
  16161. }
  16162. this._textures.reset();
  16163. }
  16164. camera.detachPostProcess(this);
  16165. var index = camera._postProcesses.indexOf(this);
  16166. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  16167. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  16168. }
  16169. };
  16170. return PostProcess;
  16171. })();
  16172. BABYLON.PostProcess = PostProcess;
  16173. })(BABYLON || (BABYLON = {}));
  16174. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  16175. (function (BABYLON) {
  16176. var PostProcessManager = (function () {
  16177. function PostProcessManager(scene) {
  16178. this._vertexDeclaration = [2];
  16179. this._vertexStrideSize = 2 * 4;
  16180. this._scene = scene;
  16181. // VBO
  16182. var vertices = [];
  16183. vertices.push(1, 1);
  16184. vertices.push(-1, 1);
  16185. vertices.push(-1, -1);
  16186. vertices.push(1, -1);
  16187. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16188. // Indices
  16189. var indices = [];
  16190. indices.push(0);
  16191. indices.push(1);
  16192. indices.push(2);
  16193. indices.push(0);
  16194. indices.push(2);
  16195. indices.push(3);
  16196. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16197. }
  16198. // Methods
  16199. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16200. var postProcesses = this._scene.activeCamera._postProcesses;
  16201. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16202. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16203. return false;
  16204. }
  16205. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16206. return true;
  16207. };
  16208. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  16209. var postProcesses = this._scene.activeCamera._postProcesses;
  16210. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16211. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16212. return;
  16213. }
  16214. var engine = this._scene.getEngine();
  16215. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  16216. if (index < postProcessesTakenIndices.length - 1) {
  16217. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  16218. }
  16219. else {
  16220. if (targetTexture) {
  16221. engine.bindFramebuffer(targetTexture);
  16222. }
  16223. else {
  16224. engine.restoreDefaultFramebuffer();
  16225. }
  16226. }
  16227. if (doNotPresent) {
  16228. break;
  16229. }
  16230. var pp = postProcesses[postProcessesTakenIndices[index]];
  16231. var effect = pp.apply();
  16232. if (effect) {
  16233. if (pp.onBeforeRender) {
  16234. pp.onBeforeRender(effect);
  16235. }
  16236. // VBOs
  16237. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16238. // Draw order
  16239. engine.draw(true, 0, 6);
  16240. }
  16241. }
  16242. // Restore depth buffer
  16243. engine.setDepthBuffer(true);
  16244. engine.setDepthWrite(true);
  16245. };
  16246. PostProcessManager.prototype.dispose = function () {
  16247. if (this._vertexBuffer) {
  16248. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16249. this._vertexBuffer = null;
  16250. }
  16251. if (this._indexBuffer) {
  16252. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16253. this._indexBuffer = null;
  16254. }
  16255. };
  16256. return PostProcessManager;
  16257. })();
  16258. BABYLON.PostProcessManager = PostProcessManager;
  16259. })(BABYLON || (BABYLON = {}));
  16260. //# sourceMappingURL=babylon.postProcessManager.js.map
  16261. var BABYLON;
  16262. (function (BABYLON) {
  16263. var PassPostProcess = (function (_super) {
  16264. __extends(PassPostProcess, _super);
  16265. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16266. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  16267. }
  16268. return PassPostProcess;
  16269. })(BABYLON.PostProcess);
  16270. BABYLON.PassPostProcess = PassPostProcess;
  16271. })(BABYLON || (BABYLON = {}));
  16272. //# sourceMappingURL=babylon.passPostProcess.js.map
  16273. var BABYLON;
  16274. (function (BABYLON) {
  16275. var BlurPostProcess = (function (_super) {
  16276. __extends(BlurPostProcess, _super);
  16277. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  16278. var _this = this;
  16279. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  16280. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  16281. this.direction = direction;
  16282. this.blurWidth = blurWidth;
  16283. this.onApply = function (effect) {
  16284. effect.setFloat2("screenSize", _this.width, _this.height);
  16285. effect.setVector2("direction", _this.direction);
  16286. effect.setFloat("blurWidth", _this.blurWidth);
  16287. };
  16288. }
  16289. return BlurPostProcess;
  16290. })(BABYLON.PostProcess);
  16291. BABYLON.BlurPostProcess = BlurPostProcess;
  16292. })(BABYLON || (BABYLON = {}));
  16293. //# sourceMappingURL=babylon.blurPostProcess.js.map
  16294. var BABYLON;
  16295. (function (BABYLON) {
  16296. var FilterPostProcess = (function (_super) {
  16297. __extends(FilterPostProcess, _super);
  16298. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  16299. var _this = this;
  16300. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  16301. this.kernelMatrix = kernelMatrix;
  16302. this.onApply = function (effect) {
  16303. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  16304. };
  16305. }
  16306. return FilterPostProcess;
  16307. })(BABYLON.PostProcess);
  16308. BABYLON.FilterPostProcess = FilterPostProcess;
  16309. })(BABYLON || (BABYLON = {}));
  16310. //# sourceMappingURL=babylon.filterPostProcess.js.map
  16311. var BABYLON;
  16312. (function (BABYLON) {
  16313. var RefractionPostProcess = (function (_super) {
  16314. __extends(RefractionPostProcess, _super);
  16315. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  16316. var _this = this;
  16317. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  16318. this.color = color;
  16319. this.depth = depth;
  16320. this.colorLevel = colorLevel;
  16321. this.onActivate = function (cam) {
  16322. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  16323. };
  16324. this.onApply = function (effect) {
  16325. effect.setColor3("baseColor", _this.color);
  16326. effect.setFloat("depth", _this.depth);
  16327. effect.setFloat("colorLevel", _this.colorLevel);
  16328. effect.setTexture("refractionSampler", _this._refRexture);
  16329. };
  16330. }
  16331. // Methods
  16332. RefractionPostProcess.prototype.dispose = function (camera) {
  16333. if (this._refRexture) {
  16334. this._refRexture.dispose();
  16335. }
  16336. _super.prototype.dispose.call(this, camera);
  16337. };
  16338. return RefractionPostProcess;
  16339. })(BABYLON.PostProcess);
  16340. BABYLON.RefractionPostProcess = RefractionPostProcess;
  16341. })(BABYLON || (BABYLON = {}));
  16342. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  16343. var BABYLON;
  16344. (function (BABYLON) {
  16345. var BlackAndWhitePostProcess = (function (_super) {
  16346. __extends(BlackAndWhitePostProcess, _super);
  16347. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16348. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  16349. }
  16350. return BlackAndWhitePostProcess;
  16351. })(BABYLON.PostProcess);
  16352. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  16353. })(BABYLON || (BABYLON = {}));
  16354. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  16355. var BABYLON;
  16356. (function (BABYLON) {
  16357. var ConvolutionPostProcess = (function (_super) {
  16358. __extends(ConvolutionPostProcess, _super);
  16359. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  16360. var _this = this;
  16361. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  16362. this.kernel = kernel;
  16363. this.onApply = function (effect) {
  16364. effect.setFloat2("screenSize", _this.width, _this.height);
  16365. effect.setArray("kernel", _this.kernel);
  16366. };
  16367. }
  16368. // Statics
  16369. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  16370. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  16371. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  16372. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  16373. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  16374. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  16375. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  16376. return ConvolutionPostProcess;
  16377. })(BABYLON.PostProcess);
  16378. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  16379. })(BABYLON || (BABYLON = {}));
  16380. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  16381. var BABYLON;
  16382. (function (BABYLON) {
  16383. var FxaaPostProcess = (function (_super) {
  16384. __extends(FxaaPostProcess, _super);
  16385. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16386. var _this = this;
  16387. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  16388. this.onSizeChanged = function () {
  16389. _this.texelWidth = 1.0 / _this.width;
  16390. _this.texelHeight = 1.0 / _this.height;
  16391. };
  16392. this.onApply = function (effect) {
  16393. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  16394. };
  16395. }
  16396. return FxaaPostProcess;
  16397. })(BABYLON.PostProcess);
  16398. BABYLON.FxaaPostProcess = FxaaPostProcess;
  16399. })(BABYLON || (BABYLON = {}));
  16400. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  16401. (function (BABYLON) {
  16402. var LensFlare = (function () {
  16403. function LensFlare(size, position, color, imgUrl, system) {
  16404. this.size = size;
  16405. this.position = position;
  16406. this.dispose = function () {
  16407. if (this.texture) {
  16408. this.texture.dispose();
  16409. }
  16410. // Remove from scene
  16411. var index = this._system.lensFlares.indexOf(this);
  16412. this._system.lensFlares.splice(index, 1);
  16413. };
  16414. this.color = color || new BABYLON.Color3(1, 1, 1);
  16415. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  16416. this._system = system;
  16417. system.lensFlares.push(this);
  16418. }
  16419. return LensFlare;
  16420. })();
  16421. BABYLON.LensFlare = LensFlare;
  16422. })(BABYLON || (BABYLON = {}));
  16423. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  16424. (function (BABYLON) {
  16425. var LensFlareSystem = (function () {
  16426. function LensFlareSystem(name, emitter, scene) {
  16427. this.name = name;
  16428. this.lensFlares = new Array();
  16429. this.borderLimit = 300;
  16430. this._vertexDeclaration = [2];
  16431. this._vertexStrideSize = 2 * 4;
  16432. this._isEnabled = true;
  16433. this._scene = scene;
  16434. this._emitter = emitter;
  16435. scene.lensFlareSystems.push(this);
  16436. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  16437. // VBO
  16438. var vertices = [];
  16439. vertices.push(1, 1);
  16440. vertices.push(-1, 1);
  16441. vertices.push(-1, -1);
  16442. vertices.push(1, -1);
  16443. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16444. // Indices
  16445. var indices = [];
  16446. indices.push(0);
  16447. indices.push(1);
  16448. indices.push(2);
  16449. indices.push(0);
  16450. indices.push(2);
  16451. indices.push(3);
  16452. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16453. // Effects
  16454. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  16455. }
  16456. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  16457. get: function () {
  16458. return this._isEnabled;
  16459. },
  16460. set: function (value) {
  16461. this._isEnabled = value;
  16462. },
  16463. enumerable: true,
  16464. configurable: true
  16465. });
  16466. LensFlareSystem.prototype.getScene = function () {
  16467. return this._scene;
  16468. };
  16469. LensFlareSystem.prototype.getEmitter = function () {
  16470. return this._emitter;
  16471. };
  16472. LensFlareSystem.prototype.getEmitterPosition = function () {
  16473. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  16474. };
  16475. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  16476. var position = this.getEmitterPosition();
  16477. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  16478. this._positionX = position.x;
  16479. this._positionY = position.y;
  16480. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  16481. if (position.z > 0) {
  16482. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  16483. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  16484. return true;
  16485. }
  16486. }
  16487. return false;
  16488. };
  16489. LensFlareSystem.prototype._isVisible = function () {
  16490. if (!this._isEnabled) {
  16491. return false;
  16492. }
  16493. var emitterPosition = this.getEmitterPosition();
  16494. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  16495. var distance = direction.length();
  16496. direction.normalize();
  16497. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  16498. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  16499. return !pickInfo.hit || pickInfo.distance > distance;
  16500. };
  16501. LensFlareSystem.prototype.render = function () {
  16502. if (!this._effect.isReady())
  16503. return false;
  16504. var engine = this._scene.getEngine();
  16505. var viewport = this._scene.activeCamera.viewport;
  16506. var globalViewport = viewport.toGlobal(engine);
  16507. // Position
  16508. if (!this.computeEffectivePosition(globalViewport)) {
  16509. return false;
  16510. }
  16511. // Visibility
  16512. if (!this._isVisible()) {
  16513. return false;
  16514. }
  16515. // Intensity
  16516. var awayX;
  16517. var awayY;
  16518. if (this._positionX < this.borderLimit + globalViewport.x) {
  16519. awayX = this.borderLimit + globalViewport.x - this._positionX;
  16520. }
  16521. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  16522. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  16523. }
  16524. else {
  16525. awayX = 0;
  16526. }
  16527. if (this._positionY < this.borderLimit + globalViewport.y) {
  16528. awayY = this.borderLimit + globalViewport.y - this._positionY;
  16529. }
  16530. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  16531. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  16532. }
  16533. else {
  16534. awayY = 0;
  16535. }
  16536. var away = (awayX > awayY) ? awayX : awayY;
  16537. if (away > this.borderLimit) {
  16538. away = this.borderLimit;
  16539. }
  16540. var intensity = 1.0 - (away / this.borderLimit);
  16541. if (intensity < 0) {
  16542. return false;
  16543. }
  16544. if (intensity > 1.0) {
  16545. intensity = 1.0;
  16546. }
  16547. // Position
  16548. var centerX = globalViewport.x + globalViewport.width / 2;
  16549. var centerY = globalViewport.y + globalViewport.height / 2;
  16550. var distX = centerX - this._positionX;
  16551. var distY = centerY - this._positionY;
  16552. // Effects
  16553. engine.enableEffect(this._effect);
  16554. engine.setState(false);
  16555. engine.setDepthBuffer(false);
  16556. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16557. // VBOs
  16558. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16559. for (var index = 0; index < this.lensFlares.length; index++) {
  16560. var flare = this.lensFlares[index];
  16561. var x = centerX - (distX * flare.position);
  16562. var y = centerY - (distY * flare.position);
  16563. var cw = flare.size;
  16564. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  16565. var cx = 2 * (x / globalViewport.width) - 1.0;
  16566. var cy = 1.0 - 2 * (y / globalViewport.height);
  16567. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  16568. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  16569. // Texture
  16570. this._effect.setTexture("textureSampler", flare.texture);
  16571. // Color
  16572. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  16573. // Draw order
  16574. engine.draw(true, 0, 6);
  16575. }
  16576. engine.setDepthBuffer(true);
  16577. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16578. return true;
  16579. };
  16580. LensFlareSystem.prototype.dispose = function () {
  16581. if (this._vertexBuffer) {
  16582. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16583. this._vertexBuffer = null;
  16584. }
  16585. if (this._indexBuffer) {
  16586. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16587. this._indexBuffer = null;
  16588. }
  16589. while (this.lensFlares.length) {
  16590. this.lensFlares[0].dispose();
  16591. }
  16592. // Remove from scene
  16593. var index = this._scene.lensFlareSystems.indexOf(this);
  16594. this._scene.lensFlareSystems.splice(index, 1);
  16595. };
  16596. return LensFlareSystem;
  16597. })();
  16598. BABYLON.LensFlareSystem = LensFlareSystem;
  16599. })(BABYLON || (BABYLON = {}));
  16600. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  16601. (function (BABYLON) {
  16602. var IntersectionInfo = (function () {
  16603. function IntersectionInfo(bu, bv, distance) {
  16604. this.bu = bu;
  16605. this.bv = bv;
  16606. this.distance = distance;
  16607. this.faceId = 0;
  16608. }
  16609. return IntersectionInfo;
  16610. })();
  16611. BABYLON.IntersectionInfo = IntersectionInfo;
  16612. var PickingInfo = (function () {
  16613. function PickingInfo() {
  16614. this.hit = false;
  16615. this.distance = 0;
  16616. this.pickedPoint = null;
  16617. this.pickedMesh = null;
  16618. this.bu = 0;
  16619. this.bv = 0;
  16620. this.faceId = -1;
  16621. }
  16622. // Methods
  16623. PickingInfo.prototype.getNormal = function () {
  16624. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16625. return null;
  16626. }
  16627. var indices = this.pickedMesh.getIndices();
  16628. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16629. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  16630. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  16631. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  16632. normal0 = normal0.scale(this.bu);
  16633. normal1 = normal1.scale(this.bv);
  16634. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  16635. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  16636. };
  16637. PickingInfo.prototype.getTextureCoordinates = function () {
  16638. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16639. return null;
  16640. }
  16641. var indices = this.pickedMesh.getIndices();
  16642. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16643. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  16644. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  16645. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  16646. uv0 = uv0.scale(this.bu);
  16647. uv1 = uv1.scale(this.bv);
  16648. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  16649. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  16650. };
  16651. return PickingInfo;
  16652. })();
  16653. BABYLON.PickingInfo = PickingInfo;
  16654. })(BABYLON || (BABYLON = {}));
  16655. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  16656. (function (BABYLON) {
  16657. var FilesInput = (function () {
  16658. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  16659. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  16660. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  16661. this.engine = p_engine;
  16662. this.canvas = p_canvas;
  16663. this.currentScene = p_scene;
  16664. this.sceneLoadedCallback = p_sceneLoadedCallback;
  16665. this.progressCallback = p_progressCallback;
  16666. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  16667. this.textureLoadingCallback = p_textureLoadingCallback;
  16668. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  16669. }
  16670. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  16671. var _this = this;
  16672. if (p_elementToMonitor) {
  16673. this.elementToMonitor = p_elementToMonitor;
  16674. this.elementToMonitor.addEventListener("dragenter", function (e) {
  16675. _this.drag(e);
  16676. }, false);
  16677. this.elementToMonitor.addEventListener("dragover", function (e) {
  16678. _this.drag(e);
  16679. }, false);
  16680. this.elementToMonitor.addEventListener("drop", function (e) {
  16681. _this.drop(e);
  16682. }, false);
  16683. }
  16684. };
  16685. FilesInput.prototype.renderFunction = function () {
  16686. if (this.additionnalRenderLoopLogicCallback) {
  16687. this.additionnalRenderLoopLogicCallback();
  16688. }
  16689. if (this.currentScene) {
  16690. if (this.textureLoadingCallback) {
  16691. var remaining = this.currentScene.getWaitingItemsCount();
  16692. if (remaining > 0) {
  16693. this.textureLoadingCallback(remaining);
  16694. }
  16695. }
  16696. this.currentScene.render();
  16697. }
  16698. };
  16699. FilesInput.prototype.drag = function (e) {
  16700. e.stopPropagation();
  16701. e.preventDefault();
  16702. };
  16703. FilesInput.prototype.drop = function (eventDrop) {
  16704. eventDrop.stopPropagation();
  16705. eventDrop.preventDefault();
  16706. this.loadFiles(eventDrop);
  16707. };
  16708. FilesInput.prototype.loadFiles = function (event) {
  16709. var _this = this;
  16710. var that = this;
  16711. if (this.startingProcessingFilesCallback)
  16712. this.startingProcessingFilesCallback();
  16713. var sceneFileToLoad;
  16714. var filesToLoad;
  16715. // Handling data transfer via drag'n'drop
  16716. if (event && event.dataTransfer && event.dataTransfer.files) {
  16717. filesToLoad = event.dataTransfer.files;
  16718. }
  16719. // Handling files from input files
  16720. if (event && event.target && event.target.files) {
  16721. filesToLoad = event.target.files;
  16722. }
  16723. if (filesToLoad && filesToLoad.length > 0) {
  16724. for (var i = 0; i < filesToLoad.length; i++) {
  16725. switch (filesToLoad[i].type) {
  16726. case "image/jpeg":
  16727. case "image/png":
  16728. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  16729. break;
  16730. case "image/targa":
  16731. case "image/vnd.ms-dds":
  16732. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  16733. break;
  16734. default:
  16735. if (filesToLoad[i].name.indexOf(".babylon") !== -1 && filesToLoad[i].name.indexOf(".manifest") === -1 && filesToLoad[i].name.indexOf(".incremental") === -1 && filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  16736. sceneFileToLoad = filesToLoad[i];
  16737. }
  16738. break;
  16739. }
  16740. }
  16741. // If a ".babylon" file has been provided
  16742. if (sceneFileToLoad) {
  16743. if (this.currentScene) {
  16744. this.engine.stopRenderLoop();
  16745. this.currentScene.dispose();
  16746. }
  16747. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  16748. that.currentScene = newScene;
  16749. // Wait for textures and shaders to be ready
  16750. that.currentScene.executeWhenReady(function () {
  16751. // Attach camera to canvas inputs
  16752. if (that.currentScene.activeCamera) {
  16753. that.currentScene.activeCamera.attachControl(that.canvas);
  16754. }
  16755. if (that.sceneLoadedCallback) {
  16756. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  16757. }
  16758. that.engine.runRenderLoop(function () {
  16759. that.renderFunction();
  16760. });
  16761. });
  16762. }, function (progress) {
  16763. if (_this.progressCallback) {
  16764. _this.progressCallback(progress);
  16765. }
  16766. });
  16767. }
  16768. else {
  16769. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  16770. }
  16771. }
  16772. };
  16773. FilesInput.FilesTextures = new Array();
  16774. FilesInput.FilesToLoad = new Array();
  16775. return FilesInput;
  16776. })();
  16777. BABYLON.FilesInput = FilesInput;
  16778. })(BABYLON || (BABYLON = {}));
  16779. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  16780. (function (BABYLON) {
  16781. var OimoJSPlugin = (function () {
  16782. function OimoJSPlugin() {
  16783. this._registeredMeshes = [];
  16784. /**
  16785. * Update the body position according to the mesh position
  16786. * @param mesh
  16787. */
  16788. this.updateBodyPosition = function (mesh) {
  16789. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16790. var registeredMesh = this._registeredMeshes[index];
  16791. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16792. var body = registeredMesh.body.body;
  16793. mesh.computeWorldMatrix(true);
  16794. var center = mesh.getBoundingInfo().boundingBox.center;
  16795. body.setPosition(center.x, center.y, center.z);
  16796. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  16797. return;
  16798. }
  16799. // Case where the parent has been updated
  16800. if (registeredMesh.mesh.parent === mesh) {
  16801. mesh.computeWorldMatrix(true);
  16802. registeredMesh.mesh.computeWorldMatrix(true);
  16803. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  16804. var absoluteRotation = mesh.rotation;
  16805. body = registeredMesh.body.body;
  16806. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  16807. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  16808. return;
  16809. }
  16810. }
  16811. };
  16812. }
  16813. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  16814. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  16815. };
  16816. OimoJSPlugin.prototype.initialize = function (iterations) {
  16817. this._world = new OIMO.World();
  16818. this._world.clear();
  16819. };
  16820. OimoJSPlugin.prototype.setGravity = function (gravity) {
  16821. this._world.gravity = gravity;
  16822. };
  16823. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  16824. var body = null;
  16825. this.unregisterMesh(mesh);
  16826. mesh.computeWorldMatrix(true);
  16827. switch (impostor) {
  16828. case BABYLON.PhysicsEngine.SphereImpostor:
  16829. var initialRotation = null;
  16830. if (mesh.rotationQuaternion) {
  16831. initialRotation = mesh.rotationQuaternion.clone();
  16832. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16833. mesh.computeWorldMatrix(true);
  16834. }
  16835. var bbox = mesh.getBoundingInfo().boundingBox;
  16836. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16837. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16838. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16839. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16840. // The delta between the mesh position and the mesh bounding box center
  16841. var deltaPosition = mesh.position.subtract(bbox.center);
  16842. // Transform delta position with the rotation
  16843. if (initialRotation) {
  16844. var m = new BABYLON.Matrix();
  16845. initialRotation.toRotationMatrix(m);
  16846. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16847. }
  16848. body = new OIMO.Body({
  16849. type: 'sphere',
  16850. size: [size],
  16851. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16852. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16853. move: options.mass != 0,
  16854. config: [options.mass, options.friction, options.restitution],
  16855. world: this._world
  16856. });
  16857. // Restore rotation
  16858. if (initialRotation) {
  16859. body.setQuaternion(initialRotation);
  16860. }
  16861. this._registeredMeshes.push({
  16862. mesh: mesh,
  16863. body: body,
  16864. delta: deltaPosition
  16865. });
  16866. break;
  16867. case BABYLON.PhysicsEngine.PlaneImpostor:
  16868. case BABYLON.PhysicsEngine.BoxImpostor:
  16869. initialRotation = null;
  16870. if (mesh.rotationQuaternion) {
  16871. initialRotation = mesh.rotationQuaternion.clone();
  16872. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16873. mesh.computeWorldMatrix(true);
  16874. }
  16875. bbox = mesh.getBoundingInfo().boundingBox;
  16876. var min = bbox.minimumWorld;
  16877. var max = bbox.maximumWorld;
  16878. var box = max.subtract(min);
  16879. var sizeX = this._checkWithEpsilon(box.x);
  16880. var sizeY = this._checkWithEpsilon(box.y);
  16881. var sizeZ = this._checkWithEpsilon(box.z);
  16882. // The delta between the mesh position and the mesh boudning box center
  16883. deltaPosition = mesh.position.subtract(bbox.center);
  16884. // Transform delta position with the rotation
  16885. if (initialRotation) {
  16886. m = new BABYLON.Matrix();
  16887. initialRotation.toRotationMatrix(m);
  16888. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16889. }
  16890. body = new OIMO.Body({
  16891. type: 'box',
  16892. size: [sizeX, sizeY, sizeZ],
  16893. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16894. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16895. move: options.mass != 0,
  16896. config: [options.mass, options.friction, options.restitution],
  16897. world: this._world
  16898. });
  16899. if (initialRotation) {
  16900. body.setQuaternion(initialRotation);
  16901. }
  16902. this._registeredMeshes.push({
  16903. mesh: mesh,
  16904. body: body,
  16905. delta: deltaPosition
  16906. });
  16907. break;
  16908. }
  16909. return body;
  16910. };
  16911. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  16912. var types = [], sizes = [], positions = [], rotations = [];
  16913. var initialMesh = parts[0].mesh;
  16914. for (var index = 0; index < parts.length; index++) {
  16915. var part = parts[index];
  16916. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  16917. types.push(bodyParameters.type);
  16918. sizes.push.apply(sizes, bodyParameters.size);
  16919. positions.push.apply(positions, bodyParameters.pos);
  16920. rotations.push.apply(rotations, bodyParameters.rot);
  16921. }
  16922. var body = new OIMO.Body({
  16923. type: types,
  16924. size: sizes,
  16925. pos: positions,
  16926. rot: rotations,
  16927. move: options.mass != 0,
  16928. config: [options.mass, options.friction, options.restitution],
  16929. world: this._world
  16930. });
  16931. this._registeredMeshes.push({
  16932. mesh: initialMesh,
  16933. body: body
  16934. });
  16935. return body;
  16936. };
  16937. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  16938. var bodyParameters = null;
  16939. var mesh = part.mesh;
  16940. // We need the bounding box/sphere info to compute the physics body
  16941. mesh.computeWorldMatrix();
  16942. switch (part.impostor) {
  16943. case BABYLON.PhysicsEngine.SphereImpostor:
  16944. var bbox = mesh.getBoundingInfo().boundingBox;
  16945. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16946. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16947. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16948. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16949. bodyParameters = {
  16950. type: 'sphere',
  16951. /* bug with oimo : sphere needs 3 sizes in this case */
  16952. size: [size, -1, -1],
  16953. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  16954. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16955. };
  16956. break;
  16957. case BABYLON.PhysicsEngine.PlaneImpostor:
  16958. case BABYLON.PhysicsEngine.BoxImpostor:
  16959. bbox = mesh.getBoundingInfo().boundingBox;
  16960. var min = bbox.minimumWorld;
  16961. var max = bbox.maximumWorld;
  16962. var box = max.subtract(min);
  16963. var sizeX = this._checkWithEpsilon(box.x);
  16964. var sizeY = this._checkWithEpsilon(box.y);
  16965. var sizeZ = this._checkWithEpsilon(box.z);
  16966. var relativePosition = mesh.position;
  16967. bodyParameters = {
  16968. type: 'box',
  16969. size: [sizeX, sizeY, sizeZ],
  16970. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  16971. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16972. };
  16973. break;
  16974. }
  16975. return bodyParameters;
  16976. };
  16977. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  16978. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16979. var registeredMesh = this._registeredMeshes[index];
  16980. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16981. if (registeredMesh.body) {
  16982. this._world.removeRigidBody(registeredMesh.body.body);
  16983. this._unbindBody(registeredMesh.body);
  16984. }
  16985. this._registeredMeshes.splice(index, 1);
  16986. return;
  16987. }
  16988. }
  16989. };
  16990. OimoJSPlugin.prototype._unbindBody = function (body) {
  16991. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16992. var registeredMesh = this._registeredMeshes[index];
  16993. if (registeredMesh.body === body) {
  16994. registeredMesh.body = null;
  16995. }
  16996. }
  16997. };
  16998. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  16999. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17000. var registeredMesh = this._registeredMeshes[index];
  17001. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17002. // Get object mass to have a behaviour similar to cannon.js
  17003. var mass = registeredMesh.body.body.massInfo.mass;
  17004. // The force is scaled with the mass of object
  17005. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17006. return;
  17007. }
  17008. }
  17009. };
  17010. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17011. var body1 = null, body2 = null;
  17012. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17013. var registeredMesh = this._registeredMeshes[index];
  17014. if (registeredMesh.mesh === mesh1) {
  17015. body1 = registeredMesh.body.body;
  17016. }
  17017. else if (registeredMesh.mesh === mesh2) {
  17018. body2 = registeredMesh.body.body;
  17019. }
  17020. }
  17021. if (!body1 || !body2) {
  17022. return false;
  17023. }
  17024. if (!options) {
  17025. options = {};
  17026. }
  17027. new OIMO.Link({
  17028. type: options.type,
  17029. body1: body1,
  17030. body2: body2,
  17031. min: options.min,
  17032. max: options.max,
  17033. axe1: options.axe1,
  17034. axe2: options.axe2,
  17035. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17036. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17037. collision: options.collision,
  17038. spring: options.spring,
  17039. world: this._world
  17040. });
  17041. return true;
  17042. };
  17043. OimoJSPlugin.prototype.dispose = function () {
  17044. this._world.clear();
  17045. while (this._registeredMeshes.length) {
  17046. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17047. }
  17048. };
  17049. OimoJSPlugin.prototype.isSupported = function () {
  17050. return OIMO !== undefined;
  17051. };
  17052. OimoJSPlugin.prototype._getLastShape = function (body) {
  17053. var lastShape = body.shapes;
  17054. while (lastShape.next) {
  17055. lastShape = lastShape.next;
  17056. }
  17057. return lastShape;
  17058. };
  17059. OimoJSPlugin.prototype.runOneStep = function (time) {
  17060. this._world.step();
  17061. // Update the position of all registered meshes
  17062. var i = this._registeredMeshes.length;
  17063. var m;
  17064. while (i--) {
  17065. var body = this._registeredMeshes[i].body.body;
  17066. var mesh = this._registeredMeshes[i].mesh;
  17067. var delta = this._registeredMeshes[i].delta;
  17068. if (!body.sleeping) {
  17069. if (body.shapes.next) {
  17070. var parentShape = this._getLastShape(body);
  17071. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17072. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17073. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17074. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17075. if (!mesh.rotationQuaternion) {
  17076. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17077. }
  17078. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17079. mesh.computeWorldMatrix();
  17080. }
  17081. else {
  17082. m = body.getMatrix();
  17083. mtx = BABYLON.Matrix.FromArray(m);
  17084. // Body position
  17085. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17086. if (!delta) {
  17087. mesh.position.x = bodyX;
  17088. mesh.position.y = bodyY;
  17089. mesh.position.z = bodyZ;
  17090. }
  17091. else {
  17092. mesh.position.x = bodyX + delta.x;
  17093. mesh.position.y = bodyY + delta.y;
  17094. mesh.position.z = bodyZ + delta.z;
  17095. }
  17096. if (!mesh.rotationQuaternion) {
  17097. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17098. }
  17099. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17100. mesh.computeWorldMatrix();
  17101. }
  17102. }
  17103. }
  17104. };
  17105. return OimoJSPlugin;
  17106. })();
  17107. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17108. })(BABYLON || (BABYLON = {}));
  17109. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17110. (function (BABYLON) {
  17111. var PhysicsEngine = (function () {
  17112. function PhysicsEngine(plugin) {
  17113. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17114. }
  17115. PhysicsEngine.prototype._initialize = function (gravity) {
  17116. this._currentPlugin.initialize();
  17117. this._setGravity(gravity);
  17118. };
  17119. PhysicsEngine.prototype._runOneStep = function (delta) {
  17120. if (delta > 0.1) {
  17121. delta = 0.1;
  17122. }
  17123. else if (delta <= 0) {
  17124. delta = 1.0 / 60.0;
  17125. }
  17126. this._currentPlugin.runOneStep(delta);
  17127. };
  17128. PhysicsEngine.prototype._setGravity = function (gravity) {
  17129. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17130. this._currentPlugin.setGravity(this.gravity);
  17131. };
  17132. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17133. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17134. };
  17135. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17136. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17137. };
  17138. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17139. this._currentPlugin.unregisterMesh(mesh);
  17140. };
  17141. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  17142. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  17143. };
  17144. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17145. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  17146. };
  17147. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  17148. this._currentPlugin.updateBodyPosition(mesh);
  17149. };
  17150. PhysicsEngine.prototype.dispose = function () {
  17151. this._currentPlugin.dispose();
  17152. };
  17153. PhysicsEngine.prototype.isSupported = function () {
  17154. return this._currentPlugin.isSupported();
  17155. };
  17156. // Statics
  17157. PhysicsEngine.NoImpostor = 0;
  17158. PhysicsEngine.SphereImpostor = 1;
  17159. PhysicsEngine.BoxImpostor = 2;
  17160. PhysicsEngine.PlaneImpostor = 3;
  17161. PhysicsEngine.MeshImpostor = 4;
  17162. PhysicsEngine.CapsuleImpostor = 5;
  17163. PhysicsEngine.ConeImpostor = 6;
  17164. PhysicsEngine.CylinderImpostor = 7;
  17165. PhysicsEngine.ConvexHullImpostor = 8;
  17166. PhysicsEngine.Epsilon = 0.001;
  17167. return PhysicsEngine;
  17168. })();
  17169. BABYLON.PhysicsEngine = PhysicsEngine;
  17170. })(BABYLON || (BABYLON = {}));
  17171. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  17172. (function (BABYLON) {
  17173. var serializeLight = function (light) {
  17174. var serializationObject = {};
  17175. serializationObject.name = light.name;
  17176. serializationObject.id = light.id;
  17177. serializationObject.tags = BABYLON.Tags.GetTags(light);
  17178. if (light instanceof BABYLON.PointLight) {
  17179. serializationObject.type = 0;
  17180. serializationObject.position = light.position.asArray();
  17181. }
  17182. else if (light instanceof BABYLON.DirectionalLight) {
  17183. serializationObject.type = 1;
  17184. var directionalLight = light;
  17185. serializationObject.position = directionalLight.position.asArray();
  17186. serializationObject.direction = directionalLight.direction.asArray();
  17187. }
  17188. else if (light instanceof BABYLON.SpotLight) {
  17189. serializationObject.type = 2;
  17190. var spotLight = light;
  17191. serializationObject.position = spotLight.position.asArray();
  17192. serializationObject.direction = spotLight.position.asArray();
  17193. serializationObject.angle = spotLight.angle;
  17194. serializationObject.exponent = spotLight.exponent;
  17195. }
  17196. else if (light instanceof BABYLON.HemisphericLight) {
  17197. serializationObject.type = 3;
  17198. var hemisphericLight = light;
  17199. serializationObject.direction = hemisphericLight.direction.asArray();
  17200. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  17201. }
  17202. if (light.intensity) {
  17203. serializationObject.intensity = light.intensity;
  17204. }
  17205. serializationObject.range = light.range;
  17206. serializationObject.diffuse = light.diffuse.asArray();
  17207. serializationObject.specular = light.specular.asArray();
  17208. return serializationObject;
  17209. };
  17210. var serializeFresnelParameter = function (fresnelParameter) {
  17211. var serializationObject = {};
  17212. serializationObject.isEnabled = fresnelParameter.isEnabled;
  17213. serializationObject.leftColor = fresnelParameter.leftColor;
  17214. serializationObject.rightColor = fresnelParameter.rightColor;
  17215. serializationObject.bias = fresnelParameter.bias;
  17216. serializationObject.power = fresnelParameter.power;
  17217. return serializationObject;
  17218. };
  17219. var serializeCamera = function (camera) {
  17220. var serializationObject = {};
  17221. serializationObject.name = camera.name;
  17222. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  17223. serializationObject.id = camera.id;
  17224. serializationObject.position = camera.position.asArray();
  17225. // Parent
  17226. if (camera.parent) {
  17227. serializationObject.parentId = camera.parent.id;
  17228. }
  17229. // Target
  17230. serializationObject.rotation = camera.rotation.asArray();
  17231. // Locked target
  17232. if (camera.lockedTarget && camera.lockedTarget.id) {
  17233. serializationObject.lockedTargetId = camera.lockedTarget.id;
  17234. }
  17235. serializationObject.fov = camera.fov;
  17236. serializationObject.minZ = camera.minZ;
  17237. serializationObject.maxZ = camera.maxZ;
  17238. serializationObject.speed = camera.speed;
  17239. serializationObject.inertia = camera.inertia;
  17240. serializationObject.checkCollisions = camera.checkCollisions;
  17241. serializationObject.applyGravity = camera.applyGravity;
  17242. if (camera.ellipsoid) {
  17243. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  17244. }
  17245. // Animations
  17246. appendAnimations(camera, serializationObject);
  17247. // Layer mask
  17248. serializationObject.layerMask = camera.layerMask;
  17249. return serializationObject;
  17250. };
  17251. var appendAnimations = function (source, destination) {
  17252. if (source.animations) {
  17253. destination.animations = [];
  17254. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  17255. var animation = source.animations[animationIndex];
  17256. destination.animations.push(serializeAnimation(animation));
  17257. }
  17258. }
  17259. };
  17260. var serializeAnimation = function (animation) {
  17261. var serializationObject = {};
  17262. serializationObject.name = animation.name;
  17263. serializationObject.property = animation.targetProperty;
  17264. serializationObject.framePerSecond = animation.framePerSecond;
  17265. serializationObject.dataType = animation.dataType;
  17266. serializationObject.loopBehavior = animation.loopMode;
  17267. var dataType = animation.dataType;
  17268. serializationObject.keys = [];
  17269. var keys = animation.getKeys();
  17270. for (var index = 0; index < keys.length; index++) {
  17271. var animationKey = keys[index];
  17272. var key = {};
  17273. key.frame = animationKey.frame;
  17274. switch (dataType) {
  17275. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17276. key.values = [animationKey.value];
  17277. break;
  17278. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17279. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17280. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17281. key.values = animationKey.value.asArray();
  17282. break;
  17283. }
  17284. serializationObject.keys.push(key);
  17285. }
  17286. return serializationObject;
  17287. };
  17288. var serializeMultiMaterial = function (material) {
  17289. var serializationObject = {};
  17290. serializationObject.name = material.name;
  17291. serializationObject.id = material.id;
  17292. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17293. serializationObject.materials = [];
  17294. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  17295. var subMat = material.subMaterials[matIndex];
  17296. if (subMat) {
  17297. serializationObject.materials.push(subMat.id);
  17298. }
  17299. else {
  17300. serializationObject.materials.push(null);
  17301. }
  17302. }
  17303. return serializationObject;
  17304. };
  17305. var serializeMaterial = function (material) {
  17306. var serializationObject = {};
  17307. serializationObject.name = material.name;
  17308. serializationObject.ambient = material.ambientColor.asArray();
  17309. serializationObject.diffuse = material.diffuseColor.asArray();
  17310. serializationObject.specular = material.specularColor.asArray();
  17311. serializationObject.specularPower = material.specularPower;
  17312. serializationObject.emissive = material.emissiveColor.asArray();
  17313. serializationObject.alpha = material.alpha;
  17314. serializationObject.id = material.id;
  17315. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17316. serializationObject.backFaceCulling = material.backFaceCulling;
  17317. if (material.diffuseTexture) {
  17318. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  17319. }
  17320. if (material.diffuseFresnelParameters) {
  17321. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  17322. }
  17323. if (material.ambientTexture) {
  17324. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  17325. }
  17326. if (material.opacityTexture) {
  17327. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  17328. }
  17329. if (material.opacityFresnelParameters) {
  17330. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  17331. }
  17332. if (material.reflectionTexture) {
  17333. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  17334. }
  17335. if (material.reflectionFresnelParameters) {
  17336. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  17337. }
  17338. if (material.emissiveTexture) {
  17339. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  17340. }
  17341. if (material.emissiveFresnelParameters) {
  17342. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  17343. }
  17344. if (material.specularTexture) {
  17345. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  17346. }
  17347. if (material.bumpTexture) {
  17348. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  17349. }
  17350. return serializationObject;
  17351. };
  17352. var serializeTexture = function (texture) {
  17353. var serializationObject = {};
  17354. if (!texture.name) {
  17355. return null;
  17356. }
  17357. if (texture instanceof BABYLON.CubeTexture) {
  17358. serializationObject.name = texture.name;
  17359. serializationObject.hasAlpha = texture.hasAlpha;
  17360. serializationObject.level = texture.level;
  17361. serializationObject.coordinatesMode = texture.coordinatesMode;
  17362. return serializationObject;
  17363. }
  17364. if (texture instanceof BABYLON.MirrorTexture) {
  17365. var mirrorTexture = texture;
  17366. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  17367. serializationObject.renderList = [];
  17368. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  17369. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  17370. }
  17371. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  17372. }
  17373. else if (texture instanceof BABYLON.RenderTargetTexture) {
  17374. var renderTargetTexture = texture;
  17375. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  17376. serializationObject.renderList = [];
  17377. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  17378. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  17379. }
  17380. }
  17381. var regularTexture = texture;
  17382. serializationObject.name = texture.name;
  17383. serializationObject.hasAlpha = texture.hasAlpha;
  17384. serializationObject.level = texture.level;
  17385. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  17386. serializationObject.coordinatesMode = texture.coordinatesMode;
  17387. serializationObject.uOffset = regularTexture.uOffset;
  17388. serializationObject.vOffset = regularTexture.vOffset;
  17389. serializationObject.uScale = regularTexture.uScale;
  17390. serializationObject.vScale = regularTexture.vScale;
  17391. serializationObject.uAng = regularTexture.uAng;
  17392. serializationObject.vAng = regularTexture.vAng;
  17393. serializationObject.wAng = regularTexture.wAng;
  17394. serializationObject.wrapU = texture.wrapU;
  17395. serializationObject.wrapV = texture.wrapV;
  17396. // Animations
  17397. appendAnimations(texture, serializationObject);
  17398. return serializationObject;
  17399. };
  17400. var serializeSkeleton = function (skeleton) {
  17401. var serializationObject = {};
  17402. serializationObject.name = skeleton.name;
  17403. serializationObject.id = skeleton.id;
  17404. serializationObject.bones = [];
  17405. for (var index = 0; index < skeleton.bones.length; index++) {
  17406. var bone = skeleton.bones[index];
  17407. var serializedBone = {
  17408. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  17409. name: bone.name,
  17410. matrix: bone.getLocalMatrix().toArray()
  17411. };
  17412. serializationObject.bones.push(serializedBone);
  17413. if (bone.animations && bone.animations.length > 0) {
  17414. serializedBone.animation = serializeAnimation(bone.animations[0]);
  17415. }
  17416. }
  17417. return serializationObject;
  17418. };
  17419. var serializeParticleSystem = function (particleSystem) {
  17420. var serializationObject = {};
  17421. serializationObject.emitterId = particleSystem.emitter.id;
  17422. serializationObject.capacity = particleSystem.getCapacity();
  17423. if (particleSystem.particleTexture) {
  17424. serializationObject.textureName = particleSystem.particleTexture.name;
  17425. }
  17426. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  17427. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  17428. serializationObject.minSize = particleSystem.minSize;
  17429. serializationObject.maxSize = particleSystem.maxSize;
  17430. serializationObject.minLifeTime = particleSystem.minLifeTime;
  17431. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  17432. serializationObject.emitRate = particleSystem.emitRate;
  17433. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  17434. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  17435. serializationObject.gravity = particleSystem.gravity.asArray();
  17436. serializationObject.direction1 = particleSystem.direction1.asArray();
  17437. serializationObject.direction2 = particleSystem.direction2.asArray();
  17438. serializationObject.color1 = particleSystem.color1.asArray();
  17439. serializationObject.color2 = particleSystem.color2.asArray();
  17440. serializationObject.colorDead = particleSystem.colorDead.asArray();
  17441. serializationObject.updateSpeed = particleSystem.updateSpeed;
  17442. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  17443. serializationObject.textureMask = particleSystem.textureMask.asArray();
  17444. serializationObject.blendMode = particleSystem.blendMode;
  17445. return serializationObject;
  17446. };
  17447. var serializeLensFlareSystem = function (lensFlareSystem) {
  17448. var serializationObject = {};
  17449. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  17450. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  17451. serializationObject.flares = [];
  17452. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  17453. var flare = lensFlareSystem.lensFlares[index];
  17454. serializationObject.flares.push({
  17455. size: flare.size,
  17456. position: flare.position,
  17457. color: flare.color.asArray(),
  17458. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  17459. });
  17460. }
  17461. return serializationObject;
  17462. };
  17463. var serializeShadowGenerator = function (light) {
  17464. var serializationObject = {};
  17465. var shadowGenerator = light.getShadowGenerator();
  17466. serializationObject.lightId = light.id;
  17467. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  17468. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  17469. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  17470. serializationObject.renderList = [];
  17471. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  17472. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  17473. serializationObject.renderList.push(mesh.id);
  17474. }
  17475. return serializationObject;
  17476. };
  17477. var serializedGeometries = [];
  17478. var serializeGeometry = function (geometry, serializationGeometries) {
  17479. if (serializedGeometries[geometry.id]) {
  17480. return;
  17481. }
  17482. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  17483. serializationGeometries.boxes.push(serializeBox(geometry));
  17484. }
  17485. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  17486. serializationGeometries.spheres.push(serializeSphere(geometry));
  17487. }
  17488. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  17489. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  17490. }
  17491. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  17492. serializationGeometries.toruses.push(serializeTorus(geometry));
  17493. }
  17494. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  17495. serializationGeometries.grounds.push(serializeGround(geometry));
  17496. }
  17497. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  17498. serializationGeometries.planes.push(serializePlane(geometry));
  17499. }
  17500. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  17501. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  17502. }
  17503. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  17504. throw new Error("Unknow primitive type");
  17505. }
  17506. else {
  17507. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  17508. }
  17509. serializedGeometries[geometry.id] = true;
  17510. };
  17511. var serializeGeometryBase = function (geometry) {
  17512. var serializationObject = {};
  17513. serializationObject.id = geometry.id;
  17514. if (BABYLON.Tags.HasTags(geometry)) {
  17515. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  17516. }
  17517. return serializationObject;
  17518. };
  17519. var serializeVertexData = function (vertexData) {
  17520. var serializationObject = serializeGeometryBase(vertexData);
  17521. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17522. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17523. }
  17524. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17525. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17526. }
  17527. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17528. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17529. }
  17530. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17531. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17532. }
  17533. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17534. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17535. }
  17536. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17537. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17538. serializationObject.matricesIndices._isExpanded = true;
  17539. }
  17540. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17541. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17542. }
  17543. serializationObject.indices = vertexData.getIndices();
  17544. return serializationObject;
  17545. };
  17546. var serializePrimitive = function (primitive) {
  17547. var serializationObject = serializeGeometryBase(primitive);
  17548. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  17549. return serializationObject;
  17550. };
  17551. var serializeBox = function (box) {
  17552. var serializationObject = serializePrimitive(box);
  17553. serializationObject.size = box.size;
  17554. return serializationObject;
  17555. };
  17556. var serializeSphere = function (sphere) {
  17557. var serializationObject = serializePrimitive(sphere);
  17558. serializationObject.segments = sphere.segments;
  17559. serializationObject.diameter = sphere.diameter;
  17560. return serializationObject;
  17561. };
  17562. var serializeCylinder = function (cylinder) {
  17563. var serializationObject = serializePrimitive(cylinder);
  17564. serializationObject.height = cylinder.height;
  17565. serializationObject.diameterTop = cylinder.diameterTop;
  17566. serializationObject.diameterBottom = cylinder.diameterBottom;
  17567. serializationObject.tessellation = cylinder.tessellation;
  17568. return serializationObject;
  17569. };
  17570. var serializeTorus = function (torus) {
  17571. var serializationObject = serializePrimitive(torus);
  17572. serializationObject.diameter = torus.diameter;
  17573. serializationObject.thickness = torus.thickness;
  17574. serializationObject.tessellation = torus.tessellation;
  17575. return serializationObject;
  17576. };
  17577. var serializeGround = function (ground) {
  17578. var serializationObject = serializePrimitive(ground);
  17579. serializationObject.width = ground.width;
  17580. serializationObject.height = ground.height;
  17581. serializationObject.subdivisions = ground.subdivisions;
  17582. return serializationObject;
  17583. };
  17584. var serializePlane = function (plane) {
  17585. var serializationObject = serializePrimitive(plane);
  17586. serializationObject.size = plane.size;
  17587. return serializationObject;
  17588. };
  17589. var serializeTorusKnot = function (torusKnot) {
  17590. var serializationObject = serializePrimitive(torusKnot);
  17591. serializationObject.radius = torusKnot.radius;
  17592. serializationObject.tube = torusKnot.tube;
  17593. serializationObject.radialSegments = torusKnot.radialSegments;
  17594. serializationObject.tubularSegments = torusKnot.tubularSegments;
  17595. serializationObject.p = torusKnot.p;
  17596. serializationObject.q = torusKnot.q;
  17597. return serializationObject;
  17598. };
  17599. var serializeMesh = function (mesh, serializationScene) {
  17600. var serializationObject = {};
  17601. serializationObject.name = mesh.name;
  17602. serializationObject.id = mesh.id;
  17603. if (BABYLON.Tags.HasTags(mesh)) {
  17604. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  17605. }
  17606. serializationObject.position = mesh.position.asArray();
  17607. if (mesh.rotationQuaternion) {
  17608. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  17609. }
  17610. else if (mesh.rotation) {
  17611. serializationObject.rotation = mesh.rotation.asArray();
  17612. }
  17613. serializationObject.scaling = mesh.scaling.asArray();
  17614. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  17615. serializationObject.isEnabled = mesh.isEnabled();
  17616. serializationObject.isVisible = mesh.isVisible;
  17617. serializationObject.infiniteDistance = mesh.infiniteDistance;
  17618. serializationObject.pickable = mesh.isPickable;
  17619. serializationObject.receiveShadows = mesh.receiveShadows;
  17620. serializationObject.billboardMode = mesh.billboardMode;
  17621. serializationObject.visibility = mesh.visibility;
  17622. serializationObject.checkCollisions = mesh.checkCollisions;
  17623. // Parent
  17624. if (mesh.parent) {
  17625. serializationObject.parentId = mesh.parent.id;
  17626. }
  17627. // Geometry
  17628. var geometry = mesh._geometry;
  17629. if (geometry) {
  17630. var geometryId = geometry.id;
  17631. serializationObject.geometryId = geometryId;
  17632. if (!mesh.getScene().getGeometryByID(geometryId)) {
  17633. // geometry was in the memory but not added to the scene, nevertheless it's better to serialize too be able to reload the mesh with its geometry
  17634. serializeGeometry(geometry, serializationScene.geometries);
  17635. }
  17636. // SubMeshes
  17637. serializationObject.subMeshes = [];
  17638. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17639. var subMesh = mesh.subMeshes[subIndex];
  17640. serializationObject.subMeshes.push({
  17641. materialIndex: subMesh.materialIndex,
  17642. verticesStart: subMesh.verticesStart,
  17643. verticesCount: subMesh.verticesCount,
  17644. indexStart: subMesh.indexStart,
  17645. indexCount: subMesh.indexCount
  17646. });
  17647. }
  17648. }
  17649. // Material
  17650. if (mesh.material) {
  17651. serializationObject.materialId = mesh.material.id;
  17652. }
  17653. else {
  17654. mesh.material = null;
  17655. }
  17656. // Skeleton
  17657. if (mesh.skeleton) {
  17658. serializationObject.skeletonId = mesh.skeleton.id;
  17659. }
  17660. // Physics
  17661. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  17662. serializationObject.physicsMass = mesh.getPhysicsMass();
  17663. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  17664. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  17665. switch (mesh.getPhysicsImpostor()) {
  17666. case BABYLON.PhysicsEngine.BoxImpostor:
  17667. serializationObject.physicsImpostor = 1;
  17668. break;
  17669. case BABYLON.PhysicsEngine.SphereImpostor:
  17670. serializationObject.physicsImpostor = 2;
  17671. break;
  17672. }
  17673. }
  17674. // Instances
  17675. serializationObject.instances = [];
  17676. for (var index = 0; index < mesh.instances.length; index++) {
  17677. var instance = mesh.instances[index];
  17678. var serializationInstance = {
  17679. name: instance.name,
  17680. position: instance.position,
  17681. rotation: instance.rotation,
  17682. rotationQuaternion: instance.rotationQuaternion,
  17683. scaling: instance.scaling
  17684. };
  17685. serializationObject.instances.push(serializationInstance);
  17686. // Animations
  17687. appendAnimations(instance, serializationInstance);
  17688. }
  17689. // Animations
  17690. appendAnimations(mesh, serializationObject);
  17691. // Layer mask
  17692. serializationObject.layerMask = mesh.layerMask;
  17693. return serializationObject;
  17694. };
  17695. var SceneSerializer = (function () {
  17696. function SceneSerializer() {
  17697. }
  17698. SceneSerializer.Serialize = function (scene) {
  17699. var serializationObject = {};
  17700. // Scene
  17701. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  17702. serializationObject.autoClear = scene.autoClear;
  17703. serializationObject.clearColor = scene.clearColor.asArray();
  17704. serializationObject.ambientColor = scene.ambientColor.asArray();
  17705. serializationObject.gravity = scene.gravity.asArray();
  17706. // Fog
  17707. if (scene.fogMode && scene.fogMode !== 0) {
  17708. serializationObject.fogMode = scene.fogMode;
  17709. serializationObject.fogColor = scene.fogColor.asArray();
  17710. serializationObject.fogStart = scene.fogStart;
  17711. serializationObject.fogEnd = scene.fogEnd;
  17712. serializationObject.fogDensity = scene.fogDensity;
  17713. }
  17714. // Lights
  17715. serializationObject.lights = [];
  17716. for (var index = 0; index < scene.lights.length; index++) {
  17717. var light = scene.lights[index];
  17718. serializationObject.lights.push(serializeLight(light));
  17719. }
  17720. // Cameras
  17721. serializationObject.cameras = [];
  17722. for (index = 0; index < scene.cameras.length; index++) {
  17723. var camera = scene.cameras[index];
  17724. if (camera instanceof BABYLON.FreeCamera) {
  17725. serializationObject.cameras.push(serializeCamera(camera));
  17726. }
  17727. }
  17728. if (scene.activeCamera) {
  17729. serializationObject.activeCameraID = scene.activeCamera.id;
  17730. }
  17731. // Materials
  17732. serializationObject.materials = [];
  17733. serializationObject.multiMaterials = [];
  17734. for (index = 0; index < scene.materials.length; index++) {
  17735. var material = scene.materials[index];
  17736. if (material instanceof BABYLON.StandardMaterial) {
  17737. serializationObject.materials.push(serializeMaterial(material));
  17738. }
  17739. else if (material instanceof BABYLON.MultiMaterial) {
  17740. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  17741. }
  17742. }
  17743. // Skeletons
  17744. serializationObject.skeletons = [];
  17745. for (index = 0; index < scene.skeletons.length; index++) {
  17746. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  17747. }
  17748. // Geometries
  17749. serializationObject.geometries = {};
  17750. serializationObject.geometries.boxes = [];
  17751. serializationObject.geometries.spheres = [];
  17752. serializationObject.geometries.cylinders = [];
  17753. serializationObject.geometries.toruses = [];
  17754. serializationObject.geometries.grounds = [];
  17755. serializationObject.geometries.planes = [];
  17756. serializationObject.geometries.torusKnots = [];
  17757. serializationObject.geometries.vertexData = [];
  17758. serializedGeometries = [];
  17759. var geometries = scene.getGeometries();
  17760. for (var index = 0; index < geometries.length; index++) {
  17761. var geometry = geometries[index];
  17762. if (geometry.isReady()) {
  17763. serializeGeometry(geometry, serializationObject.geometries);
  17764. }
  17765. }
  17766. // Meshes
  17767. serializationObject.meshes = [];
  17768. for (index = 0; index < scene.meshes.length; index++) {
  17769. var abstractMesh = scene.meshes[index];
  17770. if (abstractMesh instanceof BABYLON.Mesh) {
  17771. var mesh = abstractMesh;
  17772. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  17773. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  17774. }
  17775. }
  17776. }
  17777. // Particles Systems
  17778. serializationObject.particleSystems = [];
  17779. for (index = 0; index < scene.particleSystems.length; index++) {
  17780. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  17781. }
  17782. // Lens flares
  17783. serializationObject.lensFlareSystems = [];
  17784. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  17785. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  17786. }
  17787. // Shadows
  17788. serializationObject.shadowGenerators = [];
  17789. for (index = 0; index < scene.lights.length; index++) {
  17790. light = scene.lights[index];
  17791. if (light.getShadowGenerator()) {
  17792. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  17793. }
  17794. }
  17795. return serializationObject;
  17796. };
  17797. return SceneSerializer;
  17798. })();
  17799. BABYLON.SceneSerializer = SceneSerializer;
  17800. })(BABYLON || (BABYLON = {}));
  17801. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  17802. (function (BABYLON) {
  17803. var SceneLoader = (function () {
  17804. function SceneLoader() {
  17805. }
  17806. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  17807. get: function () {
  17808. return SceneLoader._ForceFullSceneLoadingForIncremental;
  17809. },
  17810. set: function (value) {
  17811. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  17812. },
  17813. enumerable: true,
  17814. configurable: true
  17815. });
  17816. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  17817. get: function () {
  17818. return SceneLoader._ShowLoadingScreen;
  17819. },
  17820. set: function (value) {
  17821. SceneLoader._ShowLoadingScreen = value;
  17822. },
  17823. enumerable: true,
  17824. configurable: true
  17825. });
  17826. SceneLoader._getPluginForFilename = function (sceneFilename) {
  17827. var dotPosition = sceneFilename.lastIndexOf(".");
  17828. var queryStringPosition = sceneFilename.indexOf("?");
  17829. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17830. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17831. var plugin = this._registeredPlugins[index];
  17832. if (plugin.extensions.indexOf(extension) !== -1) {
  17833. return plugin;
  17834. }
  17835. }
  17836. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17837. };
  17838. // Public functions
  17839. SceneLoader.RegisterPlugin = function (plugin) {
  17840. plugin.extensions = plugin.extensions.toLowerCase();
  17841. SceneLoader._registeredPlugins.push(plugin);
  17842. };
  17843. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17844. var manifestChecked = function (success) {
  17845. scene.database = database;
  17846. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17847. var importMeshFromData = function (data) {
  17848. var meshes = [];
  17849. var particleSystems = [];
  17850. var skeletons = [];
  17851. try {
  17852. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17853. if (onerror) {
  17854. onerror(scene, 'unable to load the scene');
  17855. }
  17856. return;
  17857. }
  17858. }
  17859. catch (e) {
  17860. if (onerror) {
  17861. onerror(scene, e);
  17862. }
  17863. return;
  17864. }
  17865. if (onsuccess) {
  17866. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17867. onsuccess(meshes, particleSystems, skeletons);
  17868. }
  17869. };
  17870. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17871. // Direct load
  17872. importMeshFromData(sceneFilename.substr(5));
  17873. return;
  17874. }
  17875. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17876. importMeshFromData(data);
  17877. }, progressCallBack, database);
  17878. };
  17879. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17880. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17881. };
  17882. /**
  17883. * Load a scene
  17884. * @param rootUrl a string that defines the root url for scene and resources
  17885. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17886. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17887. */
  17888. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17889. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17890. };
  17891. /**
  17892. * Append a scene
  17893. * @param rootUrl a string that defines the root url for scene and resources
  17894. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17895. * @param scene is the instance of BABYLON.Scene to append to
  17896. */
  17897. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17898. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17899. var database;
  17900. if (SceneLoader.ShowLoadingScreen) {
  17901. scene.getEngine().displayLoadingUI();
  17902. }
  17903. var loadSceneFromData = function (data) {
  17904. scene.database = database;
  17905. if (!plugin.load(scene, data, rootUrl)) {
  17906. if (onerror) {
  17907. onerror(scene);
  17908. }
  17909. scene.getEngine().hideLoadingUI();
  17910. return;
  17911. }
  17912. if (onsuccess) {
  17913. onsuccess(scene);
  17914. }
  17915. if (SceneLoader.ShowLoadingScreen) {
  17916. scene.executeWhenReady(function () {
  17917. scene.getEngine().hideLoadingUI();
  17918. });
  17919. }
  17920. };
  17921. var manifestChecked = function (success) {
  17922. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17923. };
  17924. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17925. // Direct load
  17926. loadSceneFromData(sceneFilename.substr(5));
  17927. return;
  17928. }
  17929. if (rootUrl.indexOf("file:") === -1) {
  17930. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17931. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17932. }
  17933. else {
  17934. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17935. }
  17936. };
  17937. // Flags
  17938. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17939. SceneLoader._ShowLoadingScreen = true;
  17940. // Members
  17941. SceneLoader._registeredPlugins = new Array();
  17942. return SceneLoader;
  17943. })();
  17944. BABYLON.SceneLoader = SceneLoader;
  17945. ;
  17946. })(BABYLON || (BABYLON = {}));
  17947. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  17948. (function (BABYLON) {
  17949. var Internals;
  17950. (function (Internals) {
  17951. var checkColors4 = function (colors, count) {
  17952. // Check if color3 was used
  17953. if (colors.length === count * 3) {
  17954. var colors4 = [];
  17955. for (var index = 0; index < colors.length; index += 3) {
  17956. var newIndex = (index / 3) * 4;
  17957. colors4[newIndex] = colors[index];
  17958. colors4[newIndex + 1] = colors[index + 1];
  17959. colors4[newIndex + 2] = colors[index + 2];
  17960. colors4[newIndex + 3] = 1.0;
  17961. }
  17962. return colors4;
  17963. }
  17964. return colors;
  17965. };
  17966. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  17967. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  17968. texture.name = parsedTexture.name;
  17969. texture.hasAlpha = parsedTexture.hasAlpha;
  17970. texture.level = parsedTexture.level;
  17971. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17972. return texture;
  17973. };
  17974. var loadTexture = function (rootUrl, parsedTexture, scene) {
  17975. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17976. return null;
  17977. }
  17978. if (parsedTexture.isCube) {
  17979. return loadCubeTexture(rootUrl, parsedTexture, scene);
  17980. }
  17981. var texture;
  17982. if (parsedTexture.mirrorPlane) {
  17983. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17984. texture._waitingRenderList = parsedTexture.renderList;
  17985. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17986. }
  17987. else if (parsedTexture.isRenderTarget) {
  17988. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17989. texture._waitingRenderList = parsedTexture.renderList;
  17990. }
  17991. else {
  17992. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17993. }
  17994. texture.name = parsedTexture.name;
  17995. texture.hasAlpha = parsedTexture.hasAlpha;
  17996. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17997. texture.level = parsedTexture.level;
  17998. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17999. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18000. texture.uOffset = parsedTexture.uOffset;
  18001. texture.vOffset = parsedTexture.vOffset;
  18002. texture.uScale = parsedTexture.uScale;
  18003. texture.vScale = parsedTexture.vScale;
  18004. texture.uAng = parsedTexture.uAng;
  18005. texture.vAng = parsedTexture.vAng;
  18006. texture.wAng = parsedTexture.wAng;
  18007. texture.wrapU = parsedTexture.wrapU;
  18008. texture.wrapV = parsedTexture.wrapV;
  18009. // Animations
  18010. if (parsedTexture.animations) {
  18011. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18012. var parsedAnimation = parsedTexture.animations[animationIndex];
  18013. texture.animations.push(parseAnimation(parsedAnimation));
  18014. }
  18015. }
  18016. return texture;
  18017. };
  18018. var parseSkeleton = function (parsedSkeleton, scene) {
  18019. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18020. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18021. var parsedBone = parsedSkeleton.bones[index];
  18022. var parentBone = null;
  18023. if (parsedBone.parentBoneIndex > -1) {
  18024. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18025. }
  18026. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18027. if (parsedBone.animation) {
  18028. bone.animations.push(parseAnimation(parsedBone.animation));
  18029. }
  18030. }
  18031. return skeleton;
  18032. };
  18033. var parseFresnelParameters = function (parsedFresnelParameters) {
  18034. var fresnelParameters = new BABYLON.FresnelParameters();
  18035. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18036. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18037. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18038. fresnelParameters.bias = parsedFresnelParameters.bias;
  18039. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18040. return fresnelParameters;
  18041. };
  18042. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18043. var material;
  18044. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18045. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18046. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18047. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18048. material.specularPower = parsedMaterial.specularPower;
  18049. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18050. material.alpha = parsedMaterial.alpha;
  18051. material.id = parsedMaterial.id;
  18052. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18053. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18054. material.wireframe = parsedMaterial.wireframe;
  18055. if (parsedMaterial.diffuseTexture) {
  18056. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18057. }
  18058. if (parsedMaterial.diffuseFresnelParameters) {
  18059. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18060. }
  18061. if (parsedMaterial.ambientTexture) {
  18062. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18063. }
  18064. if (parsedMaterial.opacityTexture) {
  18065. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18066. }
  18067. if (parsedMaterial.opacityFresnelParameters) {
  18068. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18069. }
  18070. if (parsedMaterial.reflectionTexture) {
  18071. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18072. }
  18073. if (parsedMaterial.reflectionFresnelParameters) {
  18074. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18075. }
  18076. if (parsedMaterial.emissiveTexture) {
  18077. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18078. }
  18079. if (parsedMaterial.emissiveFresnelParameters) {
  18080. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18081. }
  18082. if (parsedMaterial.specularTexture) {
  18083. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18084. }
  18085. if (parsedMaterial.bumpTexture) {
  18086. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18087. }
  18088. return material;
  18089. };
  18090. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18091. for (var index = 0; index < parsedData.materials.length; index++) {
  18092. var parsedMaterial = parsedData.materials[index];
  18093. if (parsedMaterial.id === id) {
  18094. return parseMaterial(parsedMaterial, scene, rootUrl);
  18095. }
  18096. }
  18097. return null;
  18098. };
  18099. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18100. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18101. multiMaterial.id = parsedMultiMaterial.id;
  18102. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18103. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18104. var subMatId = parsedMultiMaterial.materials[matIndex];
  18105. if (subMatId) {
  18106. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18107. }
  18108. else {
  18109. multiMaterial.subMaterials.push(null);
  18110. }
  18111. }
  18112. return multiMaterial;
  18113. };
  18114. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18115. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18116. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18117. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18118. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18119. var parsedFlare = parsedLensFlareSystem.flares[index];
  18120. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18121. }
  18122. return lensFlareSystem;
  18123. };
  18124. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18125. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18126. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18127. if (parsedParticleSystem.textureName) {
  18128. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18129. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18130. }
  18131. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18132. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18133. particleSystem.minSize = parsedParticleSystem.minSize;
  18134. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18135. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18136. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18137. particleSystem.emitter = emitter;
  18138. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18139. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18140. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18141. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18142. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18143. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18144. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18145. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18146. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18147. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18148. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18149. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18150. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18151. particleSystem.start();
  18152. return particleSystem;
  18153. };
  18154. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18155. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18156. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18157. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18158. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18159. shadowGenerator.getShadowMap().renderList.push(mesh);
  18160. }
  18161. if (parsedShadowGenerator.usePoissonSampling) {
  18162. shadowGenerator.usePoissonSampling = true;
  18163. }
  18164. else {
  18165. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  18166. }
  18167. return shadowGenerator;
  18168. };
  18169. var parseAnimation = function (parsedAnimation) {
  18170. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18171. var dataType = parsedAnimation.dataType;
  18172. var keys = [];
  18173. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18174. var key = parsedAnimation.keys[index];
  18175. var data;
  18176. switch (dataType) {
  18177. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18178. data = key.values[0];
  18179. break;
  18180. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18181. data = BABYLON.Quaternion.FromArray(key.values);
  18182. break;
  18183. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18184. data = BABYLON.Matrix.FromArray(key.values);
  18185. break;
  18186. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18187. default:
  18188. data = BABYLON.Vector3.FromArray(key.values);
  18189. break;
  18190. }
  18191. keys.push({
  18192. frame: key.frame,
  18193. value: data
  18194. });
  18195. }
  18196. animation.setKeys(keys);
  18197. return animation;
  18198. };
  18199. var parseLight = function (parsedLight, scene) {
  18200. var light;
  18201. switch (parsedLight.type) {
  18202. case 0:
  18203. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18204. break;
  18205. case 1:
  18206. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18207. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  18208. break;
  18209. case 2:
  18210. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18211. break;
  18212. case 3:
  18213. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18214. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18215. break;
  18216. }
  18217. light.id = parsedLight.id;
  18218. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18219. if (parsedLight.intensity !== undefined) {
  18220. light.intensity = parsedLight.intensity;
  18221. }
  18222. if (parsedLight.range) {
  18223. light.range = parsedLight.range;
  18224. }
  18225. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18226. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18227. if (parsedLight.excludedMeshesIds) {
  18228. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18229. }
  18230. // Parent
  18231. if (parsedLight.parentId) {
  18232. light._waitingParentId = parsedLight.parentId;
  18233. }
  18234. if (parsedLight.includedOnlyMeshesIds) {
  18235. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18236. }
  18237. // Animations
  18238. if (parsedLight.animations) {
  18239. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18240. var parsedAnimation = parsedLight.animations[animationIndex];
  18241. light.animations.push(parseAnimation(parsedAnimation));
  18242. }
  18243. }
  18244. if (parsedLight.autoAnimate) {
  18245. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  18246. }
  18247. };
  18248. var parseCamera = function (parsedCamera, scene) {
  18249. var camera;
  18250. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  18251. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  18252. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  18253. var alpha = parsedCamera.alpha;
  18254. var beta = parsedCamera.beta;
  18255. var radius = parsedCamera.radius;
  18256. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18257. var eye_space = parsedCamera.eye_space;
  18258. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18259. }
  18260. else {
  18261. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18262. }
  18263. }
  18264. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18265. eye_space = parsedCamera.eye_space;
  18266. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18267. }
  18268. else if (parsedCamera.type === "DeviceOrientationCamera") {
  18269. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18270. }
  18271. else if (parsedCamera.type === "FollowCamera") {
  18272. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18273. camera.heightOffset = parsedCamera.heightOffset;
  18274. camera.radius = parsedCamera.radius;
  18275. camera.rotationOffset = parsedCamera.rotationOffset;
  18276. if (lockedTargetMesh)
  18277. camera.target = lockedTargetMesh;
  18278. }
  18279. else if (parsedCamera.type === "GamepadCamera") {
  18280. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  18281. }
  18282. else if (parsedCamera.type === "OculusCamera") {
  18283. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  18284. }
  18285. else if (parsedCamera.type === "OculusGamepadCamera") {
  18286. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  18287. }
  18288. else if (parsedCamera.type === "TouchCamera") {
  18289. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  18290. }
  18291. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  18292. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  18293. }
  18294. else if (parsedCamera.type === "WebVRCamera") {
  18295. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  18296. }
  18297. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  18298. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  18299. }
  18300. else {
  18301. // Free Camera is the default value
  18302. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  18303. }
  18304. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  18305. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  18306. camera.lockedTarget = lockedTargetMesh;
  18307. }
  18308. camera.id = parsedCamera.id;
  18309. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  18310. // Parent
  18311. if (parsedCamera.parentId) {
  18312. camera._waitingParentId = parsedCamera.parentId;
  18313. }
  18314. // Target
  18315. if (parsedCamera.target) {
  18316. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18317. }
  18318. else {
  18319. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  18320. }
  18321. camera.fov = parsedCamera.fov;
  18322. camera.minZ = parsedCamera.minZ;
  18323. camera.maxZ = parsedCamera.maxZ;
  18324. camera.speed = parsedCamera.speed;
  18325. camera.inertia = parsedCamera.inertia;
  18326. camera.checkCollisions = parsedCamera.checkCollisions;
  18327. camera.applyGravity = parsedCamera.applyGravity;
  18328. if (parsedCamera.ellipsoid) {
  18329. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  18330. }
  18331. // Animations
  18332. if (parsedCamera.animations) {
  18333. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18334. var parsedAnimation = parsedCamera.animations[animationIndex];
  18335. camera.animations.push(parseAnimation(parsedAnimation));
  18336. }
  18337. }
  18338. if (parsedCamera.autoAnimate) {
  18339. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  18340. }
  18341. // Layer Mask
  18342. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  18343. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  18344. }
  18345. else {
  18346. camera.layerMask = 0xFFFFFFFF;
  18347. }
  18348. return camera;
  18349. };
  18350. var parseGeometry = function (parsedGeometry, scene) {
  18351. var id = parsedGeometry.id;
  18352. return scene.getGeometryByID(id);
  18353. };
  18354. var parseBox = function (parsedBox, scene) {
  18355. if (parseGeometry(parsedBox, scene)) {
  18356. return null; // null since geometry could be something else than a box...
  18357. }
  18358. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  18359. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  18360. scene.pushGeometry(box, true);
  18361. return box;
  18362. };
  18363. var parseSphere = function (parsedSphere, scene) {
  18364. if (parseGeometry(parsedSphere, scene)) {
  18365. return null; // null since geometry could be something else than a sphere...
  18366. }
  18367. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18368. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18369. scene.pushGeometry(sphere, true);
  18370. return sphere;
  18371. };
  18372. var parseCylinder = function (parsedCylinder, scene) {
  18373. if (parseGeometry(parsedCylinder, scene)) {
  18374. return null; // null since geometry could be something else than a cylinder...
  18375. }
  18376. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18377. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18378. scene.pushGeometry(cylinder, true);
  18379. return cylinder;
  18380. };
  18381. var parseTorus = function (parsedTorus, scene) {
  18382. if (parseGeometry(parsedTorus, scene)) {
  18383. return null; // null since geometry could be something else than a torus...
  18384. }
  18385. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18386. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18387. scene.pushGeometry(torus, true);
  18388. return torus;
  18389. };
  18390. var parseGround = function (parsedGround, scene) {
  18391. if (parseGeometry(parsedGround, scene)) {
  18392. return null; // null since geometry could be something else than a ground...
  18393. }
  18394. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18395. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18396. scene.pushGeometry(ground, true);
  18397. return ground;
  18398. };
  18399. var parsePlane = function (parsedPlane, scene) {
  18400. if (parseGeometry(parsedPlane, scene)) {
  18401. return null; // null since geometry could be something else than a plane...
  18402. }
  18403. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18404. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18405. scene.pushGeometry(plane, true);
  18406. return plane;
  18407. };
  18408. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18409. if (parseGeometry(parsedTorusKnot, scene)) {
  18410. return null; // null since geometry could be something else than a torusKnot...
  18411. }
  18412. var torusKnot = new BABYLON.Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  18413. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18414. scene.pushGeometry(torusKnot, true);
  18415. return torusKnot;
  18416. };
  18417. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18418. if (parseGeometry(parsedVertexData, scene)) {
  18419. return null; // null since geometry could be a primitive
  18420. }
  18421. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18422. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18423. if (parsedVertexData.delayLoadingFile) {
  18424. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18425. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18426. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18427. geometry._delayInfo = [];
  18428. if (parsedVertexData.hasUVs) {
  18429. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18430. }
  18431. if (parsedVertexData.hasUVs2) {
  18432. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18433. }
  18434. if (parsedVertexData.hasColors) {
  18435. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18436. }
  18437. if (parsedVertexData.hasMatricesIndices) {
  18438. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18439. }
  18440. if (parsedVertexData.hasMatricesWeights) {
  18441. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18442. }
  18443. geometry._delayLoadingFunction = importVertexData;
  18444. }
  18445. else {
  18446. importVertexData(parsedVertexData, geometry);
  18447. }
  18448. scene.pushGeometry(geometry, true);
  18449. return geometry;
  18450. };
  18451. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18452. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18453. mesh.id = parsedMesh.id;
  18454. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18455. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18456. if (parsedMesh.rotationQuaternion) {
  18457. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18458. }
  18459. else if (parsedMesh.rotation) {
  18460. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18461. }
  18462. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18463. if (parsedMesh.localMatrix) {
  18464. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18465. }
  18466. else if (parsedMesh.pivotMatrix) {
  18467. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18468. }
  18469. mesh.setEnabled(parsedMesh.isEnabled);
  18470. mesh.isVisible = parsedMesh.isVisible;
  18471. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18472. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18473. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18474. if (parsedMesh.applyFog !== undefined) {
  18475. mesh.applyFog = parsedMesh.applyFog;
  18476. }
  18477. if (parsedMesh.pickable !== undefined) {
  18478. mesh.isPickable = parsedMesh.pickable;
  18479. }
  18480. if (parsedMesh.alphaIndex !== undefined) {
  18481. mesh.alphaIndex = parsedMesh.alphaIndex;
  18482. }
  18483. mesh.receiveShadows = parsedMesh.receiveShadows;
  18484. mesh.billboardMode = parsedMesh.billboardMode;
  18485. if (parsedMesh.visibility !== undefined) {
  18486. mesh.visibility = parsedMesh.visibility;
  18487. }
  18488. mesh.checkCollisions = parsedMesh.checkCollisions;
  18489. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18490. // Parent
  18491. if (parsedMesh.parentId) {
  18492. mesh._waitingParentId = parsedMesh.parentId;
  18493. }
  18494. // Actions
  18495. if (parsedMesh.actions !== undefined) {
  18496. mesh._waitingActions = parsedMesh.actions;
  18497. }
  18498. // Geometry
  18499. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18500. if (parsedMesh.delayLoadingFile) {
  18501. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18502. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18503. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18504. if (parsedMesh._binaryInfo) {
  18505. mesh._binaryInfo = parsedMesh._binaryInfo;
  18506. }
  18507. mesh._delayInfo = [];
  18508. if (parsedMesh.hasUVs) {
  18509. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18510. }
  18511. if (parsedMesh.hasUVs2) {
  18512. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18513. }
  18514. if (parsedMesh.hasColors) {
  18515. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18516. }
  18517. if (parsedMesh.hasMatricesIndices) {
  18518. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18519. }
  18520. if (parsedMesh.hasMatricesWeights) {
  18521. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18522. }
  18523. mesh._delayLoadingFunction = importGeometry;
  18524. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18525. mesh._checkDelayState();
  18526. }
  18527. }
  18528. else {
  18529. importGeometry(parsedMesh, mesh);
  18530. }
  18531. // Material
  18532. if (parsedMesh.materialId) {
  18533. mesh.setMaterialByID(parsedMesh.materialId);
  18534. }
  18535. else {
  18536. mesh.material = null;
  18537. }
  18538. // Skeleton
  18539. if (parsedMesh.skeletonId > -1) {
  18540. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18541. }
  18542. // Physics
  18543. if (parsedMesh.physicsImpostor) {
  18544. if (!scene.isPhysicsEnabled()) {
  18545. scene.enablePhysics();
  18546. }
  18547. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18548. }
  18549. // Animations
  18550. if (parsedMesh.animations) {
  18551. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18552. var parsedAnimation = parsedMesh.animations[animationIndex];
  18553. mesh.animations.push(parseAnimation(parsedAnimation));
  18554. }
  18555. }
  18556. if (parsedMesh.autoAnimate) {
  18557. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18558. }
  18559. // Layer Mask
  18560. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18561. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18562. }
  18563. else {
  18564. mesh.layerMask = 0xFFFFFFFF;
  18565. }
  18566. // Instances
  18567. if (parsedMesh.instances) {
  18568. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18569. var parsedInstance = parsedMesh.instances[index];
  18570. var instance = mesh.createInstance(parsedInstance.name);
  18571. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18572. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18573. if (parsedInstance.rotationQuaternion) {
  18574. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18575. }
  18576. else if (parsedInstance.rotation) {
  18577. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18578. }
  18579. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18580. instance.checkCollisions = mesh.checkCollisions;
  18581. if (parsedMesh.animations) {
  18582. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18583. parsedAnimation = parsedMesh.animations[animationIndex];
  18584. instance.animations.push(parseAnimation(parsedAnimation));
  18585. }
  18586. }
  18587. }
  18588. }
  18589. return mesh;
  18590. };
  18591. var parseActions = function (parsedActions, object, scene) {
  18592. var actionManager = new BABYLON.ActionManager(scene);
  18593. if (object === null)
  18594. scene.actionManager = actionManager;
  18595. else
  18596. object.actionManager = actionManager;
  18597. // instanciate a new object
  18598. var instanciate = function (name, params) {
  18599. var newInstance = Object.create(BABYLON[name].prototype);
  18600. newInstance.constructor.apply(newInstance, params);
  18601. return newInstance;
  18602. };
  18603. var parseParameter = function (name, value, target, propertyPath) {
  18604. if (propertyPath === null) {
  18605. // String, boolean or float
  18606. var floatValue = parseFloat(value);
  18607. if (value === "true" || value === "false")
  18608. return value === "true";
  18609. else
  18610. return isNaN(floatValue) ? value : floatValue;
  18611. }
  18612. var effectiveTarget = propertyPath.split(".");
  18613. var values = value.split(",");
  18614. for (var i = 0; i < effectiveTarget.length; i++) {
  18615. target = target[effectiveTarget[i]];
  18616. }
  18617. // Return appropriate value with its type
  18618. if (target instanceof Boolean)
  18619. return values[0] === "true";
  18620. if (target instanceof String)
  18621. return values[0];
  18622. // Parameters with multiple values such as Vector3 etc.
  18623. var split = new Array();
  18624. for (var i = 0; i < values.length; i++)
  18625. split.push(parseFloat(values[i]));
  18626. if (target instanceof BABYLON.Vector3)
  18627. return BABYLON.Vector3.FromArray(split);
  18628. if (target instanceof BABYLON.Vector4)
  18629. return BABYLON.Vector4.FromArray(split);
  18630. if (target instanceof BABYLON.Color3)
  18631. return BABYLON.Color3.FromArray(split);
  18632. if (target instanceof BABYLON.Color4)
  18633. return BABYLON.Color4.FromArray(split);
  18634. return parseFloat(values[0]);
  18635. };
  18636. // traverse graph per trigger
  18637. var traverse = function (parsedAction, trigger, condition, action) {
  18638. var parameters = new Array();
  18639. var target = null;
  18640. var propertyPath = null;
  18641. // Parameters
  18642. if (parsedAction.type === 2)
  18643. parameters.push(actionManager);
  18644. else
  18645. parameters.push(trigger);
  18646. for (var i = 0; i < parsedAction.properties.length; i++) {
  18647. var value = parsedAction.properties[i].value;
  18648. var name = parsedAction.properties[i].name;
  18649. if (name === "target")
  18650. value = target = scene.getNodeByName(value);
  18651. else if (name === "parent")
  18652. value = scene.getNodeByName(value);
  18653. else if (name !== "propertyPath") {
  18654. if (parsedAction.type === 2 && name === "operator")
  18655. value = BABYLON.ValueCondition[value];
  18656. else
  18657. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  18658. }
  18659. else {
  18660. propertyPath = value;
  18661. }
  18662. parameters.push(value);
  18663. }
  18664. parameters.push(condition);
  18665. // If interpolate value action
  18666. if (parsedAction.name === "InterpolateValueAction") {
  18667. var param = parameters[parameters.length - 2];
  18668. parameters[parameters.length - 1] = param;
  18669. parameters[parameters.length - 2] = condition;
  18670. }
  18671. // Action or condition(s)
  18672. var newAction = instanciate(parsedAction.name, parameters);
  18673. if (newAction instanceof BABYLON.Condition) {
  18674. condition = newAction;
  18675. newAction = action;
  18676. }
  18677. else {
  18678. condition = null;
  18679. if (action)
  18680. action.then(newAction);
  18681. else
  18682. actionManager.registerAction(newAction);
  18683. }
  18684. for (var i = 0; i < parsedAction.children.length; i++)
  18685. traverse(parsedAction.children[i], trigger, condition, newAction);
  18686. };
  18687. for (var i = 0; i < parsedActions.children.length; i++) {
  18688. var triggerParams;
  18689. var trigger = parsedActions.children[i];
  18690. if (trigger.properties.length > 0) {
  18691. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  18692. }
  18693. else
  18694. triggerParams = BABYLON.ActionManager[trigger.name];
  18695. for (var j = 0; j < trigger.children.length; j++)
  18696. traverse(trigger.children[j], triggerParams, null, null);
  18697. }
  18698. };
  18699. var parseSound = function (parsedSound, scene, rootUrl) {
  18700. var soundName = parsedSound.name;
  18701. var soundUrl = rootUrl + soundName;
  18702. var options = {
  18703. autoplay: parsedSound.autoplay,
  18704. loop: parsedSound.loop,
  18705. volume: parsedSound.volume,
  18706. spatialSound: parsedSound.spatialSound,
  18707. maxDistance: parsedSound.maxDistance,
  18708. rolloffFactor: parsedSound.rolloffFactor,
  18709. refDistance: parsedSound.refDistance,
  18710. distanceModel: parsedSound.distanceModel,
  18711. panningModel: parsedSound.panningModel
  18712. };
  18713. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  18714. scene._removePendingData(newSound);
  18715. }, options);
  18716. scene._addPendingData(newSound);
  18717. if (parsedSound.position) {
  18718. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  18719. newSound.setPosition(soundPosition);
  18720. }
  18721. if (parsedSound.isDirectional) {
  18722. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  18723. if (parsedSound.localDirectionToMesh) {
  18724. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  18725. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  18726. }
  18727. }
  18728. if (parsedSound.connectedMeshId) {
  18729. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  18730. if (connectedMesh) {
  18731. newSound.attachToMesh(connectedMesh);
  18732. }
  18733. }
  18734. };
  18735. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18736. names = (names instanceof Array) ? names : [names];
  18737. for (var i in names) {
  18738. if (mesh.name === names[i]) {
  18739. hierarchyIds.push(mesh.id);
  18740. return true;
  18741. }
  18742. }
  18743. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18744. hierarchyIds.push(mesh.id);
  18745. return true;
  18746. }
  18747. return false;
  18748. };
  18749. var importVertexData = function (parsedVertexData, geometry) {
  18750. var vertexData = new BABYLON.VertexData();
  18751. // positions
  18752. var positions = parsedVertexData.positions;
  18753. if (positions) {
  18754. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18755. }
  18756. // normals
  18757. var normals = parsedVertexData.normals;
  18758. if (normals) {
  18759. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18760. }
  18761. // uvs
  18762. var uvs = parsedVertexData.uvs;
  18763. if (uvs) {
  18764. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  18765. }
  18766. // uv2s
  18767. var uv2s = parsedVertexData.uv2s;
  18768. if (uv2s) {
  18769. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  18770. }
  18771. // colors
  18772. var colors = parsedVertexData.colors;
  18773. if (colors) {
  18774. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  18775. }
  18776. // matricesIndices
  18777. var matricesIndices = parsedVertexData.matricesIndices;
  18778. if (matricesIndices) {
  18779. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  18780. }
  18781. // matricesWeights
  18782. var matricesWeights = parsedVertexData.matricesWeights;
  18783. if (matricesWeights) {
  18784. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  18785. }
  18786. // indices
  18787. var indices = parsedVertexData.indices;
  18788. if (indices) {
  18789. vertexData.indices = indices;
  18790. }
  18791. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  18792. };
  18793. var importGeometry = function (parsedGeometry, mesh) {
  18794. var scene = mesh.getScene();
  18795. // Geometry
  18796. var geometryId = parsedGeometry.geometryId;
  18797. if (geometryId) {
  18798. var geometry = scene.getGeometryByID(geometryId);
  18799. if (geometry) {
  18800. geometry.applyToMesh(mesh);
  18801. }
  18802. }
  18803. else if (parsedGeometry instanceof ArrayBuffer) {
  18804. var binaryInfo = mesh._binaryInfo;
  18805. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  18806. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  18807. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  18808. }
  18809. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  18810. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  18811. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  18812. }
  18813. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  18814. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  18815. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  18816. }
  18817. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  18818. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  18819. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  18820. }
  18821. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  18822. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  18823. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  18824. }
  18825. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  18826. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  18827. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  18828. }
  18829. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  18830. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  18831. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  18832. }
  18833. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  18834. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  18835. mesh.setIndices(indicesData);
  18836. }
  18837. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  18838. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  18839. mesh.subMeshes = [];
  18840. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  18841. var materialIndex = subMeshesData[(i * 5) + 0];
  18842. var verticesStart = subMeshesData[(i * 5) + 1];
  18843. var verticesCount = subMeshesData[(i * 5) + 2];
  18844. var indexStart = subMeshesData[(i * 5) + 3];
  18845. var indexCount = subMeshesData[(i * 5) + 4];
  18846. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  18847. }
  18848. }
  18849. }
  18850. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  18851. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  18852. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  18853. if (parsedGeometry.uvs) {
  18854. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  18855. }
  18856. if (parsedGeometry.uvs2) {
  18857. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  18858. }
  18859. if (parsedGeometry.colors) {
  18860. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  18861. }
  18862. if (parsedGeometry.matricesIndices) {
  18863. if (!parsedGeometry.matricesIndices._isExpanded) {
  18864. var floatIndices = [];
  18865. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  18866. var matricesIndex = parsedGeometry.matricesIndices[i];
  18867. floatIndices.push(matricesIndex & 0x000000FF);
  18868. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  18869. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  18870. floatIndices.push(matricesIndex >> 24);
  18871. }
  18872. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  18873. }
  18874. else {
  18875. delete parsedGeometry.matricesIndices._isExpanded;
  18876. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  18877. }
  18878. }
  18879. if (parsedGeometry.matricesWeights) {
  18880. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  18881. }
  18882. mesh.setIndices(parsedGeometry.indices);
  18883. // SubMeshes
  18884. if (parsedGeometry.subMeshes) {
  18885. mesh.subMeshes = [];
  18886. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  18887. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  18888. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  18889. }
  18890. }
  18891. }
  18892. // Flat shading
  18893. if (mesh._shouldGenerateFlatShading) {
  18894. mesh.convertToFlatShadedMesh();
  18895. delete mesh._shouldGenerateFlatShading;
  18896. }
  18897. // Update
  18898. mesh.computeWorldMatrix(true);
  18899. // Octree
  18900. if (scene._selectionOctree) {
  18901. scene._selectionOctree.addMesh(mesh);
  18902. }
  18903. };
  18904. BABYLON.SceneLoader.RegisterPlugin({
  18905. extensions: ".babylon",
  18906. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  18907. var parsedData = JSON.parse(data);
  18908. var loadedSkeletonsIds = [];
  18909. var loadedMaterialsIds = [];
  18910. var hierarchyIds = [];
  18911. for (var index = 0; index < parsedData.meshes.length; index++) {
  18912. var parsedMesh = parsedData.meshes[index];
  18913. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  18914. if (meshesNames instanceof Array) {
  18915. // Remove found mesh name from list.
  18916. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  18917. }
  18918. // Material ?
  18919. if (parsedMesh.materialId) {
  18920. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  18921. if (!materialFound) {
  18922. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  18923. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  18924. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  18925. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18926. var subMatId = parsedMultiMaterial.materials[matIndex];
  18927. loadedMaterialsIds.push(subMatId);
  18928. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  18929. }
  18930. loadedMaterialsIds.push(parsedMultiMaterial.id);
  18931. parseMultiMaterial(parsedMultiMaterial, scene);
  18932. materialFound = true;
  18933. break;
  18934. }
  18935. }
  18936. }
  18937. if (!materialFound) {
  18938. loadedMaterialsIds.push(parsedMesh.materialId);
  18939. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  18940. }
  18941. }
  18942. // Skeleton ?
  18943. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  18944. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  18945. if (!skeletonAlreadyLoaded) {
  18946. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  18947. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  18948. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  18949. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  18950. loadedSkeletonsIds.push(parsedSkeleton.id);
  18951. }
  18952. }
  18953. }
  18954. }
  18955. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  18956. meshes.push(mesh);
  18957. }
  18958. }
  18959. for (index = 0; index < scene.meshes.length; index++) {
  18960. var currentMesh = scene.meshes[index];
  18961. if (currentMesh._waitingParentId) {
  18962. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  18963. currentMesh._waitingParentId = undefined;
  18964. }
  18965. }
  18966. // Particles
  18967. if (parsedData.particleSystems) {
  18968. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18969. var parsedParticleSystem = parsedData.particleSystems[index];
  18970. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  18971. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  18972. }
  18973. }
  18974. }
  18975. return true;
  18976. },
  18977. load: function (scene, data, rootUrl) {
  18978. var parsedData = JSON.parse(data);
  18979. // Scene
  18980. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  18981. scene.autoClear = parsedData.autoClear;
  18982. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  18983. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  18984. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  18985. // Fog
  18986. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  18987. scene.fogMode = parsedData.fogMode;
  18988. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  18989. scene.fogStart = parsedData.fogStart;
  18990. scene.fogEnd = parsedData.fogEnd;
  18991. scene.fogDensity = parsedData.fogDensity;
  18992. }
  18993. for (var index = 0; index < parsedData.lights.length; index++) {
  18994. var parsedLight = parsedData.lights[index];
  18995. parseLight(parsedLight, scene);
  18996. }
  18997. // Materials
  18998. if (parsedData.materials) {
  18999. for (index = 0; index < parsedData.materials.length; index++) {
  19000. var parsedMaterial = parsedData.materials[index];
  19001. parseMaterial(parsedMaterial, scene, rootUrl);
  19002. }
  19003. }
  19004. if (parsedData.multiMaterials) {
  19005. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19006. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19007. parseMultiMaterial(parsedMultiMaterial, scene);
  19008. }
  19009. }
  19010. // Skeletons
  19011. if (parsedData.skeletons) {
  19012. for (index = 0; index < parsedData.skeletons.length; index++) {
  19013. var parsedSkeleton = parsedData.skeletons[index];
  19014. parseSkeleton(parsedSkeleton, scene);
  19015. }
  19016. }
  19017. // Geometries
  19018. var geometries = parsedData.geometries;
  19019. if (geometries) {
  19020. // Boxes
  19021. var boxes = geometries.boxes;
  19022. if (boxes) {
  19023. for (index = 0; index < boxes.length; index++) {
  19024. var parsedBox = boxes[index];
  19025. parseBox(parsedBox, scene);
  19026. }
  19027. }
  19028. // Spheres
  19029. var spheres = geometries.spheres;
  19030. if (spheres) {
  19031. for (index = 0; index < spheres.length; index++) {
  19032. var parsedSphere = spheres[index];
  19033. parseSphere(parsedSphere, scene);
  19034. }
  19035. }
  19036. // Cylinders
  19037. var cylinders = geometries.cylinders;
  19038. if (cylinders) {
  19039. for (index = 0; index < cylinders.length; index++) {
  19040. var parsedCylinder = cylinders[index];
  19041. parseCylinder(parsedCylinder, scene);
  19042. }
  19043. }
  19044. // Toruses
  19045. var toruses = geometries.toruses;
  19046. if (toruses) {
  19047. for (index = 0; index < toruses.length; index++) {
  19048. var parsedTorus = toruses[index];
  19049. parseTorus(parsedTorus, scene);
  19050. }
  19051. }
  19052. // Grounds
  19053. var grounds = geometries.grounds;
  19054. if (grounds) {
  19055. for (index = 0; index < grounds.length; index++) {
  19056. var parsedGround = grounds[index];
  19057. parseGround(parsedGround, scene);
  19058. }
  19059. }
  19060. // Planes
  19061. var planes = geometries.planes;
  19062. if (planes) {
  19063. for (index = 0; index < planes.length; index++) {
  19064. var parsedPlane = planes[index];
  19065. parsePlane(parsedPlane, scene);
  19066. }
  19067. }
  19068. // TorusKnots
  19069. var torusKnots = geometries.torusKnots;
  19070. if (torusKnots) {
  19071. for (index = 0; index < torusKnots.length; index++) {
  19072. var parsedTorusKnot = torusKnots[index];
  19073. parseTorusKnot(parsedTorusKnot, scene);
  19074. }
  19075. }
  19076. // VertexData
  19077. var vertexData = geometries.vertexData;
  19078. if (vertexData) {
  19079. for (index = 0; index < vertexData.length; index++) {
  19080. var parsedVertexData = vertexData[index];
  19081. parseVertexData(parsedVertexData, scene, rootUrl);
  19082. }
  19083. }
  19084. }
  19085. for (index = 0; index < parsedData.meshes.length; index++) {
  19086. var parsedMesh = parsedData.meshes[index];
  19087. parseMesh(parsedMesh, scene, rootUrl);
  19088. }
  19089. for (index = 0; index < parsedData.cameras.length; index++) {
  19090. var parsedCamera = parsedData.cameras[index];
  19091. parseCamera(parsedCamera, scene);
  19092. }
  19093. if (parsedData.activeCameraID) {
  19094. scene.setActiveCameraByID(parsedData.activeCameraID);
  19095. }
  19096. for (index = 0; index < scene.cameras.length; index++) {
  19097. var camera = scene.cameras[index];
  19098. if (camera._waitingParentId) {
  19099. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19100. camera._waitingParentId = undefined;
  19101. }
  19102. }
  19103. for (index = 0; index < scene.lights.length; index++) {
  19104. var light = scene.lights[index];
  19105. if (light._waitingParentId) {
  19106. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19107. light._waitingParentId = undefined;
  19108. }
  19109. }
  19110. for (index = 0; index < scene.meshes.length; index++) {
  19111. var mesh = scene.meshes[index];
  19112. if (mesh._waitingParentId) {
  19113. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19114. mesh._waitingParentId = undefined;
  19115. }
  19116. if (mesh._waitingActions) {
  19117. parseActions(mesh._waitingActions, mesh, scene);
  19118. mesh._waitingActions = undefined;
  19119. }
  19120. }
  19121. // Particles Systems
  19122. if (parsedData.particleSystems) {
  19123. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19124. var parsedParticleSystem = parsedData.particleSystems[index];
  19125. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19126. }
  19127. }
  19128. // Lens flares
  19129. if (parsedData.lensFlareSystems) {
  19130. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19131. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19132. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19133. }
  19134. }
  19135. // Shadows
  19136. if (parsedData.shadowGenerators) {
  19137. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  19138. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  19139. parseShadowGenerator(parsedShadowGenerator, scene);
  19140. }
  19141. }
  19142. // Sounds
  19143. if (parsedData.sounds && scene.getEngine().getAudioEngine().canUseWebAudio) {
  19144. for (index = 0; index < parsedData.sounds.length; index++) {
  19145. var parsedSound = parsedData.sounds[index];
  19146. parseSound(parsedSound, scene, rootUrl);
  19147. }
  19148. }
  19149. // Actions (scene)
  19150. if (parsedData.actions) {
  19151. parseActions(parsedData.actions, null, scene);
  19152. }
  19153. // Finish
  19154. return true;
  19155. }
  19156. });
  19157. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  19158. })(BABYLON || (BABYLON = {}));
  19159. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  19160. (function (BABYLON) {
  19161. // Unique ID when we import meshes from Babylon to CSG
  19162. var currentCSGMeshId = 0;
  19163. // # class Vertex
  19164. // Represents a vertex of a polygon. Use your own vertex class instead of this
  19165. // one to provide additional features like texture coordinates and vertex
  19166. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  19167. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  19168. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  19169. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  19170. // is not used anywhere else.
  19171. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  19172. var Vertex = (function () {
  19173. function Vertex(pos, normal, uv) {
  19174. this.pos = pos;
  19175. this.normal = normal;
  19176. this.uv = uv;
  19177. }
  19178. Vertex.prototype.clone = function () {
  19179. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  19180. };
  19181. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  19182. // orientation of a polygon is flipped.
  19183. Vertex.prototype.flip = function () {
  19184. this.normal = this.normal.scale(-1);
  19185. };
  19186. // Create a new vertex between this vertex and `other` by linearly
  19187. // interpolating all properties using a parameter of `t`. Subclasses should
  19188. // override this to interpolate additional properties.
  19189. Vertex.prototype.interpolate = function (other, t) {
  19190. return new Vertex(BABYLON.Vector3.Lerp(this.pos, other.pos, t), BABYLON.Vector3.Lerp(this.normal, other.normal, t), BABYLON.Vector2.Lerp(this.uv, other.uv, t));
  19191. };
  19192. return Vertex;
  19193. })();
  19194. // # class Plane
  19195. // Represents a plane in 3D space.
  19196. var Plane = (function () {
  19197. function Plane(normal, w) {
  19198. this.normal = normal;
  19199. this.w = w;
  19200. }
  19201. Plane.FromPoints = function (a, b, c) {
  19202. var v0 = c.subtract(a);
  19203. var v1 = b.subtract(a);
  19204. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  19205. return null;
  19206. }
  19207. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  19208. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  19209. };
  19210. Plane.prototype.clone = function () {
  19211. return new Plane(this.normal.clone(), this.w);
  19212. };
  19213. Plane.prototype.flip = function () {
  19214. this.normal.scaleInPlace(-1);
  19215. this.w = -this.w;
  19216. };
  19217. // Split `polygon` by this plane if needed, then put the polygon or polygon
  19218. // fragments in the appropriate lists. Coplanar polygons go into either
  19219. // `coplanarFront` or `coplanarBack` depending on their orientation with
  19220. // respect to this plane. Polygons in front or in back of this plane go into
  19221. // either `front` or `back`.
  19222. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  19223. var COPLANAR = 0;
  19224. var FRONT = 1;
  19225. var BACK = 2;
  19226. var SPANNING = 3;
  19227. // Classify each point as well as the entire polygon into one of the above
  19228. // four classes.
  19229. var polygonType = 0;
  19230. var types = [];
  19231. for (var i = 0; i < polygon.vertices.length; i++) {
  19232. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  19233. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  19234. polygonType |= type;
  19235. types.push(type);
  19236. }
  19237. switch (polygonType) {
  19238. case COPLANAR:
  19239. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  19240. break;
  19241. case FRONT:
  19242. front.push(polygon);
  19243. break;
  19244. case BACK:
  19245. back.push(polygon);
  19246. break;
  19247. case SPANNING:
  19248. var f = [], b = [];
  19249. for (i = 0; i < polygon.vertices.length; i++) {
  19250. var j = (i + 1) % polygon.vertices.length;
  19251. var ti = types[i], tj = types[j];
  19252. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  19253. if (ti != BACK)
  19254. f.push(vi);
  19255. if (ti != FRONT)
  19256. b.push(ti != BACK ? vi.clone() : vi);
  19257. if ((ti | tj) == SPANNING) {
  19258. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  19259. var v = vi.interpolate(vj, t);
  19260. f.push(v);
  19261. b.push(v.clone());
  19262. }
  19263. }
  19264. if (f.length >= 3) {
  19265. var poly = new Polygon(f, polygon.shared);
  19266. if (poly.plane)
  19267. front.push(poly);
  19268. }
  19269. if (b.length >= 3) {
  19270. poly = new Polygon(b, polygon.shared);
  19271. if (poly.plane)
  19272. back.push(poly);
  19273. }
  19274. break;
  19275. }
  19276. };
  19277. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  19278. // point is on the plane.
  19279. Plane.EPSILON = 1e-5;
  19280. return Plane;
  19281. })();
  19282. // # class Polygon
  19283. // Represents a convex polygon. The vertices used to initialize a polygon must
  19284. // be coplanar and form a convex loop.
  19285. //
  19286. // Each convex polygon has a `shared` property, which is shared between all
  19287. // polygons that are clones of each other or were split from the same polygon.
  19288. // This can be used to define per-polygon properties (such as surface color).
  19289. var Polygon = (function () {
  19290. function Polygon(vertices, shared) {
  19291. this.vertices = vertices;
  19292. this.shared = shared;
  19293. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  19294. }
  19295. Polygon.prototype.clone = function () {
  19296. var vertices = this.vertices.map(function (v) { return v.clone(); });
  19297. return new Polygon(vertices, this.shared);
  19298. };
  19299. Polygon.prototype.flip = function () {
  19300. this.vertices.reverse().map(function (v) {
  19301. v.flip();
  19302. });
  19303. this.plane.flip();
  19304. };
  19305. return Polygon;
  19306. })();
  19307. // # class Node
  19308. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  19309. // by picking a polygon to split along. That polygon (and all other coplanar
  19310. // polygons) are added directly to that node and the other polygons are added to
  19311. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  19312. // no distinction between internal and leaf nodes.
  19313. var Node = (function () {
  19314. function Node(polygons) {
  19315. this.plane = null;
  19316. this.front = null;
  19317. this.back = null;
  19318. this.polygons = [];
  19319. if (polygons) {
  19320. this.build(polygons);
  19321. }
  19322. }
  19323. Node.prototype.clone = function () {
  19324. var node = new Node();
  19325. node.plane = this.plane && this.plane.clone();
  19326. node.front = this.front && this.front.clone();
  19327. node.back = this.back && this.back.clone();
  19328. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  19329. return node;
  19330. };
  19331. // Convert solid space to empty space and empty space to solid space.
  19332. Node.prototype.invert = function () {
  19333. for (var i = 0; i < this.polygons.length; i++) {
  19334. this.polygons[i].flip();
  19335. }
  19336. if (this.plane) {
  19337. this.plane.flip();
  19338. }
  19339. if (this.front) {
  19340. this.front.invert();
  19341. }
  19342. if (this.back) {
  19343. this.back.invert();
  19344. }
  19345. var temp = this.front;
  19346. this.front = this.back;
  19347. this.back = temp;
  19348. };
  19349. // Recursively remove all polygons in `polygons` that are inside this BSP
  19350. // tree.
  19351. Node.prototype.clipPolygons = function (polygons) {
  19352. if (!this.plane)
  19353. return polygons.slice();
  19354. var front = [], back = [];
  19355. for (var i = 0; i < polygons.length; i++) {
  19356. this.plane.splitPolygon(polygons[i], front, back, front, back);
  19357. }
  19358. if (this.front) {
  19359. front = this.front.clipPolygons(front);
  19360. }
  19361. if (this.back) {
  19362. back = this.back.clipPolygons(back);
  19363. }
  19364. else {
  19365. back = [];
  19366. }
  19367. return front.concat(back);
  19368. };
  19369. // Remove all polygons in this BSP tree that are inside the other BSP tree
  19370. // `bsp`.
  19371. Node.prototype.clipTo = function (bsp) {
  19372. this.polygons = bsp.clipPolygons(this.polygons);
  19373. if (this.front)
  19374. this.front.clipTo(bsp);
  19375. if (this.back)
  19376. this.back.clipTo(bsp);
  19377. };
  19378. // Return a list of all polygons in this BSP tree.
  19379. Node.prototype.allPolygons = function () {
  19380. var polygons = this.polygons.slice();
  19381. if (this.front)
  19382. polygons = polygons.concat(this.front.allPolygons());
  19383. if (this.back)
  19384. polygons = polygons.concat(this.back.allPolygons());
  19385. return polygons;
  19386. };
  19387. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  19388. // new polygons are filtered down to the bottom of the tree and become new
  19389. // nodes there. Each set of polygons is partitioned using the first polygon
  19390. // (no heuristic is used to pick a good split).
  19391. Node.prototype.build = function (polygons) {
  19392. if (!polygons.length)
  19393. return;
  19394. if (!this.plane)
  19395. this.plane = polygons[0].plane.clone();
  19396. var front = [], back = [];
  19397. for (var i = 0; i < polygons.length; i++) {
  19398. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  19399. }
  19400. if (front.length) {
  19401. if (!this.front)
  19402. this.front = new Node();
  19403. this.front.build(front);
  19404. }
  19405. if (back.length) {
  19406. if (!this.back)
  19407. this.back = new Node();
  19408. this.back.build(back);
  19409. }
  19410. };
  19411. return Node;
  19412. })();
  19413. var CSG = (function () {
  19414. function CSG() {
  19415. this.polygons = new Array();
  19416. }
  19417. // Convert BABYLON.Mesh to BABYLON.CSG
  19418. CSG.FromMesh = function (mesh) {
  19419. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  19420. if (mesh instanceof BABYLON.Mesh) {
  19421. mesh.computeWorldMatrix(true);
  19422. var matrix = mesh.getWorldMatrix();
  19423. var meshPosition = mesh.position.clone();
  19424. var meshRotation = mesh.rotation.clone();
  19425. var meshScaling = mesh.scaling.clone();
  19426. }
  19427. else {
  19428. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  19429. }
  19430. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19431. var subMeshes = mesh.subMeshes;
  19432. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  19433. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  19434. vertices = [];
  19435. for (var j = 0; j < 3; j++) {
  19436. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  19437. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  19438. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  19439. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  19440. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  19441. vertex = new Vertex(position, normal, uv);
  19442. vertices.push(vertex);
  19443. }
  19444. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  19445. // To handle the case of degenerated triangle
  19446. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  19447. if (polygon.plane)
  19448. polygons.push(polygon);
  19449. }
  19450. }
  19451. var csg = CSG.FromPolygons(polygons);
  19452. csg.matrix = matrix;
  19453. csg.position = meshPosition;
  19454. csg.rotation = meshRotation;
  19455. csg.scaling = meshScaling;
  19456. currentCSGMeshId++;
  19457. return csg;
  19458. };
  19459. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  19460. CSG.FromPolygons = function (polygons) {
  19461. var csg = new BABYLON.CSG();
  19462. csg.polygons = polygons;
  19463. return csg;
  19464. };
  19465. CSG.prototype.clone = function () {
  19466. var csg = new BABYLON.CSG();
  19467. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  19468. csg.copyTransformAttributes(this);
  19469. return csg;
  19470. };
  19471. CSG.prototype.toPolygons = function () {
  19472. return this.polygons;
  19473. };
  19474. CSG.prototype.union = function (csg) {
  19475. var a = new Node(this.clone().polygons);
  19476. var b = new Node(csg.clone().polygons);
  19477. a.clipTo(b);
  19478. b.clipTo(a);
  19479. b.invert();
  19480. b.clipTo(a);
  19481. b.invert();
  19482. a.build(b.allPolygons());
  19483. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19484. };
  19485. CSG.prototype.unionInPlace = function (csg) {
  19486. var a = new Node(this.polygons);
  19487. var b = new Node(csg.polygons);
  19488. a.clipTo(b);
  19489. b.clipTo(a);
  19490. b.invert();
  19491. b.clipTo(a);
  19492. b.invert();
  19493. a.build(b.allPolygons());
  19494. this.polygons = a.allPolygons();
  19495. };
  19496. CSG.prototype.subtract = function (csg) {
  19497. var a = new Node(this.clone().polygons);
  19498. var b = new Node(csg.clone().polygons);
  19499. a.invert();
  19500. a.clipTo(b);
  19501. b.clipTo(a);
  19502. b.invert();
  19503. b.clipTo(a);
  19504. b.invert();
  19505. a.build(b.allPolygons());
  19506. a.invert();
  19507. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19508. };
  19509. CSG.prototype.subtractInPlace = function (csg) {
  19510. var a = new Node(this.polygons);
  19511. var b = new Node(csg.polygons);
  19512. a.invert();
  19513. a.clipTo(b);
  19514. b.clipTo(a);
  19515. b.invert();
  19516. b.clipTo(a);
  19517. b.invert();
  19518. a.build(b.allPolygons());
  19519. a.invert();
  19520. this.polygons = a.allPolygons();
  19521. };
  19522. CSG.prototype.intersect = function (csg) {
  19523. var a = new Node(this.clone().polygons);
  19524. var b = new Node(csg.clone().polygons);
  19525. a.invert();
  19526. b.clipTo(a);
  19527. b.invert();
  19528. a.clipTo(b);
  19529. b.clipTo(a);
  19530. a.build(b.allPolygons());
  19531. a.invert();
  19532. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19533. };
  19534. CSG.prototype.intersectInPlace = function (csg) {
  19535. var a = new Node(this.polygons);
  19536. var b = new Node(csg.polygons);
  19537. a.invert();
  19538. b.clipTo(a);
  19539. b.invert();
  19540. a.clipTo(b);
  19541. b.clipTo(a);
  19542. a.build(b.allPolygons());
  19543. a.invert();
  19544. this.polygons = a.allPolygons();
  19545. };
  19546. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  19547. // not modified.
  19548. CSG.prototype.inverse = function () {
  19549. var csg = this.clone();
  19550. csg.inverseInPlace();
  19551. return csg;
  19552. };
  19553. CSG.prototype.inverseInPlace = function () {
  19554. this.polygons.map(function (p) {
  19555. p.flip();
  19556. });
  19557. };
  19558. // This is used to keep meshes transformations so they can be restored
  19559. // when we build back a Babylon Mesh
  19560. // NB : All CSG operations are performed in world coordinates
  19561. CSG.prototype.copyTransformAttributes = function (csg) {
  19562. this.matrix = csg.matrix;
  19563. this.position = csg.position;
  19564. this.rotation = csg.rotation;
  19565. this.scaling = csg.scaling;
  19566. return this;
  19567. };
  19568. // Build Raw mesh from CSG
  19569. // Coordinates here are in world space
  19570. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  19571. var matrix = this.matrix.clone();
  19572. matrix.invert();
  19573. var mesh = new BABYLON.Mesh(name, scene), vertices = [], indices = [], normals = [], uvs = [], vertex = BABYLON.Vector3.Zero(), normal = BABYLON.Vector3.Zero(), uv = BABYLON.Vector2.Zero(), polygons = this.polygons, polygonIndices = [0, 0, 0], polygon, vertice_dict = {}, vertex_idx, currentIndex = 0, subMesh_dict = {}, subMesh_obj;
  19574. if (keepSubMeshes) {
  19575. // Sort Polygons, since subMeshes are indices range
  19576. polygons.sort(function (a, b) {
  19577. if (a.shared.meshId === b.shared.meshId) {
  19578. return a.shared.subMeshId - b.shared.subMeshId;
  19579. }
  19580. else {
  19581. return a.shared.meshId - b.shared.meshId;
  19582. }
  19583. });
  19584. }
  19585. for (var i = 0, il = polygons.length; i < il; i++) {
  19586. polygon = polygons[i];
  19587. // Building SubMeshes
  19588. if (!subMesh_dict[polygon.shared.meshId]) {
  19589. subMesh_dict[polygon.shared.meshId] = {};
  19590. }
  19591. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  19592. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  19593. indexStart: +Infinity,
  19594. indexEnd: -Infinity,
  19595. materialIndex: polygon.shared.materialIndex
  19596. };
  19597. }
  19598. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  19599. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  19600. polygonIndices[0] = 0;
  19601. polygonIndices[1] = j - 1;
  19602. polygonIndices[2] = j;
  19603. for (var k = 0; k < 3; k++) {
  19604. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  19605. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  19606. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  19607. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  19608. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  19609. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  19610. // Check if 2 points can be merged
  19611. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === localNormal.x && normals[vertex_idx * 3 + 1] === localNormal.y && normals[vertex_idx * 3 + 2] === localNormal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  19612. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  19613. uvs.push(uv.x, uv.y);
  19614. normals.push(normal.x, normal.y, normal.z);
  19615. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  19616. }
  19617. indices.push(vertex_idx);
  19618. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  19619. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  19620. currentIndex++;
  19621. }
  19622. }
  19623. }
  19624. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  19625. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19626. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  19627. mesh.setIndices(indices);
  19628. if (keepSubMeshes) {
  19629. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  19630. var materialIndexOffset = 0, materialMaxIndex;
  19631. mesh.subMeshes.length = 0;
  19632. for (var m in subMesh_dict) {
  19633. materialMaxIndex = -1;
  19634. for (var sm in subMesh_dict[m]) {
  19635. subMesh_obj = subMesh_dict[m][sm];
  19636. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  19637. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  19638. }
  19639. materialIndexOffset += ++materialMaxIndex;
  19640. }
  19641. }
  19642. return mesh;
  19643. };
  19644. // Build Mesh from CSG taking material and transforms into account
  19645. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  19646. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  19647. mesh.material = material;
  19648. mesh.position.copyFrom(this.position);
  19649. mesh.rotation.copyFrom(this.rotation);
  19650. mesh.scaling.copyFrom(this.scaling);
  19651. mesh.computeWorldMatrix(true);
  19652. return mesh;
  19653. };
  19654. return CSG;
  19655. })();
  19656. BABYLON.CSG = CSG;
  19657. })(BABYLON || (BABYLON = {}));
  19658. //# sourceMappingURL=babylon.csg.js.map
  19659. var BABYLON;
  19660. (function (BABYLON) {
  19661. var OculusDistortionCorrectionPostProcess = (function (_super) {
  19662. __extends(OculusDistortionCorrectionPostProcess, _super);
  19663. //ANY
  19664. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  19665. var _this = this;
  19666. _super.call(this, name, "oculusDistortionCorrection", [
  19667. 'LensCenter',
  19668. 'Scale',
  19669. 'ScaleIn',
  19670. 'HmdWarpParam'
  19671. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  19672. this._isRightEye = isRightEye;
  19673. this._distortionFactors = cameraSettings.DistortionK;
  19674. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  19675. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  19676. this.onSizeChanged = function () {
  19677. _this.aspectRatio = _this.width * .5 / _this.height;
  19678. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  19679. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  19680. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  19681. };
  19682. this.onApply = function (effect) {
  19683. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  19684. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  19685. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  19686. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  19687. };
  19688. }
  19689. return OculusDistortionCorrectionPostProcess;
  19690. })(BABYLON.PostProcess);
  19691. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  19692. })(BABYLON || (BABYLON = {}));
  19693. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  19694. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  19695. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  19696. var BABYLON;
  19697. (function (BABYLON) {
  19698. (function (JoystickAxis) {
  19699. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  19700. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  19701. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  19702. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  19703. var JoystickAxis = BABYLON.JoystickAxis;
  19704. var VirtualJoystick = (function () {
  19705. function VirtualJoystick(leftJoystick) {
  19706. var _this = this;
  19707. if (leftJoystick) {
  19708. this._leftJoystick = true;
  19709. }
  19710. else {
  19711. this._leftJoystick = false;
  19712. }
  19713. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  19714. VirtualJoystick._globalJoystickIndex++;
  19715. // By default left & right arrow keys are moving the X
  19716. // and up & down keys are moving the Y
  19717. this._axisTargetedByLeftAndRight = 0 /* X */;
  19718. this._axisTargetedByUpAndDown = 1 /* Y */;
  19719. this.reverseLeftRight = false;
  19720. this.reverseUpDown = false;
  19721. // collections of pointers
  19722. this._touches = new BABYLON.VirtualJoystick.Collection();
  19723. this.deltaPosition = BABYLON.Vector3.Zero();
  19724. this._joystickSensibility = 25;
  19725. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19726. this._rotationSpeed = 25;
  19727. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  19728. this._rotateOnAxisRelativeToMesh = false;
  19729. // injecting a canvas element on top of the canvas 3D game
  19730. if (!VirtualJoystick.vjCanvas) {
  19731. window.addEventListener("resize", function () {
  19732. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19733. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19734. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  19735. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  19736. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  19737. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  19738. }, false);
  19739. VirtualJoystick.vjCanvas = document.createElement("canvas");
  19740. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19741. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19742. VirtualJoystick.vjCanvas.width = window.innerWidth;
  19743. VirtualJoystick.vjCanvas.height = window.innerHeight;
  19744. VirtualJoystick.vjCanvas.style.width = "100%";
  19745. VirtualJoystick.vjCanvas.style.height = "100%";
  19746. VirtualJoystick.vjCanvas.style.position = "absolute";
  19747. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  19748. VirtualJoystick.vjCanvas.style.top = "0px";
  19749. VirtualJoystick.vjCanvas.style.left = "0px";
  19750. VirtualJoystick.vjCanvas.style.zIndex = "5";
  19751. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  19752. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  19753. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  19754. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19755. document.body.appendChild(VirtualJoystick.vjCanvas);
  19756. }
  19757. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  19758. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  19759. this.pressed = false;
  19760. // default joystick color
  19761. this._joystickColor = "cyan";
  19762. this._joystickPointerID = -1;
  19763. // current joystick position
  19764. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  19765. // origin joystick position
  19766. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  19767. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  19768. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  19769. _this._onPointerDown(evt);
  19770. }, false);
  19771. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  19772. _this._onPointerMove(evt);
  19773. }, false);
  19774. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  19775. _this._onPointerUp(evt);
  19776. }, false);
  19777. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  19778. _this._onPointerUp(evt);
  19779. }, false);
  19780. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  19781. evt.preventDefault(); // Disables system menu
  19782. }, false);
  19783. requestAnimationFrame(function () {
  19784. _this._drawVirtualJoystick();
  19785. });
  19786. }
  19787. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  19788. this._joystickSensibility = newJoystickSensibility;
  19789. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19790. };
  19791. VirtualJoystick.prototype._onPointerDown = function (e) {
  19792. var positionOnScreenCondition;
  19793. e.preventDefault();
  19794. if (this._leftJoystick === true) {
  19795. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  19796. }
  19797. else {
  19798. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  19799. }
  19800. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  19801. // First contact will be dedicated to the virtual joystick
  19802. this._joystickPointerID = e.pointerId;
  19803. this._joystickPointerStartPos.x = e.clientX;
  19804. this._joystickPointerStartPos.y = e.clientY;
  19805. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  19806. this._deltaJoystickVector.x = 0;
  19807. this._deltaJoystickVector.y = 0;
  19808. this.pressed = true;
  19809. this._touches.add(e.pointerId.toString(), e);
  19810. }
  19811. else {
  19812. // You can only trigger the action buttons with a joystick declared
  19813. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  19814. this._action();
  19815. this._touches.add(e.pointerId.toString(), e);
  19816. }
  19817. }
  19818. };
  19819. VirtualJoystick.prototype._onPointerMove = function (e) {
  19820. // If the current pointer is the one associated to the joystick (first touch contact)
  19821. if (this._joystickPointerID == e.pointerId) {
  19822. this._joystickPointerPos.x = e.clientX;
  19823. this._joystickPointerPos.y = e.clientY;
  19824. this._deltaJoystickVector = this._joystickPointerPos.clone();
  19825. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  19826. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  19827. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  19828. switch (this._axisTargetedByLeftAndRight) {
  19829. case 0 /* X */:
  19830. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  19831. break;
  19832. case 1 /* Y */:
  19833. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  19834. break;
  19835. case 2 /* Z */:
  19836. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  19837. break;
  19838. }
  19839. var directionUpDown = this.reverseUpDown ? 1 : -1;
  19840. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  19841. switch (this._axisTargetedByUpAndDown) {
  19842. case 0 /* X */:
  19843. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  19844. break;
  19845. case 1 /* Y */:
  19846. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  19847. break;
  19848. case 2 /* Z */:
  19849. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  19850. break;
  19851. }
  19852. }
  19853. else {
  19854. if (this._touches.item(e.pointerId.toString())) {
  19855. this._touches.item(e.pointerId.toString()).x = e.clientX;
  19856. this._touches.item(e.pointerId.toString()).y = e.clientY;
  19857. }
  19858. }
  19859. };
  19860. VirtualJoystick.prototype._onPointerUp = function (e) {
  19861. this._clearCanvas();
  19862. if (this._joystickPointerID == e.pointerId) {
  19863. this._joystickPointerID = -1;
  19864. this.pressed = false;
  19865. }
  19866. this._deltaJoystickVector.x = 0;
  19867. this._deltaJoystickVector.y = 0;
  19868. this._touches.remove(e.pointerId.toString());
  19869. };
  19870. /**
  19871. * Change the color of the virtual joystick
  19872. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  19873. */
  19874. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  19875. this._joystickColor = newColor;
  19876. };
  19877. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  19878. this._action = action;
  19879. };
  19880. // Define which axis you'd like to control for left & right
  19881. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  19882. switch (axis) {
  19883. case 0 /* X */:
  19884. case 1 /* Y */:
  19885. case 2 /* Z */:
  19886. this._axisTargetedByLeftAndRight = axis;
  19887. break;
  19888. default:
  19889. this._axisTargetedByLeftAndRight = 0 /* X */;
  19890. break;
  19891. }
  19892. };
  19893. // Define which axis you'd like to control for up & down
  19894. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  19895. switch (axis) {
  19896. case 0 /* X */:
  19897. case 1 /* Y */:
  19898. case 2 /* Z */:
  19899. this._axisTargetedByUpAndDown = axis;
  19900. break;
  19901. default:
  19902. this._axisTargetedByUpAndDown = 1 /* Y */;
  19903. break;
  19904. }
  19905. };
  19906. VirtualJoystick.prototype._clearCanvas = function () {
  19907. if (this._leftJoystick) {
  19908. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  19909. }
  19910. else {
  19911. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  19912. }
  19913. };
  19914. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  19915. var _this = this;
  19916. if (this.pressed) {
  19917. this._clearCanvas();
  19918. this._touches.forEach(function (touch) {
  19919. if (touch.pointerId === _this._joystickPointerID) {
  19920. VirtualJoystick.vjCanvasContext.beginPath();
  19921. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19922. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19923. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  19924. VirtualJoystick.vjCanvasContext.stroke();
  19925. VirtualJoystick.vjCanvasContext.beginPath();
  19926. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19927. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19928. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  19929. VirtualJoystick.vjCanvasContext.stroke();
  19930. VirtualJoystick.vjCanvasContext.beginPath();
  19931. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19932. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  19933. VirtualJoystick.vjCanvasContext.stroke();
  19934. }
  19935. else {
  19936. VirtualJoystick.vjCanvasContext.beginPath();
  19937. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  19938. VirtualJoystick.vjCanvasContext.beginPath();
  19939. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  19940. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19941. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  19942. VirtualJoystick.vjCanvasContext.stroke();
  19943. }
  19944. ;
  19945. });
  19946. }
  19947. requestAnimationFrame(function () {
  19948. _this._drawVirtualJoystick();
  19949. });
  19950. };
  19951. VirtualJoystick.prototype.releaseCanvas = function () {
  19952. if (VirtualJoystick.vjCanvas) {
  19953. document.body.removeChild(VirtualJoystick.vjCanvas);
  19954. VirtualJoystick.vjCanvas = null;
  19955. }
  19956. };
  19957. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  19958. VirtualJoystick._globalJoystickIndex = 0;
  19959. return VirtualJoystick;
  19960. })();
  19961. BABYLON.VirtualJoystick = VirtualJoystick;
  19962. })(BABYLON || (BABYLON = {}));
  19963. var BABYLON;
  19964. (function (BABYLON) {
  19965. var VirtualJoystick;
  19966. (function (VirtualJoystick) {
  19967. var Collection = (function () {
  19968. function Collection() {
  19969. this._count = 0;
  19970. this._collection = new Array();
  19971. }
  19972. Collection.prototype.Count = function () {
  19973. return this._count;
  19974. };
  19975. Collection.prototype.add = function (key, item) {
  19976. if (this._collection[key] != undefined) {
  19977. return undefined;
  19978. }
  19979. this._collection[key] = item;
  19980. return ++this._count;
  19981. };
  19982. Collection.prototype.remove = function (key) {
  19983. if (this._collection[key] == undefined) {
  19984. return undefined;
  19985. }
  19986. delete this._collection[key];
  19987. return --this._count;
  19988. };
  19989. Collection.prototype.item = function (key) {
  19990. return this._collection[key];
  19991. };
  19992. Collection.prototype.forEach = function (block) {
  19993. var key;
  19994. for (key in this._collection) {
  19995. if (this._collection.hasOwnProperty(key)) {
  19996. block(this._collection[key]);
  19997. }
  19998. }
  19999. };
  20000. return Collection;
  20001. })();
  20002. VirtualJoystick.Collection = Collection;
  20003. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20004. })(BABYLON || (BABYLON = {}));
  20005. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20006. var BABYLON;
  20007. (function (BABYLON) {
  20008. var OculusRiftDevKit2013_Metric = {
  20009. HResolution: 1280,
  20010. VResolution: 800,
  20011. HScreenSize: 0.149759993,
  20012. VScreenSize: 0.0935999975,
  20013. VScreenCenter: 0.0467999987,
  20014. EyeToScreenDistance: 0.0410000011,
  20015. LensSeparationDistance: 0.0635000020,
  20016. InterpupillaryDistance: 0.0640000030,
  20017. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20018. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20019. PostProcessScaleFactor: 1.714605507808412,
  20020. LensCenterOffset: 0.151976421
  20021. };
  20022. var _OculusInnerCamera = (function (_super) {
  20023. __extends(_OculusInnerCamera, _super);
  20024. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20025. _super.call(this, name, position, scene);
  20026. this._workMatrix = new BABYLON.Matrix();
  20027. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20028. // Constants
  20029. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20030. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20031. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20032. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20033. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20034. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20035. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20036. // Postprocess
  20037. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20038. }
  20039. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  20040. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20041. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20042. return this._projectionMatrix;
  20043. };
  20044. _OculusInnerCamera.prototype._getViewMatrix = function () {
  20045. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20046. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20047. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20048. // Computing target and final matrix
  20049. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20050. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20051. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20052. return this._viewMatrix;
  20053. };
  20054. return _OculusInnerCamera;
  20055. })(BABYLON.FreeCamera);
  20056. var OculusCamera = (function (_super) {
  20057. __extends(OculusCamera, _super);
  20058. function OculusCamera(name, position, scene) {
  20059. _super.call(this, name, position, scene);
  20060. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  20061. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  20062. this.subCameras.push(this._leftCamera);
  20063. this.subCameras.push(this._rightCamera);
  20064. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20065. }
  20066. OculusCamera.prototype._update = function () {
  20067. this._leftCamera.position.copyFrom(this.position);
  20068. this._rightCamera.position.copyFrom(this.position);
  20069. this._updateCamera(this._leftCamera);
  20070. this._updateCamera(this._rightCamera);
  20071. _super.prototype._update.call(this);
  20072. };
  20073. OculusCamera.prototype._updateCamera = function (camera) {
  20074. camera.minZ = this.minZ;
  20075. camera.maxZ = this.maxZ;
  20076. camera.rotation.x = this.rotation.x;
  20077. camera.rotation.y = this.rotation.y;
  20078. camera.rotation.z = this.rotation.z;
  20079. };
  20080. // Oculus events
  20081. OculusCamera.prototype._onOrientationEvent = function (evt) {
  20082. var yaw = evt.alpha / 180 * Math.PI;
  20083. var pitch = evt.beta / 180 * Math.PI;
  20084. var roll = evt.gamma / 180 * Math.PI;
  20085. if (!this._offsetOrientation) {
  20086. this._offsetOrientation = {
  20087. yaw: yaw,
  20088. pitch: pitch,
  20089. roll: roll
  20090. };
  20091. return;
  20092. }
  20093. else {
  20094. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20095. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20096. this.rotation.z += this._offsetOrientation.roll - roll;
  20097. this._offsetOrientation.yaw = yaw;
  20098. this._offsetOrientation.pitch = pitch;
  20099. this._offsetOrientation.roll = roll;
  20100. }
  20101. };
  20102. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  20103. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20104. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20105. };
  20106. OculusCamera.prototype.detachControl = function (element) {
  20107. _super.prototype.detachControl.call(this, element);
  20108. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20109. };
  20110. return OculusCamera;
  20111. })(BABYLON.FreeCamera);
  20112. BABYLON.OculusCamera = OculusCamera;
  20113. })(BABYLON || (BABYLON = {}));
  20114. //# sourceMappingURL=babylon.oculusCamera.js.map
  20115. var BABYLON;
  20116. (function (BABYLON) {
  20117. var OculusRiftDevKit2013_Metric = {
  20118. HResolution: 1280,
  20119. VResolution: 800,
  20120. HScreenSize: 0.149759993,
  20121. VScreenSize: 0.0935999975,
  20122. VScreenCenter: 0.0467999987,
  20123. EyeToScreenDistance: 0.0410000011,
  20124. LensSeparationDistance: 0.0635000020,
  20125. InterpupillaryDistance: 0.0640000030,
  20126. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20127. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20128. PostProcessScaleFactor: 1.714605507808412,
  20129. LensCenterOffset: 0.151976421
  20130. };
  20131. var _OculusInnerGamepadCamera = (function (_super) {
  20132. __extends(_OculusInnerGamepadCamera, _super);
  20133. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  20134. _super.call(this, name, position, scene);
  20135. this._workMatrix = new BABYLON.Matrix();
  20136. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20137. // Constants
  20138. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20139. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20140. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20141. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20142. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20143. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20144. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20145. // Postprocess
  20146. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20147. }
  20148. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  20149. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20150. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20151. return this._projectionMatrix;
  20152. };
  20153. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  20154. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20155. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20156. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20157. // Computing target and final matrix
  20158. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20159. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20160. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20161. return this._viewMatrix;
  20162. };
  20163. return _OculusInnerGamepadCamera;
  20164. })(BABYLON.FreeCamera);
  20165. var OculusGamepadCamera = (function (_super) {
  20166. __extends(OculusGamepadCamera, _super);
  20167. function OculusGamepadCamera(name, position, scene) {
  20168. var _this = this;
  20169. _super.call(this, name, position, scene);
  20170. this.angularSensibility = 200;
  20171. this.moveSensibility = 75;
  20172. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  20173. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  20174. this.subCameras.push(this._leftCamera);
  20175. this.subCameras.push(this._rightCamera);
  20176. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20177. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20178. _this._onNewGameConnected(gamepad);
  20179. });
  20180. }
  20181. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20182. // Only the first gamepad can control the camera
  20183. if (gamepad.index === 0) {
  20184. this._gamepad = gamepad;
  20185. }
  20186. };
  20187. OculusGamepadCamera.prototype._update = function () {
  20188. this._leftCamera.position.copyFrom(this.position);
  20189. this._rightCamera.position.copyFrom(this.position);
  20190. this._updateCamera(this._leftCamera);
  20191. this._updateCamera(this._rightCamera);
  20192. _super.prototype._update.call(this);
  20193. };
  20194. OculusGamepadCamera.prototype._checkInputs = function () {
  20195. if (!this._gamepad) {
  20196. return;
  20197. }
  20198. var LSValues = this._gamepad.leftStick;
  20199. var normalizedLX = LSValues.x / this.moveSensibility;
  20200. var normalizedLY = LSValues.y / this.moveSensibility;
  20201. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20202. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20203. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20204. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20205. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20206. };
  20207. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  20208. camera.minZ = this.minZ;
  20209. camera.maxZ = this.maxZ;
  20210. camera.rotation.x = this.rotation.x;
  20211. camera.rotation.y = this.rotation.y;
  20212. camera.rotation.z = this.rotation.z;
  20213. };
  20214. // Oculus events
  20215. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  20216. var yaw = evt.alpha / 180 * Math.PI;
  20217. var pitch = evt.beta / 180 * Math.PI;
  20218. var roll = evt.gamma / 180 * Math.PI;
  20219. if (!this._offsetOrientation) {
  20220. this._offsetOrientation = {
  20221. yaw: yaw,
  20222. pitch: pitch,
  20223. roll: roll
  20224. };
  20225. return;
  20226. }
  20227. else {
  20228. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20229. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20230. this.rotation.z += this._offsetOrientation.roll - roll;
  20231. this._offsetOrientation.yaw = yaw;
  20232. this._offsetOrientation.pitch = pitch;
  20233. this._offsetOrientation.roll = roll;
  20234. }
  20235. };
  20236. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  20237. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20238. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20239. };
  20240. OculusGamepadCamera.prototype.detachControl = function (element) {
  20241. _super.prototype.detachControl.call(this, element);
  20242. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20243. };
  20244. OculusGamepadCamera.prototype.dispose = function () {
  20245. this._gamepads.dispose();
  20246. _super.prototype.dispose.call(this);
  20247. };
  20248. return OculusGamepadCamera;
  20249. })(BABYLON.FreeCamera);
  20250. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  20251. })(BABYLON || (BABYLON = {}));
  20252. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  20253. var BABYLON;
  20254. (function (BABYLON) {
  20255. // We're mainly based on the logic defined into the FreeCamera code
  20256. var VirtualJoysticksCamera = (function (_super) {
  20257. __extends(VirtualJoysticksCamera, _super);
  20258. function VirtualJoysticksCamera(name, position, scene) {
  20259. _super.call(this, name, position, scene);
  20260. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  20261. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  20262. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  20263. this._leftjoystick.setJoystickSensibility(0.15);
  20264. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  20265. this._rightjoystick.setAxisForUpDown(0 /* X */);
  20266. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  20267. this._rightjoystick.reverseUpDown = true;
  20268. this._rightjoystick.setJoystickSensibility(0.05);
  20269. this._rightjoystick.setJoystickColor("yellow");
  20270. }
  20271. VirtualJoysticksCamera.prototype._checkInputs = function () {
  20272. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20273. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  20274. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20275. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  20276. if (!this._leftjoystick.pressed) {
  20277. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  20278. }
  20279. if (!this._rightjoystick.pressed) {
  20280. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  20281. }
  20282. };
  20283. VirtualJoysticksCamera.prototype.dispose = function () {
  20284. this._leftjoystick.releaseCanvas();
  20285. _super.prototype.dispose.call(this);
  20286. };
  20287. return VirtualJoysticksCamera;
  20288. })(BABYLON.FreeCamera);
  20289. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  20290. })(BABYLON || (BABYLON = {}));
  20291. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  20292. var BABYLON;
  20293. (function (BABYLON) {
  20294. var ShaderMaterial = (function (_super) {
  20295. __extends(ShaderMaterial, _super);
  20296. function ShaderMaterial(name, scene, shaderPath, options) {
  20297. _super.call(this, name, scene);
  20298. this._textures = new Array();
  20299. this._floats = new Array();
  20300. this._floatsArrays = {};
  20301. this._colors3 = new Array();
  20302. this._colors4 = new Array();
  20303. this._vectors2 = new Array();
  20304. this._vectors3 = new Array();
  20305. this._matrices = new Array();
  20306. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  20307. this._shaderPath = shaderPath;
  20308. options.needAlphaBlending = options.needAlphaBlending || false;
  20309. options.needAlphaTesting = options.needAlphaTesting || false;
  20310. options.attributes = options.attributes || ["position", "normal", "uv"];
  20311. options.uniforms = options.uniforms || ["worldViewProjection"];
  20312. options.samplers = options.samplers || [];
  20313. this._options = options;
  20314. }
  20315. ShaderMaterial.prototype.needAlphaBlending = function () {
  20316. return this._options.needAlphaBlending;
  20317. };
  20318. ShaderMaterial.prototype.needAlphaTesting = function () {
  20319. return this._options.needAlphaTesting;
  20320. };
  20321. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  20322. if (this._options.uniforms.indexOf(uniformName) === -1) {
  20323. this._options.uniforms.push(uniformName);
  20324. }
  20325. };
  20326. ShaderMaterial.prototype.setTexture = function (name, texture) {
  20327. if (this._options.samplers.indexOf(name) === -1) {
  20328. this._options.samplers.push(name);
  20329. }
  20330. this._textures[name] = texture;
  20331. return this;
  20332. };
  20333. ShaderMaterial.prototype.setFloat = function (name, value) {
  20334. this._checkUniform(name);
  20335. this._floats[name] = value;
  20336. return this;
  20337. };
  20338. ShaderMaterial.prototype.setFloats = function (name, value) {
  20339. this._checkUniform(name);
  20340. this._floatsArrays[name] = value;
  20341. return this;
  20342. };
  20343. ShaderMaterial.prototype.setColor3 = function (name, value) {
  20344. this._checkUniform(name);
  20345. this._colors3[name] = value;
  20346. return this;
  20347. };
  20348. ShaderMaterial.prototype.setColor4 = function (name, value) {
  20349. this._checkUniform(name);
  20350. this._colors4[name] = value;
  20351. return this;
  20352. };
  20353. ShaderMaterial.prototype.setVector2 = function (name, value) {
  20354. this._checkUniform(name);
  20355. this._vectors2[name] = value;
  20356. return this;
  20357. };
  20358. ShaderMaterial.prototype.setVector3 = function (name, value) {
  20359. this._checkUniform(name);
  20360. this._vectors3[name] = value;
  20361. return this;
  20362. };
  20363. ShaderMaterial.prototype.setMatrix = function (name, value) {
  20364. this._checkUniform(name);
  20365. this._matrices[name] = value;
  20366. return this;
  20367. };
  20368. ShaderMaterial.prototype.isReady = function () {
  20369. var scene = this.getScene();
  20370. var engine = scene.getEngine();
  20371. if (!this.checkReadyOnEveryCall) {
  20372. if (this._renderId === scene.getRenderId()) {
  20373. return true;
  20374. }
  20375. }
  20376. var previousEffect = this._effect;
  20377. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  20378. if (!this._effect.isReady()) {
  20379. return false;
  20380. }
  20381. if (previousEffect !== this._effect) {
  20382. scene.resetCachedMaterial();
  20383. }
  20384. this._renderId = scene.getRenderId();
  20385. return true;
  20386. };
  20387. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20388. var scene = this.getScene();
  20389. if (this._options.uniforms.indexOf("world") !== -1) {
  20390. this._effect.setMatrix("world", world);
  20391. }
  20392. if (this._options.uniforms.indexOf("worldView") !== -1) {
  20393. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  20394. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  20395. }
  20396. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  20397. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  20398. }
  20399. };
  20400. ShaderMaterial.prototype.bind = function (world) {
  20401. // Std values
  20402. this.bindOnlyWorldMatrix(world);
  20403. if (this.getScene().getCachedMaterial() !== this) {
  20404. if (this._options.uniforms.indexOf("view") !== -1) {
  20405. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  20406. }
  20407. if (this._options.uniforms.indexOf("projection") !== -1) {
  20408. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  20409. }
  20410. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  20411. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  20412. }
  20413. for (var name in this._textures) {
  20414. this._effect.setTexture(name, this._textures[name]);
  20415. }
  20416. for (name in this._floats) {
  20417. this._effect.setFloat(name, this._floats[name]);
  20418. }
  20419. for (name in this._floatsArrays) {
  20420. this._effect.setArray(name, this._floatsArrays[name]);
  20421. }
  20422. for (name in this._colors3) {
  20423. this._effect.setColor3(name, this._colors3[name]);
  20424. }
  20425. for (name in this._colors4) {
  20426. var color = this._colors4[name];
  20427. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  20428. }
  20429. for (name in this._vectors2) {
  20430. this._effect.setVector2(name, this._vectors2[name]);
  20431. }
  20432. for (name in this._vectors3) {
  20433. this._effect.setVector3(name, this._vectors3[name]);
  20434. }
  20435. for (name in this._matrices) {
  20436. this._effect.setMatrix(name, this._matrices[name]);
  20437. }
  20438. }
  20439. _super.prototype.bind.call(this, world, null);
  20440. };
  20441. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  20442. for (var name in this._textures) {
  20443. this._textures[name].dispose();
  20444. }
  20445. this._textures = [];
  20446. _super.prototype.dispose.call(this, forceDisposeEffect);
  20447. };
  20448. return ShaderMaterial;
  20449. })(BABYLON.Material);
  20450. BABYLON.ShaderMaterial = ShaderMaterial;
  20451. })(BABYLON || (BABYLON = {}));
  20452. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  20453. (function (BABYLON) {
  20454. var VertexData = (function () {
  20455. function VertexData() {
  20456. }
  20457. VertexData.prototype.set = function (data, kind) {
  20458. switch (kind) {
  20459. case BABYLON.VertexBuffer.PositionKind:
  20460. this.positions = data;
  20461. break;
  20462. case BABYLON.VertexBuffer.NormalKind:
  20463. this.normals = data;
  20464. break;
  20465. case BABYLON.VertexBuffer.UVKind:
  20466. this.uvs = data;
  20467. break;
  20468. case BABYLON.VertexBuffer.UV2Kind:
  20469. this.uv2s = data;
  20470. break;
  20471. case BABYLON.VertexBuffer.ColorKind:
  20472. this.colors = data;
  20473. break;
  20474. case BABYLON.VertexBuffer.MatricesIndicesKind:
  20475. this.matricesIndices = data;
  20476. break;
  20477. case BABYLON.VertexBuffer.MatricesWeightsKind:
  20478. this.matricesWeights = data;
  20479. break;
  20480. }
  20481. };
  20482. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  20483. this._applyTo(mesh, updatable);
  20484. };
  20485. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  20486. this._applyTo(geometry, updatable);
  20487. };
  20488. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  20489. this._update(mesh);
  20490. };
  20491. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  20492. this._update(geometry);
  20493. };
  20494. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  20495. if (this.positions) {
  20496. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  20497. }
  20498. if (this.normals) {
  20499. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  20500. }
  20501. if (this.uvs) {
  20502. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  20503. }
  20504. if (this.uv2s) {
  20505. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  20506. }
  20507. if (this.colors) {
  20508. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  20509. }
  20510. if (this.matricesIndices) {
  20511. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  20512. }
  20513. if (this.matricesWeights) {
  20514. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  20515. }
  20516. if (this.indices) {
  20517. meshOrGeometry.setIndices(this.indices);
  20518. }
  20519. };
  20520. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  20521. if (this.positions) {
  20522. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  20523. }
  20524. if (this.normals) {
  20525. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  20526. }
  20527. if (this.uvs) {
  20528. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  20529. }
  20530. if (this.uv2s) {
  20531. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  20532. }
  20533. if (this.colors) {
  20534. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  20535. }
  20536. if (this.matricesIndices) {
  20537. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  20538. }
  20539. if (this.matricesWeights) {
  20540. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  20541. }
  20542. if (this.indices) {
  20543. meshOrGeometry.setIndices(this.indices);
  20544. }
  20545. };
  20546. VertexData.prototype.transform = function (matrix) {
  20547. var transformed = BABYLON.Vector3.Zero();
  20548. if (this.positions) {
  20549. var position = BABYLON.Vector3.Zero();
  20550. for (var index = 0; index < this.positions.length; index += 3) {
  20551. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  20552. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  20553. this.positions[index] = transformed.x;
  20554. this.positions[index + 1] = transformed.y;
  20555. this.positions[index + 2] = transformed.z;
  20556. }
  20557. }
  20558. if (this.normals) {
  20559. var normal = BABYLON.Vector3.Zero();
  20560. for (index = 0; index < this.normals.length; index += 3) {
  20561. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  20562. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  20563. this.normals[index] = transformed.x;
  20564. this.normals[index + 1] = transformed.y;
  20565. this.normals[index + 2] = transformed.z;
  20566. }
  20567. }
  20568. };
  20569. VertexData.prototype.merge = function (other) {
  20570. if (other.indices) {
  20571. if (!this.indices) {
  20572. this.indices = [];
  20573. }
  20574. var offset = this.positions ? this.positions.length / 3 : 0;
  20575. for (var index = 0; index < other.indices.length; index++) {
  20576. this.indices.push(other.indices[index] + offset);
  20577. }
  20578. }
  20579. if (other.positions) {
  20580. if (!this.positions) {
  20581. this.positions = [];
  20582. }
  20583. for (index = 0; index < other.positions.length; index++) {
  20584. this.positions.push(other.positions[index]);
  20585. }
  20586. }
  20587. if (other.normals) {
  20588. if (!this.normals) {
  20589. this.normals = [];
  20590. }
  20591. for (index = 0; index < other.normals.length; index++) {
  20592. this.normals.push(other.normals[index]);
  20593. }
  20594. }
  20595. if (other.uvs) {
  20596. if (!this.uvs) {
  20597. this.uvs = [];
  20598. }
  20599. for (index = 0; index < other.uvs.length; index++) {
  20600. this.uvs.push(other.uvs[index]);
  20601. }
  20602. }
  20603. if (other.uv2s) {
  20604. if (!this.uv2s) {
  20605. this.uv2s = [];
  20606. }
  20607. for (index = 0; index < other.uv2s.length; index++) {
  20608. this.uv2s.push(other.uv2s[index]);
  20609. }
  20610. }
  20611. if (other.matricesIndices) {
  20612. if (!this.matricesIndices) {
  20613. this.matricesIndices = [];
  20614. }
  20615. for (index = 0; index < other.matricesIndices.length; index++) {
  20616. this.matricesIndices.push(other.matricesIndices[index]);
  20617. }
  20618. }
  20619. if (other.matricesWeights) {
  20620. if (!this.matricesWeights) {
  20621. this.matricesWeights = [];
  20622. }
  20623. for (index = 0; index < other.matricesWeights.length; index++) {
  20624. this.matricesWeights.push(other.matricesWeights[index]);
  20625. }
  20626. }
  20627. if (other.colors) {
  20628. if (!this.colors) {
  20629. this.colors = [];
  20630. }
  20631. for (index = 0; index < other.colors.length; index++) {
  20632. this.colors.push(other.colors[index]);
  20633. }
  20634. }
  20635. };
  20636. // Statics
  20637. VertexData.ExtractFromMesh = function (mesh) {
  20638. return VertexData._ExtractFrom(mesh);
  20639. };
  20640. VertexData.ExtractFromGeometry = function (geometry) {
  20641. return VertexData._ExtractFrom(geometry);
  20642. };
  20643. VertexData._ExtractFrom = function (meshOrGeometry) {
  20644. var result = new BABYLON.VertexData();
  20645. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20646. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20647. }
  20648. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20649. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20650. }
  20651. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20652. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20653. }
  20654. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20655. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  20656. }
  20657. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20658. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  20659. }
  20660. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20661. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20662. }
  20663. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20664. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20665. }
  20666. result.indices = meshOrGeometry.getIndices();
  20667. return result;
  20668. };
  20669. VertexData.CreateBox = function (size) {
  20670. var normalsSource = [
  20671. new BABYLON.Vector3(0, 0, 1),
  20672. new BABYLON.Vector3(0, 0, -1),
  20673. new BABYLON.Vector3(1, 0, 0),
  20674. new BABYLON.Vector3(-1, 0, 0),
  20675. new BABYLON.Vector3(0, 1, 0),
  20676. new BABYLON.Vector3(0, -1, 0)
  20677. ];
  20678. var indices = [];
  20679. var positions = [];
  20680. var normals = [];
  20681. var uvs = [];
  20682. size = size || 1;
  20683. for (var index = 0; index < normalsSource.length; index++) {
  20684. var normal = normalsSource[index];
  20685. // Get two vectors perpendicular to the face normal and to each other.
  20686. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  20687. var side2 = BABYLON.Vector3.Cross(normal, side1);
  20688. // Six indices (two triangles) per face.
  20689. var verticesLength = positions.length / 3;
  20690. indices.push(verticesLength);
  20691. indices.push(verticesLength + 1);
  20692. indices.push(verticesLength + 2);
  20693. indices.push(verticesLength);
  20694. indices.push(verticesLength + 2);
  20695. indices.push(verticesLength + 3);
  20696. // Four vertices per face.
  20697. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  20698. positions.push(vertex.x, vertex.y, vertex.z);
  20699. normals.push(normal.x, normal.y, normal.z);
  20700. uvs.push(1.0, 1.0);
  20701. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  20702. positions.push(vertex.x, vertex.y, vertex.z);
  20703. normals.push(normal.x, normal.y, normal.z);
  20704. uvs.push(0.0, 1.0);
  20705. vertex = normal.add(side1).add(side2).scale(size / 2);
  20706. positions.push(vertex.x, vertex.y, vertex.z);
  20707. normals.push(normal.x, normal.y, normal.z);
  20708. uvs.push(0.0, 0.0);
  20709. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  20710. positions.push(vertex.x, vertex.y, vertex.z);
  20711. normals.push(normal.x, normal.y, normal.z);
  20712. uvs.push(1.0, 0.0);
  20713. }
  20714. // Result
  20715. var vertexData = new BABYLON.VertexData();
  20716. vertexData.indices = indices;
  20717. vertexData.positions = positions;
  20718. vertexData.normals = normals;
  20719. vertexData.uvs = uvs;
  20720. return vertexData;
  20721. };
  20722. VertexData.CreateSphere = function (segments, diameter) {
  20723. segments = segments || 32;
  20724. diameter = diameter || 1;
  20725. var radius = diameter / 2;
  20726. var totalZRotationSteps = 2 + segments;
  20727. var totalYRotationSteps = 2 * totalZRotationSteps;
  20728. var indices = [];
  20729. var positions = [];
  20730. var normals = [];
  20731. var uvs = [];
  20732. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  20733. var normalizedZ = zRotationStep / totalZRotationSteps;
  20734. var angleZ = (normalizedZ * Math.PI);
  20735. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  20736. var normalizedY = yRotationStep / totalYRotationSteps;
  20737. var angleY = normalizedY * Math.PI * 2;
  20738. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  20739. var rotationY = BABYLON.Matrix.RotationY(angleY);
  20740. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  20741. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  20742. var vertex = complete.scale(radius);
  20743. var normal = BABYLON.Vector3.Normalize(vertex);
  20744. positions.push(vertex.x, vertex.y, vertex.z);
  20745. normals.push(normal.x, normal.y, normal.z);
  20746. uvs.push(normalizedZ, normalizedY);
  20747. }
  20748. if (zRotationStep > 0) {
  20749. var verticesCount = positions.length / 3;
  20750. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  20751. indices.push((firstIndex));
  20752. indices.push((firstIndex + 1));
  20753. indices.push(firstIndex + totalYRotationSteps + 1);
  20754. indices.push((firstIndex + totalYRotationSteps + 1));
  20755. indices.push((firstIndex + 1));
  20756. indices.push((firstIndex + totalYRotationSteps + 2));
  20757. }
  20758. }
  20759. }
  20760. // Result
  20761. var vertexData = new BABYLON.VertexData();
  20762. vertexData.indices = indices;
  20763. vertexData.positions = positions;
  20764. vertexData.normals = normals;
  20765. vertexData.uvs = uvs;
  20766. return vertexData;
  20767. };
  20768. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  20769. if (subdivisions === void 0) { subdivisions = 1; }
  20770. var radiusTop = diameterTop / 2;
  20771. var radiusBottom = diameterBottom / 2;
  20772. var indices = [];
  20773. var positions = [];
  20774. var normals = [];
  20775. var uvs = [];
  20776. height = height || 1;
  20777. diameterTop = diameterTop || 0.5;
  20778. diameterBottom = diameterBottom || 1;
  20779. tessellation = tessellation || 16;
  20780. subdivisions = subdivisions || 1;
  20781. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  20782. var getCircleVector = function (i) {
  20783. var angle = (i * 2.0 * Math.PI / tessellation);
  20784. var dx = Math.cos(angle);
  20785. var dz = Math.sin(angle);
  20786. return new BABYLON.Vector3(dx, 0, dz);
  20787. };
  20788. var createCylinderCap = function (isTop) {
  20789. var radius = isTop ? radiusTop : radiusBottom;
  20790. if (radius == 0) {
  20791. return;
  20792. }
  20793. var vbase = positions.length / 3;
  20794. var offset = new BABYLON.Vector3(0, height / 2, 0);
  20795. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  20796. if (!isTop) {
  20797. offset.scaleInPlace(-1);
  20798. textureScale.x = -textureScale.x;
  20799. }
  20800. for (i = 0; i < tessellation; i++) {
  20801. var circleVector = getCircleVector(i);
  20802. var position = circleVector.scale(radius).add(offset);
  20803. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  20804. positions.push(position.x, position.y, position.z);
  20805. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20806. }
  20807. for (var i = 0; i < tessellation - 2; i++) {
  20808. if (!isTop) {
  20809. indices.push(vbase);
  20810. indices.push(vbase + (i + 2) % tessellation);
  20811. indices.push(vbase + (i + 1) % tessellation);
  20812. }
  20813. else {
  20814. indices.push(vbase);
  20815. indices.push(vbase + (i + 1) % tessellation);
  20816. indices.push(vbase + (i + 2) % tessellation);
  20817. }
  20818. }
  20819. };
  20820. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  20821. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  20822. var stride = tessellation + 1;
  20823. for (var i = 0; i <= tessellation; i++) {
  20824. var circleVector = getCircleVector(i);
  20825. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  20826. var position, radius = radiusBottom;
  20827. for (var s = 0; s <= subdivisions; s++) {
  20828. // Update variables
  20829. position = circleVector.scale(radius);
  20830. position.addInPlace(base.add(offset.scale(s)));
  20831. textureCoordinate.y += 1 / subdivisions;
  20832. radius += (radiusTop - radiusBottom) / subdivisions;
  20833. // Push in arrays
  20834. positions.push(position.x, position.y, position.z);
  20835. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20836. }
  20837. }
  20838. subdivisions += 1;
  20839. for (var s = 0; s < subdivisions - 1; s++) {
  20840. for (var i = 0; i <= tessellation; i++) {
  20841. indices.push(i * subdivisions + s);
  20842. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20843. indices.push(i * subdivisions + (s + 1));
  20844. indices.push(i * subdivisions + (s + 1));
  20845. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20846. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  20847. }
  20848. }
  20849. // Create flat triangle fan caps to seal the top and bottom.
  20850. createCylinderCap(true);
  20851. createCylinderCap(false);
  20852. // Normals
  20853. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20854. // Result
  20855. var vertexData = new BABYLON.VertexData();
  20856. vertexData.indices = indices;
  20857. vertexData.positions = positions;
  20858. vertexData.normals = normals;
  20859. vertexData.uvs = uvs;
  20860. return vertexData;
  20861. };
  20862. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  20863. var indices = [];
  20864. var positions = [];
  20865. var normals = [];
  20866. var uvs = [];
  20867. diameter = diameter || 1;
  20868. thickness = thickness || 0.5;
  20869. tessellation = tessellation || 16;
  20870. var stride = tessellation + 1;
  20871. for (var i = 0; i <= tessellation; i++) {
  20872. var u = i / tessellation;
  20873. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  20874. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  20875. for (var j = 0; j <= tessellation; j++) {
  20876. var v = 1 - j / tessellation;
  20877. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  20878. var dx = Math.cos(innerAngle);
  20879. var dy = Math.sin(innerAngle);
  20880. // Create a vertex.
  20881. var normal = new BABYLON.Vector3(dx, dy, 0);
  20882. var position = normal.scale(thickness / 2);
  20883. var textureCoordinate = new BABYLON.Vector2(u, v);
  20884. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  20885. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  20886. positions.push(position.x, position.y, position.z);
  20887. normals.push(normal.x, normal.y, normal.z);
  20888. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20889. // And create indices for two triangles.
  20890. var nextI = (i + 1) % stride;
  20891. var nextJ = (j + 1) % stride;
  20892. indices.push(i * stride + j);
  20893. indices.push(i * stride + nextJ);
  20894. indices.push(nextI * stride + j);
  20895. indices.push(i * stride + nextJ);
  20896. indices.push(nextI * stride + nextJ);
  20897. indices.push(nextI * stride + j);
  20898. }
  20899. }
  20900. // Result
  20901. var vertexData = new BABYLON.VertexData();
  20902. vertexData.indices = indices;
  20903. vertexData.positions = positions;
  20904. vertexData.normals = normals;
  20905. vertexData.uvs = uvs;
  20906. return vertexData;
  20907. };
  20908. VertexData.CreateLines = function (points) {
  20909. var indices = [];
  20910. var positions = [];
  20911. for (var index = 0; index < points.length; index++) {
  20912. positions.push(points[index].x, points[index].y, points[index].z);
  20913. if (index > 0) {
  20914. indices.push(index - 1);
  20915. indices.push(index);
  20916. }
  20917. }
  20918. // Result
  20919. var vertexData = new BABYLON.VertexData();
  20920. vertexData.indices = indices;
  20921. vertexData.positions = positions;
  20922. return vertexData;
  20923. };
  20924. VertexData.CreateGround = function (width, height, subdivisions) {
  20925. var indices = [];
  20926. var positions = [];
  20927. var normals = [];
  20928. var uvs = [];
  20929. var row, col;
  20930. width = width || 1;
  20931. height = height || 1;
  20932. subdivisions = subdivisions || 1;
  20933. for (row = 0; row <= subdivisions; row++) {
  20934. for (col = 0; col <= subdivisions; col++) {
  20935. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  20936. var normal = new BABYLON.Vector3(0, 1.0, 0);
  20937. positions.push(position.x, position.y, position.z);
  20938. normals.push(normal.x, normal.y, normal.z);
  20939. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20940. }
  20941. }
  20942. for (row = 0; row < subdivisions; row++) {
  20943. for (col = 0; col < subdivisions; col++) {
  20944. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20945. indices.push(col + 1 + row * (subdivisions + 1));
  20946. indices.push(col + row * (subdivisions + 1));
  20947. indices.push(col + (row + 1) * (subdivisions + 1));
  20948. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20949. indices.push(col + row * (subdivisions + 1));
  20950. }
  20951. }
  20952. // Result
  20953. var vertexData = new BABYLON.VertexData();
  20954. vertexData.indices = indices;
  20955. vertexData.positions = positions;
  20956. vertexData.normals = normals;
  20957. vertexData.uvs = uvs;
  20958. return vertexData;
  20959. };
  20960. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  20961. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  20962. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  20963. var indices = [];
  20964. var positions = [];
  20965. var normals = [];
  20966. var uvs = [];
  20967. var row, col, tileRow, tileCol;
  20968. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  20969. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  20970. precision.w = (precision.w < 1) ? 1 : precision.w;
  20971. precision.h = (precision.h < 1) ? 1 : precision.h;
  20972. var tileSize = {
  20973. 'w': (xmax - xmin) / subdivisions.w,
  20974. 'h': (zmax - zmin) / subdivisions.h
  20975. };
  20976. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  20977. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  20978. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  20979. }
  20980. }
  20981. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  20982. // Indices
  20983. var base = positions.length / 3;
  20984. var rowLength = precision.w + 1;
  20985. for (row = 0; row < precision.h; row++) {
  20986. for (col = 0; col < precision.w; col++) {
  20987. var square = [
  20988. base + col + row * rowLength,
  20989. base + (col + 1) + row * rowLength,
  20990. base + (col + 1) + (row + 1) * rowLength,
  20991. base + col + (row + 1) * rowLength
  20992. ];
  20993. indices.push(square[1]);
  20994. indices.push(square[2]);
  20995. indices.push(square[3]);
  20996. indices.push(square[0]);
  20997. indices.push(square[1]);
  20998. indices.push(square[3]);
  20999. }
  21000. }
  21001. // Position, normals and uvs
  21002. var position = BABYLON.Vector3.Zero();
  21003. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21004. for (row = 0; row <= precision.h; row++) {
  21005. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  21006. for (col = 0; col <= precision.w; col++) {
  21007. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  21008. position.y = 0;
  21009. positions.push(position.x, position.y, position.z);
  21010. normals.push(normal.x, normal.y, normal.z);
  21011. uvs.push(col / precision.w, row / precision.h);
  21012. }
  21013. }
  21014. }
  21015. // Result
  21016. var vertexData = new BABYLON.VertexData();
  21017. vertexData.indices = indices;
  21018. vertexData.positions = positions;
  21019. vertexData.normals = normals;
  21020. vertexData.uvs = uvs;
  21021. return vertexData;
  21022. };
  21023. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  21024. var indices = [];
  21025. var positions = [];
  21026. var normals = [];
  21027. var uvs = [];
  21028. var row, col;
  21029. for (row = 0; row <= subdivisions; row++) {
  21030. for (col = 0; col <= subdivisions; col++) {
  21031. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21032. // Compute height
  21033. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  21034. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  21035. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  21036. var r = buffer[pos] / 255.0;
  21037. var g = buffer[pos + 1] / 255.0;
  21038. var b = buffer[pos + 2] / 255.0;
  21039. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21040. position.y = minHeight + (maxHeight - minHeight) * gradient;
  21041. // Add vertex
  21042. positions.push(position.x, position.y, position.z);
  21043. normals.push(0, 0, 0);
  21044. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21045. }
  21046. }
  21047. for (row = 0; row < subdivisions; row++) {
  21048. for (col = 0; col < subdivisions; col++) {
  21049. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21050. indices.push(col + 1 + row * (subdivisions + 1));
  21051. indices.push(col + row * (subdivisions + 1));
  21052. indices.push(col + (row + 1) * (subdivisions + 1));
  21053. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21054. indices.push(col + row * (subdivisions + 1));
  21055. }
  21056. }
  21057. // Normals
  21058. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21059. // Result
  21060. var vertexData = new BABYLON.VertexData();
  21061. vertexData.indices = indices;
  21062. vertexData.positions = positions;
  21063. vertexData.normals = normals;
  21064. vertexData.uvs = uvs;
  21065. return vertexData;
  21066. };
  21067. VertexData.CreatePlane = function (size) {
  21068. var indices = [];
  21069. var positions = [];
  21070. var normals = [];
  21071. var uvs = [];
  21072. size = size || 1;
  21073. // Vertices
  21074. var halfSize = size / 2.0;
  21075. positions.push(-halfSize, -halfSize, 0);
  21076. normals.push(0, 0, -1.0);
  21077. uvs.push(0.0, 0.0);
  21078. positions.push(halfSize, -halfSize, 0);
  21079. normals.push(0, 0, -1.0);
  21080. uvs.push(1.0, 0.0);
  21081. positions.push(halfSize, halfSize, 0);
  21082. normals.push(0, 0, -1.0);
  21083. uvs.push(1.0, 1.0);
  21084. positions.push(-halfSize, halfSize, 0);
  21085. normals.push(0, 0, -1.0);
  21086. uvs.push(0.0, 1.0);
  21087. // Indices
  21088. indices.push(0);
  21089. indices.push(1);
  21090. indices.push(2);
  21091. indices.push(0);
  21092. indices.push(2);
  21093. indices.push(3);
  21094. // Result
  21095. var vertexData = new BABYLON.VertexData();
  21096. vertexData.indices = indices;
  21097. vertexData.positions = positions;
  21098. vertexData.normals = normals;
  21099. vertexData.uvs = uvs;
  21100. return vertexData;
  21101. };
  21102. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  21103. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  21104. var indices = [];
  21105. var positions = [];
  21106. var normals = [];
  21107. var uvs = [];
  21108. radius = radius || 2;
  21109. tube = tube || 0.5;
  21110. radialSegments = radialSegments || 32;
  21111. tubularSegments = tubularSegments || 32;
  21112. p = p || 2;
  21113. q = q || 3;
  21114. // Helper
  21115. var getPos = function (angle) {
  21116. var cu = Math.cos(angle);
  21117. var su = Math.sin(angle);
  21118. var quOverP = q / p * angle;
  21119. var cs = Math.cos(quOverP);
  21120. var tx = radius * (2 + cs) * 0.5 * cu;
  21121. var ty = radius * (2 + cs) * su * 0.5;
  21122. var tz = radius * Math.sin(quOverP) * 0.5;
  21123. return new BABYLON.Vector3(tx, ty, tz);
  21124. };
  21125. for (var i = 0; i <= radialSegments; i++) {
  21126. var modI = i % radialSegments;
  21127. var u = modI / radialSegments * 2 * p * Math.PI;
  21128. var p1 = getPos(u);
  21129. var p2 = getPos(u + 0.01);
  21130. var tang = p2.subtract(p1);
  21131. var n = p2.add(p1);
  21132. var bitan = BABYLON.Vector3.Cross(tang, n);
  21133. n = BABYLON.Vector3.Cross(bitan, tang);
  21134. bitan.normalize();
  21135. n.normalize();
  21136. for (var j = 0; j < tubularSegments; j++) {
  21137. var modJ = j % tubularSegments;
  21138. var v = modJ / tubularSegments * 2 * Math.PI;
  21139. var cx = -tube * Math.cos(v);
  21140. var cy = tube * Math.sin(v);
  21141. positions.push(p1.x + cx * n.x + cy * bitan.x);
  21142. positions.push(p1.y + cx * n.y + cy * bitan.y);
  21143. positions.push(p1.z + cx * n.z + cy * bitan.z);
  21144. uvs.push(i / radialSegments);
  21145. uvs.push(j / tubularSegments);
  21146. }
  21147. }
  21148. for (i = 0; i < radialSegments; i++) {
  21149. for (j = 0; j < tubularSegments; j++) {
  21150. var jNext = (j + 1) % tubularSegments;
  21151. var a = i * tubularSegments + j;
  21152. var b = (i + 1) * tubularSegments + j;
  21153. var c = (i + 1) * tubularSegments + jNext;
  21154. var d = i * tubularSegments + jNext;
  21155. indices.push(d);
  21156. indices.push(b);
  21157. indices.push(a);
  21158. indices.push(d);
  21159. indices.push(c);
  21160. indices.push(b);
  21161. }
  21162. }
  21163. // Normals
  21164. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21165. // Result
  21166. var vertexData = new BABYLON.VertexData();
  21167. vertexData.indices = indices;
  21168. vertexData.positions = positions;
  21169. vertexData.normals = normals;
  21170. vertexData.uvs = uvs;
  21171. return vertexData;
  21172. };
  21173. // Tools
  21174. VertexData.ComputeNormals = function (positions, indices, normals) {
  21175. var positionVectors = [];
  21176. var facesOfVertices = [];
  21177. var index;
  21178. for (index = 0; index < positions.length; index += 3) {
  21179. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  21180. positionVectors.push(vector3);
  21181. facesOfVertices.push([]);
  21182. }
  21183. // Compute normals
  21184. var facesNormals = [];
  21185. for (index = 0; index < indices.length / 3; index++) {
  21186. var i1 = indices[index * 3];
  21187. var i2 = indices[index * 3 + 1];
  21188. var i3 = indices[index * 3 + 2];
  21189. var p1 = positionVectors[i1];
  21190. var p2 = positionVectors[i2];
  21191. var p3 = positionVectors[i3];
  21192. var p1p2 = p1.subtract(p2);
  21193. var p3p2 = p3.subtract(p2);
  21194. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21195. facesOfVertices[i1].push(index);
  21196. facesOfVertices[i2].push(index);
  21197. facesOfVertices[i3].push(index);
  21198. }
  21199. for (index = 0; index < positionVectors.length; index++) {
  21200. var faces = facesOfVertices[index];
  21201. var normal = BABYLON.Vector3.Zero();
  21202. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  21203. normal.addInPlace(facesNormals[faces[faceIndex]]);
  21204. }
  21205. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  21206. normals[index * 3] = normal.x;
  21207. normals[index * 3 + 1] = normal.y;
  21208. normals[index * 3 + 2] = normal.z;
  21209. }
  21210. };
  21211. return VertexData;
  21212. })();
  21213. BABYLON.VertexData = VertexData;
  21214. })(BABYLON || (BABYLON = {}));
  21215. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  21216. var BABYLON;
  21217. (function (BABYLON) {
  21218. var buildCamera = function (that, name) {
  21219. that._leftCamera.isIntermediate = true;
  21220. that.subCameras.push(that._leftCamera);
  21221. that.subCameras.push(that._rightCamera);
  21222. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  21223. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  21224. that._anaglyphPostProcess.onApply = function (effect) {
  21225. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  21226. };
  21227. that._update();
  21228. };
  21229. var AnaglyphArcRotateCamera = (function (_super) {
  21230. __extends(AnaglyphArcRotateCamera, _super);
  21231. // ANY
  21232. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  21233. _super.call(this, name, alpha, beta, radius, target, scene);
  21234. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21235. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  21236. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  21237. buildCamera(this, name);
  21238. }
  21239. AnaglyphArcRotateCamera.prototype._update = function () {
  21240. this._updateCamera(this._leftCamera);
  21241. this._updateCamera(this._rightCamera);
  21242. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  21243. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  21244. _super.prototype._update.call(this);
  21245. };
  21246. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  21247. camera.beta = this.beta;
  21248. camera.radius = this.radius;
  21249. camera.minZ = this.minZ;
  21250. camera.maxZ = this.maxZ;
  21251. camera.fov = this.fov;
  21252. camera.target = this.target;
  21253. };
  21254. return AnaglyphArcRotateCamera;
  21255. })(BABYLON.ArcRotateCamera);
  21256. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  21257. var AnaglyphFreeCamera = (function (_super) {
  21258. __extends(AnaglyphFreeCamera, _super);
  21259. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  21260. _super.call(this, name, position, scene);
  21261. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21262. this._transformMatrix = new BABYLON.Matrix();
  21263. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  21264. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  21265. buildCamera(this, name);
  21266. }
  21267. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  21268. var target = this.getTarget();
  21269. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  21270. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  21271. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  21272. };
  21273. AnaglyphFreeCamera.prototype._update = function () {
  21274. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  21275. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  21276. this._updateCamera(this._leftCamera);
  21277. this._updateCamera(this._rightCamera);
  21278. _super.prototype._update.call(this);
  21279. };
  21280. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  21281. camera.minZ = this.minZ;
  21282. camera.maxZ = this.maxZ;
  21283. camera.fov = this.fov;
  21284. camera.viewport = this.viewport;
  21285. camera.setTarget(this.getTarget());
  21286. };
  21287. return AnaglyphFreeCamera;
  21288. })(BABYLON.FreeCamera);
  21289. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  21290. })(BABYLON || (BABYLON = {}));
  21291. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  21292. var BABYLON;
  21293. (function (BABYLON) {
  21294. var AnaglyphPostProcess = (function (_super) {
  21295. __extends(AnaglyphPostProcess, _super);
  21296. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21297. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  21298. }
  21299. return AnaglyphPostProcess;
  21300. })(BABYLON.PostProcess);
  21301. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  21302. })(BABYLON || (BABYLON = {}));
  21303. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  21304. (function (BABYLON) {
  21305. var Tags = (function () {
  21306. function Tags() {
  21307. }
  21308. Tags.EnableFor = function (obj) {
  21309. obj._tags = obj._tags || {};
  21310. obj.hasTags = function () {
  21311. return Tags.HasTags(obj);
  21312. };
  21313. obj.addTags = function (tagsString) {
  21314. return Tags.AddTagsTo(obj, tagsString);
  21315. };
  21316. obj.removeTags = function (tagsString) {
  21317. return Tags.RemoveTagsFrom(obj, tagsString);
  21318. };
  21319. obj.matchesTagsQuery = function (tagsQuery) {
  21320. return Tags.MatchesQuery(obj, tagsQuery);
  21321. };
  21322. };
  21323. Tags.DisableFor = function (obj) {
  21324. delete obj._tags;
  21325. delete obj.hasTags;
  21326. delete obj.addTags;
  21327. delete obj.removeTags;
  21328. delete obj.matchesTagsQuery;
  21329. };
  21330. Tags.HasTags = function (obj) {
  21331. if (!obj._tags) {
  21332. return false;
  21333. }
  21334. return !BABYLON.Tools.IsEmpty(obj._tags);
  21335. };
  21336. Tags.GetTags = function (obj) {
  21337. if (!obj._tags) {
  21338. return null;
  21339. }
  21340. return obj._tags;
  21341. };
  21342. // the tags 'true' and 'false' are reserved and cannot be used as tags
  21343. // a tag cannot start with '||', '&&', and '!'
  21344. // it cannot contain whitespaces
  21345. Tags.AddTagsTo = function (obj, tagsString) {
  21346. if (!tagsString) {
  21347. return;
  21348. }
  21349. var tags = tagsString.split(" ");
  21350. for (var t in tags) {
  21351. Tags._AddTagTo(obj, tags[t]);
  21352. }
  21353. };
  21354. Tags._AddTagTo = function (obj, tag) {
  21355. tag = tag.trim();
  21356. if (tag === "" || tag === "true" || tag === "false") {
  21357. return;
  21358. }
  21359. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  21360. return;
  21361. }
  21362. Tags.EnableFor(obj);
  21363. obj._tags[tag] = true;
  21364. };
  21365. Tags.RemoveTagsFrom = function (obj, tagsString) {
  21366. if (!Tags.HasTags(obj)) {
  21367. return;
  21368. }
  21369. var tags = tagsString.split(" ");
  21370. for (var t in tags) {
  21371. Tags._RemoveTagFrom(obj, tags[t]);
  21372. }
  21373. };
  21374. Tags._RemoveTagFrom = function (obj, tag) {
  21375. delete obj._tags[tag];
  21376. };
  21377. Tags.MatchesQuery = function (obj, tagsQuery) {
  21378. if (tagsQuery === undefined) {
  21379. return true;
  21380. }
  21381. if (tagsQuery === "") {
  21382. return Tags.HasTags(obj);
  21383. }
  21384. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  21385. };
  21386. return Tags;
  21387. })();
  21388. BABYLON.Tags = Tags;
  21389. })(BABYLON || (BABYLON = {}));
  21390. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  21391. (function (BABYLON) {
  21392. var Internals;
  21393. (function (Internals) {
  21394. var AndOrNotEvaluator = (function () {
  21395. function AndOrNotEvaluator() {
  21396. }
  21397. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  21398. if (!query.match(/\([^\(\)]*\)/g)) {
  21399. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  21400. }
  21401. else {
  21402. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  21403. // remove parenthesis
  21404. r = r.slice(1, r.length - 1);
  21405. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  21406. });
  21407. }
  21408. if (query === "true") {
  21409. return true;
  21410. }
  21411. if (query === "false") {
  21412. return false;
  21413. }
  21414. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  21415. };
  21416. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  21417. evaluateCallback = evaluateCallback || (function (r) {
  21418. return r === "true" ? true : false;
  21419. });
  21420. var result;
  21421. var or = parenthesisContent.split("||");
  21422. for (var i in or) {
  21423. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  21424. var and = ori.split("&&");
  21425. if (and.length > 1) {
  21426. for (var j = 0; j < and.length; ++j) {
  21427. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  21428. if (andj !== "true" && andj !== "false") {
  21429. if (andj[0] === "!") {
  21430. result = !evaluateCallback(andj.substring(1));
  21431. }
  21432. else {
  21433. result = evaluateCallback(andj);
  21434. }
  21435. }
  21436. else {
  21437. result = andj === "true" ? true : false;
  21438. }
  21439. if (!result) {
  21440. ori = "false";
  21441. break;
  21442. }
  21443. }
  21444. }
  21445. if (result || ori === "true") {
  21446. result = true;
  21447. break;
  21448. }
  21449. // result equals false (or undefined)
  21450. if (ori !== "true" && ori !== "false") {
  21451. if (ori[0] === "!") {
  21452. result = !evaluateCallback(ori.substring(1));
  21453. }
  21454. else {
  21455. result = evaluateCallback(ori);
  21456. }
  21457. }
  21458. else {
  21459. result = ori === "true" ? true : false;
  21460. }
  21461. }
  21462. // the whole parenthesis scope is replaced by 'true' or 'false'
  21463. return result ? "true" : "false";
  21464. };
  21465. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  21466. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  21467. // remove whitespaces
  21468. r = r.replace(/[\s]/g, function () { return ""; });
  21469. return r.length % 2 ? "!" : "";
  21470. });
  21471. booleanString = booleanString.trim();
  21472. if (booleanString === "!true") {
  21473. booleanString = "false";
  21474. }
  21475. else if (booleanString === "!false") {
  21476. booleanString = "true";
  21477. }
  21478. return booleanString;
  21479. };
  21480. return AndOrNotEvaluator;
  21481. })();
  21482. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  21483. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21484. })(BABYLON || (BABYLON = {}));
  21485. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  21486. (function (BABYLON) {
  21487. var PostProcessRenderPass = (function () {
  21488. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  21489. this._enabled = true;
  21490. this._refCount = 0;
  21491. this._name = name;
  21492. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  21493. this.setRenderList(renderList);
  21494. this._renderTexture.onBeforeRender = beforeRender;
  21495. this._renderTexture.onAfterRender = afterRender;
  21496. this._scene = scene;
  21497. this._renderList = renderList;
  21498. }
  21499. // private
  21500. PostProcessRenderPass.prototype._incRefCount = function () {
  21501. if (this._refCount === 0) {
  21502. this._scene.customRenderTargets.push(this._renderTexture);
  21503. }
  21504. return ++this._refCount;
  21505. };
  21506. PostProcessRenderPass.prototype._decRefCount = function () {
  21507. this._refCount--;
  21508. if (this._refCount <= 0) {
  21509. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  21510. }
  21511. return this._refCount;
  21512. };
  21513. PostProcessRenderPass.prototype._update = function () {
  21514. this.setRenderList(this._renderList);
  21515. };
  21516. // public
  21517. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  21518. this._renderTexture.renderList = renderList;
  21519. };
  21520. PostProcessRenderPass.prototype.getRenderTexture = function () {
  21521. return this._renderTexture;
  21522. };
  21523. return PostProcessRenderPass;
  21524. })();
  21525. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  21526. })(BABYLON || (BABYLON = {}));
  21527. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  21528. (function (BABYLON) {
  21529. var PostProcessRenderEffect = (function () {
  21530. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  21531. this._engine = engine;
  21532. this._name = name;
  21533. this._singleInstance = singleInstance || true;
  21534. this._getPostProcess = getPostProcess;
  21535. this._cameras = [];
  21536. this._indicesForCamera = [];
  21537. this._postProcesses = {};
  21538. this._renderPasses = {};
  21539. this._renderEffectAsPasses = {};
  21540. }
  21541. PostProcessRenderEffect.prototype._update = function () {
  21542. for (var renderPassName in this._renderPasses) {
  21543. this._renderPasses[renderPassName]._update();
  21544. }
  21545. };
  21546. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  21547. this._renderPasses[renderPass._name] = renderPass;
  21548. this._linkParameters();
  21549. };
  21550. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  21551. delete this._renderPasses[renderPass._name];
  21552. this._linkParameters();
  21553. };
  21554. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  21555. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  21556. this._linkParameters();
  21557. };
  21558. PostProcessRenderEffect.prototype.getPass = function (passName) {
  21559. for (var renderPassName in this._renderPasses) {
  21560. if (renderPassName === passName) {
  21561. return this._renderPasses[passName];
  21562. }
  21563. }
  21564. };
  21565. PostProcessRenderEffect.prototype.emptyPasses = function () {
  21566. this._renderPasses = {};
  21567. this._linkParameters();
  21568. };
  21569. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  21570. var cameraKey;
  21571. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21572. for (var i = 0; i < _cam.length; i++) {
  21573. var camera = _cam[i];
  21574. var cameraName = camera.name;
  21575. if (this._singleInstance) {
  21576. cameraKey = 0;
  21577. }
  21578. else {
  21579. cameraKey = cameraName;
  21580. }
  21581. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  21582. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  21583. if (!this._indicesForCamera[cameraName]) {
  21584. this._indicesForCamera[cameraName] = [];
  21585. }
  21586. this._indicesForCamera[cameraName].push(index);
  21587. if (this._cameras.indexOf(camera) === -1) {
  21588. this._cameras[cameraName] = camera;
  21589. }
  21590. for (var passName in this._renderPasses) {
  21591. this._renderPasses[passName]._incRefCount();
  21592. }
  21593. }
  21594. this._linkParameters();
  21595. };
  21596. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  21597. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21598. for (var i = 0; i < _cam.length; i++) {
  21599. var camera = _cam[i];
  21600. var cameraName = camera.name;
  21601. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21602. var index = this._cameras.indexOf(cameraName);
  21603. this._indicesForCamera.splice(index, 1);
  21604. this._cameras.splice(index, 1);
  21605. for (var passName in this._renderPasses) {
  21606. this._renderPasses[passName]._decRefCount();
  21607. }
  21608. }
  21609. };
  21610. PostProcessRenderEffect.prototype._enable = function (cameras) {
  21611. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21612. for (var i = 0; i < _cam.length; i++) {
  21613. var camera = _cam[i];
  21614. var cameraName = camera.name;
  21615. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  21616. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  21617. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  21618. }
  21619. }
  21620. for (var passName in this._renderPasses) {
  21621. this._renderPasses[passName]._incRefCount();
  21622. }
  21623. }
  21624. };
  21625. PostProcessRenderEffect.prototype._disable = function (cameras) {
  21626. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21627. for (var i = 0; i < _cam.length; i++) {
  21628. var camera = _cam[i];
  21629. var cameraName = camera.Name;
  21630. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21631. for (var passName in this._renderPasses) {
  21632. this._renderPasses[passName]._decRefCount();
  21633. }
  21634. }
  21635. };
  21636. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  21637. if (this._singleInstance) {
  21638. return this._postProcesses[0];
  21639. }
  21640. else {
  21641. return this._postProcesses[camera.name];
  21642. }
  21643. };
  21644. PostProcessRenderEffect.prototype._linkParameters = function () {
  21645. var _this = this;
  21646. for (var index in this._postProcesses) {
  21647. if (this.applyParameters) {
  21648. this.applyParameters(this._postProcesses[index]);
  21649. }
  21650. this._postProcesses[index].onBeforeRender = function (effect) {
  21651. _this._linkTextures(effect);
  21652. };
  21653. }
  21654. };
  21655. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  21656. for (var renderPassName in this._renderPasses) {
  21657. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  21658. }
  21659. for (var renderEffectName in this._renderEffectAsPasses) {
  21660. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  21661. }
  21662. };
  21663. return PostProcessRenderEffect;
  21664. })();
  21665. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  21666. })(BABYLON || (BABYLON = {}));
  21667. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  21668. (function (BABYLON) {
  21669. var PostProcessRenderPipeline = (function () {
  21670. function PostProcessRenderPipeline(engine, name) {
  21671. this._engine = engine;
  21672. this._name = name;
  21673. this._renderEffects = {};
  21674. this._renderEffectsForIsolatedPass = {};
  21675. this._cameras = [];
  21676. }
  21677. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  21678. this._renderEffects[renderEffect._name] = renderEffect;
  21679. };
  21680. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  21681. var renderEffects = this._renderEffects[renderEffectName];
  21682. if (!renderEffects) {
  21683. return;
  21684. }
  21685. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21686. };
  21687. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  21688. var renderEffects = this._renderEffects[renderEffectName];
  21689. if (!renderEffects) {
  21690. return;
  21691. }
  21692. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21693. };
  21694. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  21695. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21696. var indicesToDelete = [];
  21697. for (var i = 0; i < _cam.length; i++) {
  21698. var camera = _cam[i];
  21699. var cameraName = camera.name;
  21700. if (this._cameras.indexOf(camera) === -1) {
  21701. this._cameras[cameraName] = camera;
  21702. }
  21703. else if (unique) {
  21704. indicesToDelete.push(i);
  21705. }
  21706. }
  21707. for (var i = 0; i < indicesToDelete.length; i++) {
  21708. cameras.splice(indicesToDelete[i], 1);
  21709. }
  21710. for (var renderEffectName in this._renderEffects) {
  21711. this._renderEffects[renderEffectName]._attachCameras(_cam);
  21712. }
  21713. };
  21714. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  21715. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21716. for (var renderEffectName in this._renderEffects) {
  21717. this._renderEffects[renderEffectName]._detachCameras(_cam);
  21718. }
  21719. for (var i = 0; i < _cam.length; i++) {
  21720. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  21721. }
  21722. };
  21723. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  21724. var _this = this;
  21725. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21726. var pass = null;
  21727. for (var renderEffectName in this._renderEffects) {
  21728. pass = this._renderEffects[renderEffectName].getPass(passName);
  21729. if (pass != null) {
  21730. break;
  21731. }
  21732. }
  21733. if (pass === null) {
  21734. return;
  21735. }
  21736. for (var renderEffectName in this._renderEffects) {
  21737. this._renderEffects[renderEffectName]._disable(_cam);
  21738. }
  21739. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  21740. for (var i = 0; i < _cam.length; i++) {
  21741. var camera = _cam[i];
  21742. var cameraName = camera.name;
  21743. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21744. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21745. });
  21746. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  21747. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  21748. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  21749. }
  21750. };
  21751. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  21752. var _this = this;
  21753. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21754. for (var i = 0; i < _cam.length; i++) {
  21755. var camera = _cam[i];
  21756. var cameraName = camera.name;
  21757. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21758. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21759. });
  21760. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  21761. }
  21762. for (var renderEffectName in this._renderEffects) {
  21763. this._renderEffects[renderEffectName]._enable(_cam);
  21764. }
  21765. };
  21766. PostProcessRenderPipeline.prototype._update = function () {
  21767. for (var renderEffectName in this._renderEffects) {
  21768. this._renderEffects[renderEffectName]._update();
  21769. }
  21770. for (var i = 0; i < this._cameras.length; i++) {
  21771. var cameraName = this._cameras[i].name;
  21772. if (this._renderEffectsForIsolatedPass[cameraName]) {
  21773. this._renderEffectsForIsolatedPass[cameraName]._update();
  21774. }
  21775. }
  21776. };
  21777. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  21778. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  21779. return PostProcessRenderPipeline;
  21780. })();
  21781. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  21782. })(BABYLON || (BABYLON = {}));
  21783. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  21784. (function (BABYLON) {
  21785. var PostProcessRenderPipelineManager = (function () {
  21786. function PostProcessRenderPipelineManager() {
  21787. this._renderPipelines = {};
  21788. }
  21789. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  21790. this._renderPipelines[renderPipeline._name] = renderPipeline;
  21791. };
  21792. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  21793. var renderPipeline = this._renderPipelines[renderPipelineName];
  21794. if (!renderPipeline) {
  21795. return;
  21796. }
  21797. renderPipeline._attachCameras(cameras, unique);
  21798. };
  21799. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  21800. var renderPipeline = this._renderPipelines[renderPipelineName];
  21801. if (!renderPipeline) {
  21802. return;
  21803. }
  21804. renderPipeline._detachCameras(cameras);
  21805. };
  21806. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21807. var renderPipeline = this._renderPipelines[renderPipelineName];
  21808. if (!renderPipeline) {
  21809. return;
  21810. }
  21811. renderPipeline._enableEffect(renderEffectName, cameras);
  21812. };
  21813. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21814. var renderPipeline = this._renderPipelines[renderPipelineName];
  21815. if (!renderPipeline) {
  21816. return;
  21817. }
  21818. renderPipeline._disableEffect(renderEffectName, cameras);
  21819. };
  21820. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  21821. var renderPipeline = this._renderPipelines[renderPipelineName];
  21822. if (!renderPipeline) {
  21823. return;
  21824. }
  21825. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  21826. };
  21827. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  21828. var renderPipeline = this._renderPipelines[renderPipelineName];
  21829. if (!renderPipeline) {
  21830. return;
  21831. }
  21832. renderPipeline._disableDisplayOnlyPass(cameras);
  21833. };
  21834. PostProcessRenderPipelineManager.prototype.update = function () {
  21835. for (var renderPipelineName in this._renderPipelines) {
  21836. this._renderPipelines[renderPipelineName]._update();
  21837. }
  21838. };
  21839. return PostProcessRenderPipelineManager;
  21840. })();
  21841. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  21842. })(BABYLON || (BABYLON = {}));
  21843. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  21844. var BABYLON;
  21845. (function (BABYLON) {
  21846. var DisplayPassPostProcess = (function (_super) {
  21847. __extends(DisplayPassPostProcess, _super);
  21848. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21849. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  21850. }
  21851. return DisplayPassPostProcess;
  21852. })(BABYLON.PostProcess);
  21853. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  21854. })(BABYLON || (BABYLON = {}));
  21855. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  21856. (function (BABYLON) {
  21857. var BoundingBoxRenderer = (function () {
  21858. function BoundingBoxRenderer(scene) {
  21859. this.frontColor = new BABYLON.Color3(1, 1, 1);
  21860. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  21861. this.showBackLines = true;
  21862. this.renderList = new BABYLON.SmartArray(32);
  21863. this._scene = scene;
  21864. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  21865. attributes: ["position"],
  21866. uniforms: ["worldViewProjection", "color"]
  21867. });
  21868. var engine = this._scene.getEngine();
  21869. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  21870. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  21871. this._ib = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
  21872. }
  21873. BoundingBoxRenderer.prototype.reset = function () {
  21874. this.renderList.reset();
  21875. };
  21876. BoundingBoxRenderer.prototype.render = function () {
  21877. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  21878. return;
  21879. }
  21880. var engine = this._scene.getEngine();
  21881. engine.setDepthWrite(false);
  21882. this._colorShader._preBind();
  21883. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  21884. var boundingBox = this.renderList.data[boundingBoxIndex];
  21885. var min = boundingBox.minimum;
  21886. var max = boundingBox.maximum;
  21887. var diff = max.subtract(min);
  21888. var median = min.add(diff.scale(0.5));
  21889. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  21890. // VBOs
  21891. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  21892. if (this.showBackLines) {
  21893. // Back
  21894. engine.setDepthFunctionToGreaterOrEqual();
  21895. this._scene.resetCachedMaterial();
  21896. this._colorShader.setColor4("color", this.backColor.toColor4());
  21897. this._colorShader.bind(worldMatrix);
  21898. // Draw order
  21899. engine.draw(false, 0, 24);
  21900. }
  21901. // Front
  21902. engine.setDepthFunctionToLess();
  21903. this._scene.resetCachedMaterial();
  21904. this._colorShader.setColor4("color", this.frontColor.toColor4());
  21905. this._colorShader.bind(worldMatrix);
  21906. // Draw order
  21907. engine.draw(false, 0, 24);
  21908. }
  21909. this._colorShader.unbind();
  21910. engine.setDepthFunctionToLessOrEqual();
  21911. engine.setDepthWrite(true);
  21912. };
  21913. BoundingBoxRenderer.prototype.dispose = function () {
  21914. this._colorShader.dispose();
  21915. this._vb.dispose();
  21916. this._scene.getEngine()._releaseBuffer(this._ib);
  21917. };
  21918. return BoundingBoxRenderer;
  21919. })();
  21920. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  21921. })(BABYLON || (BABYLON = {}));
  21922. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  21923. (function (BABYLON) {
  21924. var Internals;
  21925. (function (Internals) {
  21926. /*
  21927. * Based on jsTGALoader - Javascript loader for TGA file
  21928. * By Vincent Thibault
  21929. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  21930. */
  21931. var TGATools = (function () {
  21932. function TGATools() {
  21933. }
  21934. TGATools.GetTGAHeader = function (data) {
  21935. var offset = 0;
  21936. var header = {
  21937. id_length: data[offset++],
  21938. colormap_type: data[offset++],
  21939. image_type: data[offset++],
  21940. colormap_index: data[offset++] | data[offset++] << 8,
  21941. colormap_length: data[offset++] | data[offset++] << 8,
  21942. colormap_size: data[offset++],
  21943. origin: [
  21944. data[offset++] | data[offset++] << 8,
  21945. data[offset++] | data[offset++] << 8
  21946. ],
  21947. width: data[offset++] | data[offset++] << 8,
  21948. height: data[offset++] | data[offset++] << 8,
  21949. pixel_size: data[offset++],
  21950. flags: data[offset++]
  21951. };
  21952. return header;
  21953. };
  21954. TGATools.UploadContent = function (gl, data) {
  21955. // Not enough data to contain header ?
  21956. if (data.length < 19) {
  21957. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  21958. return;
  21959. }
  21960. // Read Header
  21961. var offset = 18;
  21962. var header = TGATools.GetTGAHeader(data);
  21963. // Assume it's a valid Targa file.
  21964. if (header.id_length + offset > data.length) {
  21965. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  21966. return;
  21967. }
  21968. // Skip not needed data
  21969. offset += header.id_length;
  21970. var use_rle = false;
  21971. var use_pal = false;
  21972. var use_rgb = false;
  21973. var use_grey = false;
  21974. switch (header.image_type) {
  21975. case TGATools._TYPE_RLE_INDEXED:
  21976. use_rle = true;
  21977. case TGATools._TYPE_INDEXED:
  21978. use_pal = true;
  21979. break;
  21980. case TGATools._TYPE_RLE_RGB:
  21981. use_rle = true;
  21982. case TGATools._TYPE_RGB:
  21983. use_rgb = true;
  21984. break;
  21985. case TGATools._TYPE_RLE_GREY:
  21986. use_rle = true;
  21987. case TGATools._TYPE_GREY:
  21988. use_grey = true;
  21989. break;
  21990. }
  21991. var pixel_data;
  21992. var numAlphaBits = header.flags & 0xf;
  21993. var pixel_size = header.pixel_size >> 3;
  21994. var pixel_total = header.width * header.height * pixel_size;
  21995. // Read palettes
  21996. var palettes;
  21997. if (use_pal) {
  21998. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  21999. }
  22000. // Read LRE
  22001. if (use_rle) {
  22002. pixel_data = new Uint8Array(pixel_total);
  22003. var c, count, i;
  22004. var localOffset = 0;
  22005. var pixels = new Uint8Array(pixel_size);
  22006. while (offset < pixel_total && localOffset < pixel_total) {
  22007. c = data[offset++];
  22008. count = (c & 0x7f) + 1;
  22009. // RLE pixels
  22010. if (c & 0x80) {
  22011. for (i = 0; i < pixel_size; ++i) {
  22012. pixels[i] = data[offset++];
  22013. }
  22014. for (i = 0; i < count; ++i) {
  22015. pixel_data.set(pixels, localOffset + i * pixel_size);
  22016. }
  22017. localOffset += pixel_size * count;
  22018. }
  22019. else {
  22020. count *= pixel_size;
  22021. for (i = 0; i < count; ++i) {
  22022. pixel_data[localOffset + i] = data[offset++];
  22023. }
  22024. localOffset += count;
  22025. }
  22026. }
  22027. }
  22028. else {
  22029. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  22030. }
  22031. // Load to texture
  22032. var x_start, y_start, x_step, y_step, y_end, x_end;
  22033. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  22034. default:
  22035. case TGATools._ORIGIN_UL:
  22036. x_start = 0;
  22037. x_step = 1;
  22038. x_end = header.width;
  22039. y_start = 0;
  22040. y_step = 1;
  22041. y_end = header.height;
  22042. break;
  22043. case TGATools._ORIGIN_BL:
  22044. x_start = 0;
  22045. x_step = 1;
  22046. x_end = header.width;
  22047. y_start = header.height - 1;
  22048. y_step = -1;
  22049. y_end = -1;
  22050. break;
  22051. case TGATools._ORIGIN_UR:
  22052. x_start = header.width - 1;
  22053. x_step = -1;
  22054. x_end = -1;
  22055. y_start = 0;
  22056. y_step = 1;
  22057. y_end = header.height;
  22058. break;
  22059. case TGATools._ORIGIN_BR:
  22060. x_start = header.width - 1;
  22061. x_step = -1;
  22062. x_end = -1;
  22063. y_start = header.height - 1;
  22064. y_step = -1;
  22065. y_end = -1;
  22066. break;
  22067. }
  22068. // Load the specify method
  22069. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  22070. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  22071. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  22072. };
  22073. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22074. var image = pixel_data, colormap = palettes;
  22075. var width = header.width, height = header.height;
  22076. var color, i = 0, x, y;
  22077. var imageData = new Uint8Array(width * height * 4);
  22078. for (y = y_start; y !== y_end; y += y_step) {
  22079. for (x = x_start; x !== x_end; x += x_step, i++) {
  22080. color = image[i];
  22081. imageData[(x + width * y) * 4 + 3] = 255;
  22082. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  22083. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  22084. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  22085. }
  22086. }
  22087. return imageData;
  22088. };
  22089. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22090. var image = pixel_data;
  22091. var width = header.width, height = header.height;
  22092. var color, i = 0, x, y;
  22093. var imageData = new Uint8Array(width * height * 4);
  22094. for (y = y_start; y !== y_end; y += y_step) {
  22095. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22096. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  22097. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  22098. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  22099. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  22100. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  22101. }
  22102. }
  22103. return imageData;
  22104. };
  22105. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22106. var image = pixel_data;
  22107. var width = header.width, height = header.height;
  22108. var i = 0, x, y;
  22109. var imageData = new Uint8Array(width * height * 4);
  22110. for (y = y_start; y !== y_end; y += y_step) {
  22111. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  22112. imageData[(x + width * y) * 4 + 3] = 255;
  22113. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22114. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22115. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22116. }
  22117. }
  22118. return imageData;
  22119. };
  22120. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22121. var image = pixel_data;
  22122. var width = header.width, height = header.height;
  22123. var i = 0, x, y;
  22124. var imageData = new Uint8Array(width * height * 4);
  22125. for (y = y_start; y !== y_end; y += y_step) {
  22126. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  22127. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22128. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22129. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22130. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  22131. }
  22132. }
  22133. return imageData;
  22134. };
  22135. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22136. var image = pixel_data;
  22137. var width = header.width, height = header.height;
  22138. var color, i = 0, x, y;
  22139. var imageData = new Uint8Array(width * height * 4);
  22140. for (y = y_start; y !== y_end; y += y_step) {
  22141. for (x = x_start; x !== x_end; x += x_step, i++) {
  22142. color = image[i];
  22143. imageData[(x + width * y) * 4 + 0] = color;
  22144. imageData[(x + width * y) * 4 + 1] = color;
  22145. imageData[(x + width * y) * 4 + 2] = color;
  22146. imageData[(x + width * y) * 4 + 3] = 255;
  22147. }
  22148. }
  22149. return imageData;
  22150. };
  22151. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22152. var image = pixel_data;
  22153. var width = header.width, height = header.height;
  22154. var i = 0, x, y;
  22155. var imageData = new Uint8Array(width * height * 4);
  22156. for (y = y_start; y !== y_end; y += y_step) {
  22157. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22158. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  22159. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  22160. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22161. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  22162. }
  22163. }
  22164. return imageData;
  22165. };
  22166. TGATools._TYPE_NO_DATA = 0;
  22167. TGATools._TYPE_INDEXED = 1;
  22168. TGATools._TYPE_RGB = 2;
  22169. TGATools._TYPE_GREY = 3;
  22170. TGATools._TYPE_RLE_INDEXED = 9;
  22171. TGATools._TYPE_RLE_RGB = 10;
  22172. TGATools._TYPE_RLE_GREY = 11;
  22173. TGATools._ORIGIN_MASK = 0x30;
  22174. TGATools._ORIGIN_SHIFT = 0x04;
  22175. TGATools._ORIGIN_BL = 0x00;
  22176. TGATools._ORIGIN_BR = 0x01;
  22177. TGATools._ORIGIN_UL = 0x02;
  22178. TGATools._ORIGIN_UR = 0x03;
  22179. return TGATools;
  22180. })();
  22181. Internals.TGATools = TGATools;
  22182. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22183. })(BABYLON || (BABYLON = {}));
  22184. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  22185. (function (BABYLON) {
  22186. var Internals;
  22187. (function (Internals) {
  22188. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  22189. // All values and structures referenced from:
  22190. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  22191. var DDS_MAGIC = 0x20534444;
  22192. var DDSD_CAPS = 0x1, DDSD_HEIGHT = 0x2, DDSD_WIDTH = 0x4, DDSD_PITCH = 0x8, DDSD_PIXELFORMAT = 0x1000, DDSD_MIPMAPCOUNT = 0x20000, DDSD_LINEARSIZE = 0x80000, DDSD_DEPTH = 0x800000;
  22193. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  22194. var DDSCAPS2_CUBEMAP = 0x200, DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, DDSCAPS2_VOLUME = 0x200000;
  22195. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  22196. function FourCCToInt32(value) {
  22197. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  22198. }
  22199. function Int32ToFourCC(value) {
  22200. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  22201. }
  22202. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  22203. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  22204. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  22205. var headerLengthInt = 31; // The header length in 32 bit ints
  22206. // Offsets into the header array
  22207. var off_magic = 0;
  22208. var off_size = 1;
  22209. var off_flags = 2;
  22210. var off_height = 3;
  22211. var off_width = 4;
  22212. var off_mipmapCount = 7;
  22213. var off_pfFlags = 20;
  22214. var off_pfFourCC = 21;
  22215. var off_RGBbpp = 22;
  22216. var off_RMask = 23;
  22217. var off_GMask = 24;
  22218. var off_BMask = 25;
  22219. var off_AMask = 26;
  22220. var off_caps1 = 27;
  22221. var off_caps2 = 28;
  22222. ;
  22223. var DDSTools = (function () {
  22224. function DDSTools() {
  22225. }
  22226. DDSTools.GetDDSInfo = function (arrayBuffer) {
  22227. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  22228. var mipmapCount = 1;
  22229. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  22230. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22231. }
  22232. return {
  22233. width: header[off_width],
  22234. height: header[off_height],
  22235. mipmapCount: mipmapCount,
  22236. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  22237. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  22238. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  22239. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  22240. };
  22241. };
  22242. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22243. var byteArray = new Uint8Array(dataLength);
  22244. var srcData = new Uint8Array(arrayBuffer);
  22245. var index = 0;
  22246. for (var y = height - 1; y >= 0; y--) {
  22247. for (var x = 0; x < width; x++) {
  22248. var srcPos = dataOffset + (x + y * width) * 4;
  22249. byteArray[index + 2] = srcData[srcPos];
  22250. byteArray[index + 1] = srcData[srcPos + 1];
  22251. byteArray[index] = srcData[srcPos + 2];
  22252. byteArray[index + 3] = srcData[srcPos + 3];
  22253. index += 4;
  22254. }
  22255. }
  22256. return byteArray;
  22257. };
  22258. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22259. var byteArray = new Uint8Array(dataLength);
  22260. var srcData = new Uint8Array(arrayBuffer);
  22261. var index = 0;
  22262. for (var y = height - 1; y >= 0; y--) {
  22263. for (var x = 0; x < width; x++) {
  22264. var srcPos = dataOffset + (x + y * width) * 3;
  22265. byteArray[index + 2] = srcData[srcPos];
  22266. byteArray[index + 1] = srcData[srcPos + 1];
  22267. byteArray[index] = srcData[srcPos + 2];
  22268. index += 3;
  22269. }
  22270. }
  22271. return byteArray;
  22272. };
  22273. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22274. var byteArray = new Uint8Array(dataLength);
  22275. var srcData = new Uint8Array(arrayBuffer);
  22276. var index = 0;
  22277. for (var y = height - 1; y >= 0; y--) {
  22278. for (var x = 0; x < width; x++) {
  22279. var srcPos = dataOffset + (x + y * width);
  22280. byteArray[index] = srcData[srcPos];
  22281. index++;
  22282. }
  22283. }
  22284. return byteArray;
  22285. };
  22286. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  22287. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  22288. if (header[off_magic] != DDS_MAGIC) {
  22289. BABYLON.Tools.Error("Invalid magic number in DDS header");
  22290. return;
  22291. }
  22292. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  22293. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  22294. return;
  22295. }
  22296. if (info.isFourCC) {
  22297. fourCC = header[off_pfFourCC];
  22298. switch (fourCC) {
  22299. case FOURCC_DXT1:
  22300. blockBytes = 8;
  22301. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  22302. break;
  22303. case FOURCC_DXT3:
  22304. blockBytes = 16;
  22305. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  22306. break;
  22307. case FOURCC_DXT5:
  22308. blockBytes = 16;
  22309. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  22310. break;
  22311. default:
  22312. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  22313. return;
  22314. }
  22315. }
  22316. mipmapCount = 1;
  22317. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  22318. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22319. }
  22320. var bpp = header[off_RGBbpp];
  22321. for (var face = 0; face < faces; face++) {
  22322. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  22323. width = header[off_width];
  22324. height = header[off_height];
  22325. dataOffset = header[off_size] + 4;
  22326. for (i = 0; i < mipmapCount; ++i) {
  22327. if (info.isRGB) {
  22328. if (bpp == 24) {
  22329. dataLength = width * height * 3;
  22330. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22331. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  22332. }
  22333. else {
  22334. dataLength = width * height * 4;
  22335. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22336. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  22337. }
  22338. }
  22339. else if (info.isLuminance) {
  22340. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  22341. var unpaddedRowSize = width;
  22342. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  22343. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  22344. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22345. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  22346. }
  22347. else {
  22348. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  22349. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  22350. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  22351. }
  22352. dataOffset += dataLength;
  22353. width *= 0.5;
  22354. height *= 0.5;
  22355. width = Math.max(1.0, width);
  22356. height = Math.max(1.0, height);
  22357. }
  22358. }
  22359. };
  22360. return DDSTools;
  22361. })();
  22362. Internals.DDSTools = DDSTools;
  22363. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22364. })(BABYLON || (BABYLON = {}));
  22365. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  22366. (function (BABYLON) {
  22367. var SmartArray = (function () {
  22368. function SmartArray(capacity) {
  22369. this.length = 0;
  22370. this._duplicateId = 0;
  22371. this.data = new Array(capacity);
  22372. this._id = SmartArray._GlobalId++;
  22373. }
  22374. SmartArray.prototype.push = function (value) {
  22375. this.data[this.length++] = value;
  22376. if (this.length > this.data.length) {
  22377. this.data.length *= 2;
  22378. }
  22379. if (!value.__smartArrayFlags) {
  22380. value.__smartArrayFlags = {};
  22381. }
  22382. value.__smartArrayFlags[this._id] = this._duplicateId;
  22383. };
  22384. SmartArray.prototype.pushNoDuplicate = function (value) {
  22385. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  22386. return;
  22387. }
  22388. this.push(value);
  22389. };
  22390. SmartArray.prototype.sort = function (compareFn) {
  22391. this.data.sort(compareFn);
  22392. };
  22393. SmartArray.prototype.reset = function () {
  22394. this.length = 0;
  22395. this._duplicateId++;
  22396. };
  22397. SmartArray.prototype.concat = function (array) {
  22398. if (array.length === 0) {
  22399. return;
  22400. }
  22401. if (this.length + array.length > this.data.length) {
  22402. this.data.length = (this.length + array.length) * 2;
  22403. }
  22404. for (var index = 0; index < array.length; index++) {
  22405. this.data[this.length++] = (array.data || array)[index];
  22406. }
  22407. };
  22408. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  22409. if (array.length === 0) {
  22410. return;
  22411. }
  22412. if (this.length + array.length > this.data.length) {
  22413. this.data.length = (this.length + array.length) * 2;
  22414. }
  22415. for (var index = 0; index < array.length; index++) {
  22416. var item = (array.data || array)[index];
  22417. this.pushNoDuplicate(item);
  22418. }
  22419. };
  22420. SmartArray.prototype.indexOf = function (value) {
  22421. var position = this.data.indexOf(value);
  22422. if (position >= this.length) {
  22423. return -1;
  22424. }
  22425. return position;
  22426. };
  22427. // Statics
  22428. SmartArray._GlobalId = 0;
  22429. return SmartArray;
  22430. })();
  22431. BABYLON.SmartArray = SmartArray;
  22432. })(BABYLON || (BABYLON = {}));
  22433. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  22434. (function (BABYLON) {
  22435. var CannonJSPlugin = (function () {
  22436. function CannonJSPlugin() {
  22437. this._registeredMeshes = [];
  22438. this._physicsMaterials = [];
  22439. this.updateBodyPosition = function (mesh) {
  22440. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22441. var registeredMesh = this._registeredMeshes[index];
  22442. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22443. var body = registeredMesh.body;
  22444. var center = mesh.getBoundingInfo().boundingBox.center;
  22445. body.position.set(center.x, center.z, center.y);
  22446. body.quaternion.x = mesh.rotationQuaternion.x;
  22447. body.quaternion.z = mesh.rotationQuaternion.y;
  22448. body.quaternion.y = mesh.rotationQuaternion.z;
  22449. body.quaternion.w = -mesh.rotationQuaternion.w;
  22450. return;
  22451. }
  22452. }
  22453. };
  22454. }
  22455. CannonJSPlugin.prototype.initialize = function (iterations) {
  22456. if (iterations === void 0) { iterations = 10; }
  22457. this._world = new CANNON.World();
  22458. this._world.broadphase = new CANNON.NaiveBroadphase();
  22459. this._world.solver.iterations = iterations;
  22460. };
  22461. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22462. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22463. };
  22464. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22465. this._world.step(delta);
  22466. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22467. var registeredMesh = this._registeredMeshes[index];
  22468. if (registeredMesh.isChild) {
  22469. continue;
  22470. }
  22471. // Body position
  22472. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22473. var deltaPos = registeredMesh.delta;
  22474. if (deltaPos) {
  22475. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22476. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22477. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22478. }
  22479. else {
  22480. registeredMesh.mesh.position.x = bodyX;
  22481. registeredMesh.mesh.position.y = bodyZ;
  22482. registeredMesh.mesh.position.z = bodyY;
  22483. }
  22484. if (!registeredMesh.mesh.rotationQuaternion) {
  22485. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22486. }
  22487. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22488. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22489. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22490. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22491. }
  22492. };
  22493. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22494. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22495. };
  22496. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22497. this.unregisterMesh(mesh);
  22498. mesh.computeWorldMatrix(true);
  22499. switch (impostor) {
  22500. case BABYLON.PhysicsEngine.SphereImpostor:
  22501. var bbox = mesh.getBoundingInfo().boundingBox;
  22502. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22503. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22504. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22505. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22506. case BABYLON.PhysicsEngine.BoxImpostor:
  22507. bbox = mesh.getBoundingInfo().boundingBox;
  22508. var min = bbox.minimumWorld;
  22509. var max = bbox.maximumWorld;
  22510. var box = max.subtract(min).scale(0.5);
  22511. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22512. case BABYLON.PhysicsEngine.PlaneImpostor:
  22513. return this._createPlane(mesh, options);
  22514. case BABYLON.PhysicsEngine.MeshImpostor:
  22515. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22516. var rawFaces = mesh.getIndices();
  22517. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22518. }
  22519. return null;
  22520. };
  22521. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22522. var shape = new CANNON.Sphere(radius);
  22523. if (!options) {
  22524. return shape;
  22525. }
  22526. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22527. };
  22528. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22529. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22530. if (!options) {
  22531. return shape;
  22532. }
  22533. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22534. };
  22535. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22536. var shape = new CANNON.Plane();
  22537. if (!options) {
  22538. return shape;
  22539. }
  22540. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22541. };
  22542. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22543. var verts = [], faces = [];
  22544. mesh.computeWorldMatrix(true);
  22545. for (var i = 0; i < rawVerts.length; i += 3) {
  22546. var transformed = BABYLON.Vector3.Zero();
  22547. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22548. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22549. }
  22550. for (var j = 0; j < rawFaces.length; j += 3) {
  22551. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22552. }
  22553. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22554. if (!options) {
  22555. return shape;
  22556. }
  22557. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22558. };
  22559. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22560. var index;
  22561. var mat;
  22562. for (index = 0; index < this._physicsMaterials.length; index++) {
  22563. mat = this._physicsMaterials[index];
  22564. if (mat.friction === friction && mat.restitution === restitution) {
  22565. return mat;
  22566. }
  22567. }
  22568. var currentMat = new CANNON.Material();
  22569. currentMat.friction = friction;
  22570. currentMat.restitution = restitution;
  22571. this._physicsMaterials.push(currentMat);
  22572. for (index = 0; index < this._physicsMaterials.length; index++) {
  22573. mat = this._physicsMaterials[index];
  22574. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22575. contactMaterial.contactEquationStiffness = 1e10;
  22576. contactMaterial.contactEquationRegularizationTime = 10;
  22577. this._world.addContactMaterial(contactMaterial);
  22578. }
  22579. return currentMat;
  22580. };
  22581. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22582. var initialRotation = null;
  22583. if (mesh.rotationQuaternion) {
  22584. initialRotation = mesh.rotationQuaternion.clone();
  22585. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22586. }
  22587. // The delta between the mesh position and the mesh bounding box center
  22588. var bbox = mesh.getBoundingInfo().boundingBox;
  22589. var deltaPosition = mesh.position.subtract(bbox.center);
  22590. var material = this._addMaterial(friction, restitution);
  22591. var body = new CANNON.RigidBody(mass, shape, material);
  22592. if (initialRotation) {
  22593. body.quaternion.x = initialRotation.x;
  22594. body.quaternion.z = initialRotation.y;
  22595. body.quaternion.y = initialRotation.z;
  22596. body.quaternion.w = -initialRotation.w;
  22597. }
  22598. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22599. this._world.add(body);
  22600. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22601. return body;
  22602. };
  22603. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22604. var compoundShape = new CANNON.Compound();
  22605. for (var index = 0; index < parts.length; index++) {
  22606. var mesh = parts[index].mesh;
  22607. var shape = this.registerMesh(mesh, parts[index].impostor);
  22608. if (index == 0) {
  22609. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22610. }
  22611. else {
  22612. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22613. }
  22614. }
  22615. var initialMesh = parts[0].mesh;
  22616. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22617. body.parts = parts;
  22618. return body;
  22619. };
  22620. CannonJSPlugin.prototype._unbindBody = function (body) {
  22621. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22622. var registeredMesh = this._registeredMeshes[index];
  22623. if (registeredMesh.body === body) {
  22624. registeredMesh.body = null;
  22625. registeredMesh.delta = 0;
  22626. }
  22627. }
  22628. };
  22629. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22630. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22631. var registeredMesh = this._registeredMeshes[index];
  22632. if (registeredMesh.mesh === mesh) {
  22633. // Remove body
  22634. if (registeredMesh.body) {
  22635. this._world.remove(registeredMesh.body);
  22636. this._unbindBody(registeredMesh.body);
  22637. }
  22638. this._registeredMeshes.splice(index, 1);
  22639. return;
  22640. }
  22641. }
  22642. };
  22643. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22644. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22645. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22646. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22647. var registeredMesh = this._registeredMeshes[index];
  22648. if (registeredMesh.mesh === mesh) {
  22649. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22650. return;
  22651. }
  22652. }
  22653. };
  22654. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22655. var body1 = null, body2 = null;
  22656. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22657. var registeredMesh = this._registeredMeshes[index];
  22658. if (registeredMesh.mesh === mesh1) {
  22659. body1 = registeredMesh.body;
  22660. }
  22661. else if (registeredMesh.mesh === mesh2) {
  22662. body2 = registeredMesh.body;
  22663. }
  22664. }
  22665. if (!body1 || !body2) {
  22666. return false;
  22667. }
  22668. var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.z, pivot1.y), body2, new CANNON.Vec3(pivot2.x, pivot2.z, pivot2.y));
  22669. this._world.addConstraint(constraint);
  22670. return true;
  22671. };
  22672. CannonJSPlugin.prototype.dispose = function () {
  22673. while (this._registeredMeshes.length) {
  22674. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22675. }
  22676. };
  22677. CannonJSPlugin.prototype.isSupported = function () {
  22678. return window.CANNON !== undefined;
  22679. };
  22680. return CannonJSPlugin;
  22681. })();
  22682. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22683. })(BABYLON || (BABYLON = {}));
  22684. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22685. var BABYLON;
  22686. (function (BABYLON) {
  22687. var Condition = (function () {
  22688. function Condition(actionManager) {
  22689. this._actionManager = actionManager;
  22690. }
  22691. Condition.prototype.isValid = function () {
  22692. return true;
  22693. };
  22694. Condition.prototype._getProperty = function (propertyPath) {
  22695. return this._actionManager._getProperty(propertyPath);
  22696. };
  22697. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  22698. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22699. };
  22700. return Condition;
  22701. })();
  22702. BABYLON.Condition = Condition;
  22703. var ValueCondition = (function (_super) {
  22704. __extends(ValueCondition, _super);
  22705. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  22706. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  22707. _super.call(this, actionManager);
  22708. this.propertyPath = propertyPath;
  22709. this.value = value;
  22710. this.operator = operator;
  22711. this._target = this._getEffectiveTarget(target, this.propertyPath);
  22712. this._property = this._getProperty(this.propertyPath);
  22713. }
  22714. Object.defineProperty(ValueCondition, "IsEqual", {
  22715. get: function () {
  22716. return ValueCondition._IsEqual;
  22717. },
  22718. enumerable: true,
  22719. configurable: true
  22720. });
  22721. Object.defineProperty(ValueCondition, "IsDifferent", {
  22722. get: function () {
  22723. return ValueCondition._IsDifferent;
  22724. },
  22725. enumerable: true,
  22726. configurable: true
  22727. });
  22728. Object.defineProperty(ValueCondition, "IsGreater", {
  22729. get: function () {
  22730. return ValueCondition._IsGreater;
  22731. },
  22732. enumerable: true,
  22733. configurable: true
  22734. });
  22735. Object.defineProperty(ValueCondition, "IsLesser", {
  22736. get: function () {
  22737. return ValueCondition._IsLesser;
  22738. },
  22739. enumerable: true,
  22740. configurable: true
  22741. });
  22742. // Methods
  22743. ValueCondition.prototype.isValid = function () {
  22744. switch (this.operator) {
  22745. case ValueCondition.IsGreater:
  22746. return this._target[this._property] > this.value;
  22747. case ValueCondition.IsLesser:
  22748. return this._target[this._property] < this.value;
  22749. case ValueCondition.IsEqual:
  22750. case ValueCondition.IsDifferent:
  22751. var check;
  22752. if (this.value.equals) {
  22753. check = this.value.equals(this._target[this._property]);
  22754. }
  22755. else {
  22756. check = this.value === this._target[this._property];
  22757. }
  22758. return this.operator === ValueCondition.IsEqual ? check : !check;
  22759. }
  22760. return false;
  22761. };
  22762. // Statics
  22763. ValueCondition._IsEqual = 0;
  22764. ValueCondition._IsDifferent = 1;
  22765. ValueCondition._IsGreater = 2;
  22766. ValueCondition._IsLesser = 3;
  22767. return ValueCondition;
  22768. })(Condition);
  22769. BABYLON.ValueCondition = ValueCondition;
  22770. var PredicateCondition = (function (_super) {
  22771. __extends(PredicateCondition, _super);
  22772. function PredicateCondition(actionManager, predicate) {
  22773. _super.call(this, actionManager);
  22774. this.predicate = predicate;
  22775. }
  22776. PredicateCondition.prototype.isValid = function () {
  22777. return this.predicate();
  22778. };
  22779. return PredicateCondition;
  22780. })(Condition);
  22781. BABYLON.PredicateCondition = PredicateCondition;
  22782. var StateCondition = (function (_super) {
  22783. __extends(StateCondition, _super);
  22784. function StateCondition(actionManager, target, value) {
  22785. _super.call(this, actionManager);
  22786. this.value = value;
  22787. this._target = target;
  22788. }
  22789. // Methods
  22790. StateCondition.prototype.isValid = function () {
  22791. return this._target.state === this.value;
  22792. };
  22793. return StateCondition;
  22794. })(Condition);
  22795. BABYLON.StateCondition = StateCondition;
  22796. })(BABYLON || (BABYLON = {}));
  22797. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  22798. (function (BABYLON) {
  22799. var Action = (function () {
  22800. function Action(triggerOptions, condition) {
  22801. this.triggerOptions = triggerOptions;
  22802. if (triggerOptions.parameter) {
  22803. this.trigger = triggerOptions.trigger;
  22804. this._triggerParameter = triggerOptions.parameter;
  22805. }
  22806. else {
  22807. this.trigger = triggerOptions;
  22808. }
  22809. this._nextActiveAction = this;
  22810. this._condition = condition;
  22811. }
  22812. // Methods
  22813. Action.prototype._prepare = function () {
  22814. };
  22815. Action.prototype.getTriggerParameter = function () {
  22816. return this._triggerParameter;
  22817. };
  22818. Action.prototype._executeCurrent = function (evt) {
  22819. if (this._condition) {
  22820. var currentRenderId = this._actionManager.getScene().getRenderId();
  22821. // We cache the current evaluation for the current frame
  22822. if (this._condition._evaluationId === currentRenderId) {
  22823. if (!this._condition._currentResult) {
  22824. return;
  22825. }
  22826. }
  22827. else {
  22828. this._condition._evaluationId = currentRenderId;
  22829. if (!this._condition.isValid()) {
  22830. this._condition._currentResult = false;
  22831. return;
  22832. }
  22833. this._condition._currentResult = true;
  22834. }
  22835. }
  22836. this._nextActiveAction.execute(evt);
  22837. if (this._nextActiveAction._child) {
  22838. if (!this._nextActiveAction._child._actionManager) {
  22839. this._nextActiveAction._child._actionManager = this._actionManager;
  22840. }
  22841. this._nextActiveAction = this._nextActiveAction._child;
  22842. }
  22843. else {
  22844. this._nextActiveAction = this;
  22845. }
  22846. };
  22847. Action.prototype.execute = function (evt) {
  22848. };
  22849. Action.prototype.then = function (action) {
  22850. this._child = action;
  22851. action._actionManager = this._actionManager;
  22852. action._prepare();
  22853. return action;
  22854. };
  22855. Action.prototype._getProperty = function (propertyPath) {
  22856. return this._actionManager._getProperty(propertyPath);
  22857. };
  22858. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  22859. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22860. };
  22861. return Action;
  22862. })();
  22863. BABYLON.Action = Action;
  22864. })(BABYLON || (BABYLON = {}));
  22865. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  22866. (function (BABYLON) {
  22867. /**
  22868. * ActionEvent is the event beint sent when an action is triggered.
  22869. */
  22870. var ActionEvent = (function () {
  22871. /**
  22872. * @constructor
  22873. * @param source The mesh that triggered the action.
  22874. * @param pointerX the X mouse cursor position at the time of the event
  22875. * @param pointerY the Y mouse cursor position at the time of the event
  22876. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  22877. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  22878. */
  22879. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  22880. this.source = source;
  22881. this.pointerX = pointerX;
  22882. this.pointerY = pointerY;
  22883. this.meshUnderPointer = meshUnderPointer;
  22884. this.sourceEvent = sourceEvent;
  22885. }
  22886. /**
  22887. * Helper function to auto-create an ActionEvent from a source mesh.
  22888. * @param source the source mesh that triggered the event
  22889. * @param evt {Event} The original (browser) event
  22890. */
  22891. ActionEvent.CreateNew = function (source, evt) {
  22892. var scene = source.getScene();
  22893. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22894. };
  22895. /**
  22896. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  22897. * @param scene the scene where the event occurred
  22898. * @param evt {Event} The original (browser) event
  22899. */
  22900. ActionEvent.CreateNewFromScene = function (scene, evt) {
  22901. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22902. };
  22903. return ActionEvent;
  22904. })();
  22905. BABYLON.ActionEvent = ActionEvent;
  22906. /**
  22907. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  22908. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  22909. */
  22910. var ActionManager = (function () {
  22911. function ActionManager(scene) {
  22912. // Members
  22913. this.actions = new Array();
  22914. this._scene = scene;
  22915. scene._actionManagers.push(this);
  22916. }
  22917. Object.defineProperty(ActionManager, "NothingTrigger", {
  22918. get: function () {
  22919. return ActionManager._NothingTrigger;
  22920. },
  22921. enumerable: true,
  22922. configurable: true
  22923. });
  22924. Object.defineProperty(ActionManager, "OnPickTrigger", {
  22925. get: function () {
  22926. return ActionManager._OnPickTrigger;
  22927. },
  22928. enumerable: true,
  22929. configurable: true
  22930. });
  22931. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  22932. get: function () {
  22933. return ActionManager._OnLeftPickTrigger;
  22934. },
  22935. enumerable: true,
  22936. configurable: true
  22937. });
  22938. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  22939. get: function () {
  22940. return ActionManager._OnRightPickTrigger;
  22941. },
  22942. enumerable: true,
  22943. configurable: true
  22944. });
  22945. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  22946. get: function () {
  22947. return ActionManager._OnCenterPickTrigger;
  22948. },
  22949. enumerable: true,
  22950. configurable: true
  22951. });
  22952. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  22953. get: function () {
  22954. return ActionManager._OnPointerOverTrigger;
  22955. },
  22956. enumerable: true,
  22957. configurable: true
  22958. });
  22959. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  22960. get: function () {
  22961. return ActionManager._OnPointerOutTrigger;
  22962. },
  22963. enumerable: true,
  22964. configurable: true
  22965. });
  22966. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  22967. get: function () {
  22968. return ActionManager._OnEveryFrameTrigger;
  22969. },
  22970. enumerable: true,
  22971. configurable: true
  22972. });
  22973. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  22974. get: function () {
  22975. return ActionManager._OnIntersectionEnterTrigger;
  22976. },
  22977. enumerable: true,
  22978. configurable: true
  22979. });
  22980. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  22981. get: function () {
  22982. return ActionManager._OnIntersectionExitTrigger;
  22983. },
  22984. enumerable: true,
  22985. configurable: true
  22986. });
  22987. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  22988. get: function () {
  22989. return ActionManager._OnKeyDownTrigger;
  22990. },
  22991. enumerable: true,
  22992. configurable: true
  22993. });
  22994. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  22995. get: function () {
  22996. return ActionManager._OnKeyUpTrigger;
  22997. },
  22998. enumerable: true,
  22999. configurable: true
  23000. });
  23001. // Methods
  23002. ActionManager.prototype.dispose = function () {
  23003. var index = this._scene._actionManagers.indexOf(this);
  23004. if (index > -1) {
  23005. this._scene._actionManagers.splice(index, 1);
  23006. }
  23007. };
  23008. ActionManager.prototype.getScene = function () {
  23009. return this._scene;
  23010. };
  23011. /**
  23012. * Does this action manager handles actions of any of the given triggers
  23013. * @param {number[]} triggers - the triggers to be tested
  23014. * @return {boolean} whether one (or more) of the triggers is handeled
  23015. */
  23016. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  23017. for (var index = 0; index < this.actions.length; index++) {
  23018. var action = this.actions[index];
  23019. if (triggers.indexOf(action.trigger) > -1) {
  23020. return true;
  23021. }
  23022. }
  23023. return false;
  23024. };
  23025. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  23026. /**
  23027. * Does this action manager has pointer triggers
  23028. * @return {boolean} whether or not it has pointer triggers
  23029. */
  23030. get: function () {
  23031. for (var index = 0; index < this.actions.length; index++) {
  23032. var action = this.actions[index];
  23033. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  23034. return true;
  23035. }
  23036. }
  23037. return false;
  23038. },
  23039. enumerable: true,
  23040. configurable: true
  23041. });
  23042. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  23043. /**
  23044. * Does this action manager has pick triggers
  23045. * @return {boolean} whether or not it has pick triggers
  23046. */
  23047. get: function () {
  23048. for (var index = 0; index < this.actions.length; index++) {
  23049. var action = this.actions[index];
  23050. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  23051. return true;
  23052. }
  23053. }
  23054. return false;
  23055. },
  23056. enumerable: true,
  23057. configurable: true
  23058. });
  23059. /**
  23060. * Registers an action to this action manager
  23061. * @param {BABYLON.Action} action - the action to be registered
  23062. * @return {BABYLON.Action} the action amended (prepared) after registration
  23063. */
  23064. ActionManager.prototype.registerAction = function (action) {
  23065. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  23066. if (this.getScene().actionManager !== this) {
  23067. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  23068. return null;
  23069. }
  23070. }
  23071. this.actions.push(action);
  23072. action._actionManager = this;
  23073. action._prepare();
  23074. return action;
  23075. };
  23076. /**
  23077. * Process a specific trigger
  23078. * @param {number} trigger - the trigger to process
  23079. * @param evt {BABYLON.ActionEvent} the event details to be processed
  23080. */
  23081. ActionManager.prototype.processTrigger = function (trigger, evt) {
  23082. for (var index = 0; index < this.actions.length; index++) {
  23083. var action = this.actions[index];
  23084. if (action.trigger === trigger) {
  23085. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  23086. var parameter = action.getTriggerParameter();
  23087. if (parameter) {
  23088. if (evt.sourceEvent.key !== parameter) {
  23089. continue;
  23090. }
  23091. }
  23092. }
  23093. action._executeCurrent(evt);
  23094. }
  23095. }
  23096. };
  23097. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  23098. var properties = propertyPath.split(".");
  23099. for (var index = 0; index < properties.length - 1; index++) {
  23100. target = target[properties[index]];
  23101. }
  23102. return target;
  23103. };
  23104. ActionManager.prototype._getProperty = function (propertyPath) {
  23105. var properties = propertyPath.split(".");
  23106. return properties[properties.length - 1];
  23107. };
  23108. // Statics
  23109. ActionManager._NothingTrigger = 0;
  23110. ActionManager._OnPickTrigger = 1;
  23111. ActionManager._OnLeftPickTrigger = 2;
  23112. ActionManager._OnRightPickTrigger = 3;
  23113. ActionManager._OnCenterPickTrigger = 4;
  23114. ActionManager._OnPointerOverTrigger = 5;
  23115. ActionManager._OnPointerOutTrigger = 6;
  23116. ActionManager._OnEveryFrameTrigger = 7;
  23117. ActionManager._OnIntersectionEnterTrigger = 8;
  23118. ActionManager._OnIntersectionExitTrigger = 9;
  23119. ActionManager._OnKeyDownTrigger = 10;
  23120. ActionManager._OnKeyUpTrigger = 11;
  23121. return ActionManager;
  23122. })();
  23123. BABYLON.ActionManager = ActionManager;
  23124. })(BABYLON || (BABYLON = {}));
  23125. //# sourceMappingURL=babylon.actionManager.js.map
  23126. var BABYLON;
  23127. (function (BABYLON) {
  23128. var InterpolateValueAction = (function (_super) {
  23129. __extends(InterpolateValueAction, _super);
  23130. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  23131. if (duration === void 0) { duration = 1000; }
  23132. _super.call(this, triggerOptions, condition);
  23133. this.propertyPath = propertyPath;
  23134. this.value = value;
  23135. this.duration = duration;
  23136. this.stopOtherAnimations = stopOtherAnimations;
  23137. this._target = target;
  23138. }
  23139. InterpolateValueAction.prototype._prepare = function () {
  23140. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23141. this._property = this._getProperty(this.propertyPath);
  23142. };
  23143. InterpolateValueAction.prototype.execute = function () {
  23144. var scene = this._actionManager.getScene();
  23145. var keys = [
  23146. {
  23147. frame: 0,
  23148. value: this._target[this._property]
  23149. },
  23150. {
  23151. frame: 100,
  23152. value: this.value
  23153. }
  23154. ];
  23155. var dataType;
  23156. if (typeof this.value === "number") {
  23157. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  23158. }
  23159. else if (this.value instanceof BABYLON.Color3) {
  23160. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  23161. }
  23162. else if (this.value instanceof BABYLON.Vector3) {
  23163. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  23164. }
  23165. else if (this.value instanceof BABYLON.Matrix) {
  23166. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  23167. }
  23168. else if (this.value instanceof BABYLON.Quaternion) {
  23169. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  23170. }
  23171. else {
  23172. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  23173. return;
  23174. }
  23175. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  23176. animation.setKeys(keys);
  23177. if (this.stopOtherAnimations) {
  23178. scene.stopAnimation(this._target);
  23179. }
  23180. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  23181. };
  23182. return InterpolateValueAction;
  23183. })(BABYLON.Action);
  23184. BABYLON.InterpolateValueAction = InterpolateValueAction;
  23185. })(BABYLON || (BABYLON = {}));
  23186. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  23187. var BABYLON;
  23188. (function (BABYLON) {
  23189. var SwitchBooleanAction = (function (_super) {
  23190. __extends(SwitchBooleanAction, _super);
  23191. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  23192. _super.call(this, triggerOptions, condition);
  23193. this.propertyPath = propertyPath;
  23194. this._target = target;
  23195. }
  23196. SwitchBooleanAction.prototype._prepare = function () {
  23197. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23198. this._property = this._getProperty(this.propertyPath);
  23199. };
  23200. SwitchBooleanAction.prototype.execute = function () {
  23201. this._target[this._property] = !this._target[this._property];
  23202. };
  23203. return SwitchBooleanAction;
  23204. })(BABYLON.Action);
  23205. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  23206. var SetStateAction = (function (_super) {
  23207. __extends(SetStateAction, _super);
  23208. function SetStateAction(triggerOptions, target, value, condition) {
  23209. _super.call(this, triggerOptions, condition);
  23210. this.value = value;
  23211. this._target = target;
  23212. }
  23213. SetStateAction.prototype.execute = function () {
  23214. this._target.state = this.value;
  23215. };
  23216. return SetStateAction;
  23217. })(BABYLON.Action);
  23218. BABYLON.SetStateAction = SetStateAction;
  23219. var SetValueAction = (function (_super) {
  23220. __extends(SetValueAction, _super);
  23221. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  23222. _super.call(this, triggerOptions, condition);
  23223. this.propertyPath = propertyPath;
  23224. this.value = value;
  23225. this._target = target;
  23226. }
  23227. SetValueAction.prototype._prepare = function () {
  23228. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23229. this._property = this._getProperty(this.propertyPath);
  23230. };
  23231. SetValueAction.prototype.execute = function () {
  23232. this._target[this._property] = this.value;
  23233. };
  23234. return SetValueAction;
  23235. })(BABYLON.Action);
  23236. BABYLON.SetValueAction = SetValueAction;
  23237. var IncrementValueAction = (function (_super) {
  23238. __extends(IncrementValueAction, _super);
  23239. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  23240. _super.call(this, triggerOptions, condition);
  23241. this.propertyPath = propertyPath;
  23242. this.value = value;
  23243. this._target = target;
  23244. }
  23245. IncrementValueAction.prototype._prepare = function () {
  23246. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23247. this._property = this._getProperty(this.propertyPath);
  23248. if (typeof this._target[this._property] !== "number") {
  23249. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  23250. }
  23251. };
  23252. IncrementValueAction.prototype.execute = function () {
  23253. this._target[this._property] += this.value;
  23254. };
  23255. return IncrementValueAction;
  23256. })(BABYLON.Action);
  23257. BABYLON.IncrementValueAction = IncrementValueAction;
  23258. var PlayAnimationAction = (function (_super) {
  23259. __extends(PlayAnimationAction, _super);
  23260. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  23261. _super.call(this, triggerOptions, condition);
  23262. this.from = from;
  23263. this.to = to;
  23264. this.loop = loop;
  23265. this._target = target;
  23266. }
  23267. PlayAnimationAction.prototype._prepare = function () {
  23268. };
  23269. PlayAnimationAction.prototype.execute = function () {
  23270. var scene = this._actionManager.getScene();
  23271. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  23272. };
  23273. return PlayAnimationAction;
  23274. })(BABYLON.Action);
  23275. BABYLON.PlayAnimationAction = PlayAnimationAction;
  23276. var StopAnimationAction = (function (_super) {
  23277. __extends(StopAnimationAction, _super);
  23278. function StopAnimationAction(triggerOptions, target, condition) {
  23279. _super.call(this, triggerOptions, condition);
  23280. this._target = target;
  23281. }
  23282. StopAnimationAction.prototype._prepare = function () {
  23283. };
  23284. StopAnimationAction.prototype.execute = function () {
  23285. var scene = this._actionManager.getScene();
  23286. scene.stopAnimation(this._target);
  23287. };
  23288. return StopAnimationAction;
  23289. })(BABYLON.Action);
  23290. BABYLON.StopAnimationAction = StopAnimationAction;
  23291. var DoNothingAction = (function (_super) {
  23292. __extends(DoNothingAction, _super);
  23293. function DoNothingAction(triggerOptions, condition) {
  23294. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  23295. _super.call(this, triggerOptions, condition);
  23296. }
  23297. DoNothingAction.prototype.execute = function () {
  23298. };
  23299. return DoNothingAction;
  23300. })(BABYLON.Action);
  23301. BABYLON.DoNothingAction = DoNothingAction;
  23302. var CombineAction = (function (_super) {
  23303. __extends(CombineAction, _super);
  23304. function CombineAction(triggerOptions, children, condition) {
  23305. _super.call(this, triggerOptions, condition);
  23306. this.children = children;
  23307. }
  23308. CombineAction.prototype._prepare = function () {
  23309. for (var index = 0; index < this.children.length; index++) {
  23310. this.children[index]._actionManager = this._actionManager;
  23311. this.children[index]._prepare();
  23312. }
  23313. };
  23314. CombineAction.prototype.execute = function (evt) {
  23315. for (var index = 0; index < this.children.length; index++) {
  23316. this.children[index].execute(evt);
  23317. }
  23318. };
  23319. return CombineAction;
  23320. })(BABYLON.Action);
  23321. BABYLON.CombineAction = CombineAction;
  23322. var ExecuteCodeAction = (function (_super) {
  23323. __extends(ExecuteCodeAction, _super);
  23324. function ExecuteCodeAction(triggerOptions, func, condition) {
  23325. _super.call(this, triggerOptions, condition);
  23326. this.func = func;
  23327. }
  23328. ExecuteCodeAction.prototype.execute = function (evt) {
  23329. this.func(evt);
  23330. };
  23331. return ExecuteCodeAction;
  23332. })(BABYLON.Action);
  23333. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  23334. var SetParentAction = (function (_super) {
  23335. __extends(SetParentAction, _super);
  23336. function SetParentAction(triggerOptions, target, parent, condition) {
  23337. _super.call(this, triggerOptions, condition);
  23338. this._target = target;
  23339. this._parent = parent;
  23340. }
  23341. SetParentAction.prototype._prepare = function () {
  23342. };
  23343. SetParentAction.prototype.execute = function () {
  23344. if (this._target.parent === this._parent) {
  23345. return;
  23346. }
  23347. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  23348. invertParentWorldMatrix.invert();
  23349. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  23350. this._target.parent = this._parent;
  23351. };
  23352. return SetParentAction;
  23353. })(BABYLON.Action);
  23354. BABYLON.SetParentAction = SetParentAction;
  23355. })(BABYLON || (BABYLON = {}));
  23356. //# sourceMappingURL=babylon.directActions.js.map
  23357. var BABYLON;
  23358. (function (BABYLON) {
  23359. var Geometry = (function () {
  23360. function Geometry(id, scene, vertexData, updatable, mesh) {
  23361. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23362. this._totalVertices = 0;
  23363. this._indices = [];
  23364. this.id = id;
  23365. this._engine = scene.getEngine();
  23366. this._meshes = [];
  23367. this._scene = scene;
  23368. // vertexData
  23369. if (vertexData) {
  23370. this.setAllVerticesData(vertexData, updatable);
  23371. }
  23372. else {
  23373. this._totalVertices = 0;
  23374. this._indices = [];
  23375. }
  23376. // applyToMesh
  23377. if (mesh) {
  23378. this.applyToMesh(mesh);
  23379. }
  23380. }
  23381. Geometry.prototype.getScene = function () {
  23382. return this._scene;
  23383. };
  23384. Geometry.prototype.getEngine = function () {
  23385. return this._engine;
  23386. };
  23387. Geometry.prototype.isReady = function () {
  23388. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  23389. };
  23390. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  23391. vertexData.applyToGeometry(this, updatable);
  23392. };
  23393. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23394. this._vertexBuffers = this._vertexBuffers || {};
  23395. if (this._vertexBuffers[kind]) {
  23396. this._vertexBuffers[kind].dispose();
  23397. }
  23398. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  23399. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23400. stride = this._vertexBuffers[kind].getStrideSize();
  23401. this._totalVertices = data.length / stride;
  23402. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23403. var meshes = this._meshes;
  23404. var numOfMeshes = meshes.length;
  23405. for (var index = 0; index < numOfMeshes; index++) {
  23406. var mesh = meshes[index];
  23407. mesh._resetPointsArrayCache();
  23408. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23409. mesh._createGlobalSubMesh();
  23410. mesh.computeWorldMatrix(true);
  23411. }
  23412. }
  23413. };
  23414. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  23415. var vertexBuffer = this.getVertexBuffer(kind);
  23416. if (!vertexBuffer) {
  23417. return;
  23418. }
  23419. vertexBuffer.updateDirectly(data, offset);
  23420. };
  23421. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  23422. var vertexBuffer = this.getVertexBuffer(kind);
  23423. if (!vertexBuffer) {
  23424. return;
  23425. }
  23426. vertexBuffer.update(data);
  23427. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23428. var extend;
  23429. var stride = vertexBuffer.getStrideSize();
  23430. this._totalVertices = data.length / stride;
  23431. if (updateExtends) {
  23432. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23433. }
  23434. var meshes = this._meshes;
  23435. var numOfMeshes = meshes.length;
  23436. for (var index = 0; index < numOfMeshes; index++) {
  23437. var mesh = meshes[index];
  23438. mesh._resetPointsArrayCache();
  23439. if (updateExtends) {
  23440. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23441. }
  23442. }
  23443. }
  23444. };
  23445. Geometry.prototype.getTotalVertices = function () {
  23446. if (!this.isReady()) {
  23447. return 0;
  23448. }
  23449. return this._totalVertices;
  23450. };
  23451. Geometry.prototype.getVerticesData = function (kind) {
  23452. var vertexBuffer = this.getVertexBuffer(kind);
  23453. if (!vertexBuffer) {
  23454. return null;
  23455. }
  23456. return vertexBuffer.getData();
  23457. };
  23458. Geometry.prototype.getVertexBuffer = function (kind) {
  23459. if (!this.isReady()) {
  23460. return null;
  23461. }
  23462. return this._vertexBuffers[kind];
  23463. };
  23464. Geometry.prototype.getVertexBuffers = function () {
  23465. if (!this.isReady()) {
  23466. return null;
  23467. }
  23468. return this._vertexBuffers;
  23469. };
  23470. Geometry.prototype.isVerticesDataPresent = function (kind) {
  23471. if (!this._vertexBuffers) {
  23472. if (this._delayInfo) {
  23473. return this._delayInfo.indexOf(kind) !== -1;
  23474. }
  23475. return false;
  23476. }
  23477. return this._vertexBuffers[kind] !== undefined;
  23478. };
  23479. Geometry.prototype.getVerticesDataKinds = function () {
  23480. var result = [];
  23481. if (!this._vertexBuffers && this._delayInfo) {
  23482. for (var kind in this._delayInfo) {
  23483. result.push(kind);
  23484. }
  23485. }
  23486. else {
  23487. for (kind in this._vertexBuffers) {
  23488. result.push(kind);
  23489. }
  23490. }
  23491. return result;
  23492. };
  23493. Geometry.prototype.setIndices = function (indices, totalVertices) {
  23494. if (this._indexBuffer) {
  23495. this._engine._releaseBuffer(this._indexBuffer);
  23496. }
  23497. this._indices = indices;
  23498. if (this._meshes.length !== 0 && this._indices) {
  23499. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23500. }
  23501. if (totalVertices !== undefined) {
  23502. this._totalVertices = totalVertices;
  23503. }
  23504. var meshes = this._meshes;
  23505. var numOfMeshes = meshes.length;
  23506. for (var index = 0; index < numOfMeshes; index++) {
  23507. meshes[index]._createGlobalSubMesh();
  23508. }
  23509. };
  23510. Geometry.prototype.getTotalIndices = function () {
  23511. if (!this.isReady()) {
  23512. return 0;
  23513. }
  23514. return this._indices.length;
  23515. };
  23516. Geometry.prototype.getIndices = function () {
  23517. if (!this.isReady()) {
  23518. return null;
  23519. }
  23520. return this._indices;
  23521. };
  23522. Geometry.prototype.getIndexBuffer = function () {
  23523. if (!this.isReady()) {
  23524. return null;
  23525. }
  23526. return this._indexBuffer;
  23527. };
  23528. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  23529. var meshes = this._meshes;
  23530. var index = meshes.indexOf(mesh);
  23531. if (index === -1) {
  23532. return;
  23533. }
  23534. for (var kind in this._vertexBuffers) {
  23535. this._vertexBuffers[kind].dispose();
  23536. }
  23537. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  23538. this._indexBuffer = null;
  23539. }
  23540. meshes.splice(index, 1);
  23541. mesh._geometry = null;
  23542. if (meshes.length === 0 && shouldDispose) {
  23543. this.dispose();
  23544. }
  23545. };
  23546. Geometry.prototype.applyToMesh = function (mesh) {
  23547. if (mesh._geometry === this) {
  23548. return;
  23549. }
  23550. var previousGeometry = mesh._geometry;
  23551. if (previousGeometry) {
  23552. previousGeometry.releaseForMesh(mesh);
  23553. }
  23554. var meshes = this._meshes;
  23555. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  23556. mesh._geometry = this;
  23557. this._scene.pushGeometry(this);
  23558. meshes.push(mesh);
  23559. if (this.isReady()) {
  23560. this._applyToMesh(mesh);
  23561. }
  23562. else {
  23563. mesh._boundingInfo = this._boundingInfo;
  23564. }
  23565. };
  23566. Geometry.prototype._applyToMesh = function (mesh) {
  23567. var numOfMeshes = this._meshes.length;
  23568. for (var kind in this._vertexBuffers) {
  23569. if (numOfMeshes === 1) {
  23570. this._vertexBuffers[kind].create();
  23571. }
  23572. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  23573. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23574. mesh._resetPointsArrayCache();
  23575. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  23576. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23577. mesh._createGlobalSubMesh();
  23578. //bounding info was just created again, world matrix should be applied again.
  23579. mesh._updateBoundingInfo();
  23580. }
  23581. }
  23582. // indexBuffer
  23583. if (numOfMeshes === 1 && this._indices) {
  23584. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23585. }
  23586. if (this._indexBuffer) {
  23587. this._indexBuffer.references = numOfMeshes;
  23588. }
  23589. };
  23590. Geometry.prototype.load = function (scene, onLoaded) {
  23591. var _this = this;
  23592. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23593. return;
  23594. }
  23595. if (this.isReady()) {
  23596. if (onLoaded) {
  23597. onLoaded();
  23598. }
  23599. return;
  23600. }
  23601. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23602. scene._addPendingData(this);
  23603. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23604. _this._delayLoadingFunction(JSON.parse(data), _this);
  23605. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23606. _this._delayInfo = [];
  23607. scene._removePendingData(_this);
  23608. var meshes = _this._meshes;
  23609. var numOfMeshes = meshes.length;
  23610. for (var index = 0; index < numOfMeshes; index++) {
  23611. _this._applyToMesh(meshes[index]);
  23612. }
  23613. if (onLoaded) {
  23614. onLoaded();
  23615. }
  23616. }, function () {
  23617. }, scene.database);
  23618. };
  23619. Geometry.prototype.dispose = function () {
  23620. var meshes = this._meshes;
  23621. var numOfMeshes = meshes.length;
  23622. var index;
  23623. for (index = 0; index < numOfMeshes; index++) {
  23624. this.releaseForMesh(meshes[index]);
  23625. }
  23626. this._meshes = [];
  23627. for (var kind in this._vertexBuffers) {
  23628. this._vertexBuffers[kind].dispose();
  23629. }
  23630. this._vertexBuffers = [];
  23631. this._totalVertices = 0;
  23632. if (this._indexBuffer) {
  23633. this._engine._releaseBuffer(this._indexBuffer);
  23634. }
  23635. this._indexBuffer = null;
  23636. this._indices = [];
  23637. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23638. this.delayLoadingFile = null;
  23639. this._delayLoadingFunction = null;
  23640. this._delayInfo = [];
  23641. this._boundingInfo = null; // todo: .dispose()
  23642. var geometries = this._scene.getGeometries();
  23643. index = geometries.indexOf(this);
  23644. if (index > -1) {
  23645. geometries.splice(index, 1);
  23646. }
  23647. };
  23648. Geometry.prototype.copy = function (id) {
  23649. var vertexData = new BABYLON.VertexData();
  23650. vertexData.indices = [];
  23651. var indices = this.getIndices();
  23652. for (var index = 0; index < indices.length; index++) {
  23653. vertexData.indices.push(indices[index]);
  23654. }
  23655. var updatable = false;
  23656. var stopChecking = false;
  23657. for (var kind in this._vertexBuffers) {
  23658. vertexData.set(this.getVerticesData(kind), kind);
  23659. if (!stopChecking) {
  23660. updatable = this.getVertexBuffer(kind).isUpdatable();
  23661. stopChecking = !updatable;
  23662. }
  23663. }
  23664. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  23665. geometry.delayLoadState = this.delayLoadState;
  23666. geometry.delayLoadingFile = this.delayLoadingFile;
  23667. geometry._delayLoadingFunction = this._delayLoadingFunction;
  23668. for (kind in this._delayInfo) {
  23669. geometry._delayInfo = geometry._delayInfo || [];
  23670. geometry._delayInfo.push(kind);
  23671. }
  23672. // Bounding info
  23673. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  23674. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23675. return geometry;
  23676. };
  23677. // Statics
  23678. Geometry.ExtractFromMesh = function (mesh, id) {
  23679. var geometry = mesh._geometry;
  23680. if (!geometry) {
  23681. return null;
  23682. }
  23683. return geometry.copy(id);
  23684. };
  23685. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  23686. // be aware Math.random() could cause collisions
  23687. Geometry.RandomId = function () {
  23688. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  23689. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  23690. return v.toString(16);
  23691. });
  23692. };
  23693. return Geometry;
  23694. })();
  23695. BABYLON.Geometry = Geometry;
  23696. /////// Primitives //////////////////////////////////////////////
  23697. var Geometry;
  23698. (function (Geometry) {
  23699. var Primitives;
  23700. (function (Primitives) {
  23701. /// Abstract class
  23702. var _Primitive = (function (_super) {
  23703. __extends(_Primitive, _super);
  23704. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  23705. this._beingRegenerated = true;
  23706. this._canBeRegenerated = canBeRegenerated;
  23707. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  23708. this._beingRegenerated = false;
  23709. }
  23710. _Primitive.prototype.canBeRegenerated = function () {
  23711. return this._canBeRegenerated;
  23712. };
  23713. _Primitive.prototype.regenerate = function () {
  23714. if (!this._canBeRegenerated) {
  23715. return;
  23716. }
  23717. this._beingRegenerated = true;
  23718. this.setAllVerticesData(this._regenerateVertexData(), false);
  23719. this._beingRegenerated = false;
  23720. };
  23721. _Primitive.prototype.asNewGeometry = function (id) {
  23722. return _super.prototype.copy.call(this, id);
  23723. };
  23724. // overrides
  23725. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  23726. if (!this._beingRegenerated) {
  23727. return;
  23728. }
  23729. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  23730. };
  23731. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  23732. if (!this._beingRegenerated) {
  23733. return;
  23734. }
  23735. _super.prototype.setVerticesData.call(this, kind, data, false);
  23736. };
  23737. // to override
  23738. // protected
  23739. _Primitive.prototype._regenerateVertexData = function () {
  23740. throw new Error("Abstract method");
  23741. };
  23742. _Primitive.prototype.copy = function (id) {
  23743. throw new Error("Must be overriden in sub-classes.");
  23744. };
  23745. return _Primitive;
  23746. })(Geometry);
  23747. Primitives._Primitive = _Primitive;
  23748. var Box = (function (_super) {
  23749. __extends(Box, _super);
  23750. function Box(id, scene, size, canBeRegenerated, mesh) {
  23751. this.size = size;
  23752. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23753. }
  23754. Box.prototype._regenerateVertexData = function () {
  23755. return BABYLON.VertexData.CreateBox(this.size);
  23756. };
  23757. Box.prototype.copy = function (id) {
  23758. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23759. };
  23760. return Box;
  23761. })(_Primitive);
  23762. Primitives.Box = Box;
  23763. var Sphere = (function (_super) {
  23764. __extends(Sphere, _super);
  23765. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  23766. this.segments = segments;
  23767. this.diameter = diameter;
  23768. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23769. }
  23770. Sphere.prototype._regenerateVertexData = function () {
  23771. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  23772. };
  23773. Sphere.prototype.copy = function (id) {
  23774. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  23775. };
  23776. return Sphere;
  23777. })(_Primitive);
  23778. Primitives.Sphere = Sphere;
  23779. var Cylinder = (function (_super) {
  23780. __extends(Cylinder, _super);
  23781. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  23782. if (subdivisions === void 0) { subdivisions = 1; }
  23783. this.height = height;
  23784. this.diameterTop = diameterTop;
  23785. this.diameterBottom = diameterBottom;
  23786. this.tessellation = tessellation;
  23787. this.subdivisions = subdivisions;
  23788. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23789. }
  23790. Cylinder.prototype._regenerateVertexData = function () {
  23791. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  23792. };
  23793. Cylinder.prototype.copy = function (id) {
  23794. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  23795. };
  23796. return Cylinder;
  23797. })(_Primitive);
  23798. Primitives.Cylinder = Cylinder;
  23799. var Torus = (function (_super) {
  23800. __extends(Torus, _super);
  23801. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  23802. this.diameter = diameter;
  23803. this.thickness = thickness;
  23804. this.tessellation = tessellation;
  23805. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23806. }
  23807. Torus.prototype._regenerateVertexData = function () {
  23808. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  23809. };
  23810. Torus.prototype.copy = function (id) {
  23811. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  23812. };
  23813. return Torus;
  23814. })(_Primitive);
  23815. Primitives.Torus = Torus;
  23816. var Ground = (function (_super) {
  23817. __extends(Ground, _super);
  23818. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  23819. this.width = width;
  23820. this.height = height;
  23821. this.subdivisions = subdivisions;
  23822. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23823. }
  23824. Ground.prototype._regenerateVertexData = function () {
  23825. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  23826. };
  23827. Ground.prototype.copy = function (id) {
  23828. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  23829. };
  23830. return Ground;
  23831. })(_Primitive);
  23832. Primitives.Ground = Ground;
  23833. var TiledGround = (function (_super) {
  23834. __extends(TiledGround, _super);
  23835. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  23836. this.xmin = xmin;
  23837. this.zmin = zmin;
  23838. this.xmax = xmax;
  23839. this.zmax = zmax;
  23840. this.subdivisions = subdivisions;
  23841. this.precision = precision;
  23842. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23843. }
  23844. TiledGround.prototype._regenerateVertexData = function () {
  23845. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  23846. };
  23847. TiledGround.prototype.copy = function (id) {
  23848. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  23849. };
  23850. return TiledGround;
  23851. })(_Primitive);
  23852. Primitives.TiledGround = TiledGround;
  23853. var Plane = (function (_super) {
  23854. __extends(Plane, _super);
  23855. function Plane(id, scene, size, canBeRegenerated, mesh) {
  23856. this.size = size;
  23857. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23858. }
  23859. Plane.prototype._regenerateVertexData = function () {
  23860. return BABYLON.VertexData.CreatePlane(this.size);
  23861. };
  23862. Plane.prototype.copy = function (id) {
  23863. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23864. };
  23865. return Plane;
  23866. })(_Primitive);
  23867. Primitives.Plane = Plane;
  23868. var TorusKnot = (function (_super) {
  23869. __extends(TorusKnot, _super);
  23870. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  23871. this.radius = radius;
  23872. this.tube = tube;
  23873. this.radialSegments = radialSegments;
  23874. this.tubularSegments = tubularSegments;
  23875. this.p = p;
  23876. this.q = q;
  23877. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23878. }
  23879. TorusKnot.prototype._regenerateVertexData = function () {
  23880. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  23881. };
  23882. TorusKnot.prototype.copy = function (id) {
  23883. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  23884. };
  23885. return TorusKnot;
  23886. })(_Primitive);
  23887. Primitives.TorusKnot = TorusKnot;
  23888. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  23889. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  23890. })(BABYLON || (BABYLON = {}));
  23891. //# sourceMappingURL=babylon.geometry.js.map
  23892. var BABYLON;
  23893. (function (BABYLON) {
  23894. var Gamepads = (function () {
  23895. function Gamepads(ongamedpadconnected) {
  23896. var _this = this;
  23897. this.babylonGamepads = [];
  23898. this.oneGamepadConnected = false;
  23899. this.isMonitoring = false;
  23900. this.gamepadEventSupported = 'GamepadEvent' in window;
  23901. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  23902. this.buttonADataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAA9aSURBVHja7FtpbBzneX7m3otcihSpm9Z9UJalxPKhVLZlp6ktNzEaxE0CtAnQAgnSoPWPBi3syuiPwordFi5Qt2haFygCoylSV4Vby6os1I3kOLYrS65kXXQoypJJSaFEUTyXy925+rzfzC6HFFlL1kpAIe7i5czO7H7zPs97ft8MtTAMcSu/dNzirxkCZgiYIWCGgBkCZgi4hV/mDR5fSxAt+0ZiX0ucDxMSTJLK+f83BFSA6TFgK75OclshouKBFbA+xaV4k7Z+fD6sNRlmjYFXQMu4NiUVS/oHe5/ecnHo3MYxd7QthN9UcsdW6FqEPwgDOFbqpAajL2VlTrTULzj4Ow8+s4+nipSxWMoxIUkyrl/pGswFtIR7WzHgDCX77K7vfHNkbOA+AryjYZadb27OIJdzCNZBKmXw4kbk35qPsTEfJbeEkZESentHMdBfGtY142gu1bDvqV/925f4tQJlNCaj4hXX7RHXS0AFuJEAXvfHr/zmk67vPjir0V68aFEe8xtuQ6O1FHlrEXLmHBiaDUtzYBlpNYjrF+GFZfhhCcPeBQy53ehzT+H8QBe6uwfRf7l8xjKsvX/y5X98jl8fThDhJ4i46QQkrS5I6v7oX7/++77vPtLUlFnZtnIRlubvxRxnHbJmE79sxD/SqG0oZk8MFarRqufUkQAFrxcXSkfx0eB+nOggKX2jHYZhvf79r/z4L2IiipO84aYRkASfefnAX695p3P3c9mM/UufuaMVdzRvxVx7A0xaWdOMqVULJ6Z3TZv6KmHo0ztK6CkfxpHe3Th0pAuF0fLbn1u+9cmv3vW77bE3fGoSPi0BVfAvvPEHm9rPv//iooWz5m9Z/wCWZx+Go9UrN48QTD9IGMZ1cJIzTPisRQclPMrhME4W9mDfB2+i+2z/+TXz7/z2E7/85+9OIuGGE6BV3H77zm/d33nx6Ktr18zFg2t+DQude2n1tLJ8tcJ90vDhpG5Am7qTkJAQErywiLOld7G3/d9xvL0Hy1vWPbbtS3//00Q4hDeaAFXintrx1fu7+jp2r13bgofX/gaazbVkJQdLT9P6VqRFDSu2hIgXlBUBLgtCr3cce47/CMePX0Rr08qtzz7+8k8TpfKGtcKq1jPZre7oObyjdWkGd628l7AXwvMCeL7HjO6qrS8S1E5kTE9tfbiur665ccU9EB1EF9Ep0WXesEZIJb9j5/b/XUtzNrt29Rw0og2lchmBVqLo8LSAHlCixbTpddGm8Y7pjkttCCUP+JQy3FiatNuxdvUx9F4ayopO/OL9sQeEN4oA/eHn577oWPbGVes11PsrUBxjDafze1Te1VzouqnK2TgmLQljQqmrnAsT+iaPVb5b2co7EC+QhBgUeM1R1AcrsGp9Jy6+4W8U3fZ8r+e3EnOI2uaAX3l+zgNB4O9rW5/B8tY5WGo9BtOrJ4uMfUl+uj0B8HTmPXj8Pex86xVEnTDBBSE2r78fX9i09RPyZfT2A5ceIMSPwDOH8JH7Kk5+fAHtR0Zh6MZ9e7534Wc3wgO0sXLhD9OpFOa0egjGMhguD8BgTJooMfPbV1h/umz25ondcFP90IzY2iTgrfY9uH31aqSc9CeSEHkBEyITv28M8XMGc2/z0HGCpWCs8BS/9sWrDYOrJuCBZ+vu5sUfXbicia5kYGzUw4DWTwJKbApSjHuTBBjT2H68zg0MD4KlEwabZi0Y7wd85u/3O9/B6sVrPlEXeiF9nMmRxPt6Qf4y/HyIbh3HwkdF1zefGt5fUwK8wP2WAGwh02MFE/5ogYr3Qg/STL0W3d8aB1ppa+Pw0uI2Tz6/134Mg+UoIGZlZ2HMLaJYHkPICr6//RBamvPj/UA4dYKsegGrXqAXMaqNsDT6SreOY5Gu/FptCeBFN+caAphGiKFiGaOjA3AJHoGt6r7GgNbjqjo5yQkBUVHQ8PaJExjiaZ2yue12nO27gCNdHSptvf/xGdw11I2UZSmvCIJgQiJMhoEfeqpNDvUSRvUB5hMX9fUecg0aBi+Hm2uaAz633bmbm1VN8+h07LfKJdkOkQB2fL4BTlsj8No4YLG2putMSjwjp3QNvZdH8YsiExV501isFjU30lpF7D8dVfCA8sFHp7BuWYtaIwiCsCrCSDVhh9IX8k0CoHsoMQ84FrfFAE3zQAK0VaLzO9tK79XKAxSj+aYALt3XLfNipZD1v492YexrE/sP0zBgUIQIoYaflAXbz16CzyY6YKqYl8uheTarRioD7xAxCQHUpv18L1Yud+Iloujtk4zQo9WZcKURqjbHclzKvj0Gvcw8UA6oY2WqonSuGQGb5I+TJgEFEsB4daXzc0eopabcX13W0BXwgAnRZL4Q62s8ppnR/pFz/QjF+tRvxeIsY/cizGwRt83P4czACL8HdA1JUivCNGVogvdkNkgaGDNe4CvXFyJ8n+B5XGLJ1FmJXJ53AzjZKgGbatkKL5c/liNWIPO8uM/4VO2uKCQZjLmBqQAGJ4EmI8NMabDTOuyUobYXmPlCEpiqA1IkYdWSBpjpEDl6wsrF9aAjqHNOPXDyXAGprAknY5B0btOGGk/GlfE1taqofCNuuYNIJ+omOiZ1rpUHtEYWjkpWoP5EWV2sb5isA7aIQTHHxaIniNADui8PIs0Eb6SY/Z0UQc+j+mXYuoM7Vy/Age7zkBUyCZGLhRLSOYcWpfXFA1wPhqup8JNKq5UkKeoqSHxPLSoqnUQtw5ioc60IyE/VkOji8mYE2nZELNgCXLaOkGDFJBg4OzCMDEcxCfAzS1pQX5fHSNDLClLGwmwzls6vQ09hGFJYegdZ1hha2bqIBNelB5Qjog02TzpFNVEquYpMuTSYr/lcQPKPJHoRQ8W1GYO3lDgpO9pPWTEZEQGnuodg5Hyk66Lyd8fKOQQ6gqyWict7GeuWz8HQyWEFw+bB7ksF3Nk2V1nfpZTLQqSLslzXlDmHpsQ1osVoy/Solwf/GpdErpaAQUqjWxL2GWcWaSfAMIis7RBwiuCdtD1OgmNHBJCg7r4uZBnbdjaaq+3YewB+USYicY8juYPnMtloqdCjG3f39eO+3JKIAFadSiiZigBdgdcqItMxsmZbIbvUIKlzzQjoEgLGRjU2KTp8AjRCkzEnAG0mtQh8Ku0oAqok8JzP+Lw0MkB3jpKjKpapaL5WKZxafDdBqoC6O8LtyMAQhoZdzG7MwLU8FUYKPINcl+qimismRj26v2I71I3jDxfdpM41I6CTsmG4X0djKyc8RYu9t0Vl2QJbBJ5xFPiICJIg1hdhR3fs5HnWeldleZXABLA98b7Y5HtjkgwNEtbTN4iFC5oI3I1CTsAbsfVjAizJB3Qbx9HphRp6eqr3TDprSYA0FI/3ntOxbpUNM2OjpEcE6HYEWkhIKw+ICeBxi+T09F1WZU+iJq2n8fRDf4Ymu3XSrcOIgg8H9uOFn31fNUVC0oddZ7B5YxtDwlTgo66SEici2fokwCJjju0hw7J54WypQsB7tSRAza+H+nld30Y+m2b7SS+Qn9PKFl1egRciHIfWpxC8x+7tdA97+3zUcNyWX4Ci/THOoD2x/hmlQTox+3gDjWYeg/4gmF853xjBpUsjaGnJR24fu36FNzX5pmfY7EPStlSLIgb6gwk616QRYk8tS88/l/2PT/loyqbQkEmhPpNGNp1CmvtieQHvONGtL4sdy9Hjp5kkpTWmSzM7L529hErHs0cCpt2qW00BymDV3JXSU8HkAXKIjtNnedxS48m4Mr5cR9YlMrx+XTqNRmbP2ZkMOjvHKir/PNa5pouiitFjH44iZ6YwO5tFAy+eo6SdpOUJyhBQTJR+HT9HYLJaFve0PqQmTQLaVOCdmIRIWE+wrmWTzG8iAugF7qgWjSWkGbYa32EjJQTkGFv5dBZNJKCeHdb77UPXZP1rWhKLZ4Rqjv2Fz86lLMNlpusCY9BnqTNUIyTgrVhhs7rVq2KoW2TSxWlXLOCqWX4svmpzZdEjWvgQcdVWPnu+i4ClUS+HyLIFnsVf/9eBduw8eKYy2D1XMxO8Jg+IB9wl+3s/uAC3qKMpXY88m/ecnUHaSis3Na8Ab1UtaCh3j1y+sm8m9o0J+9Fv9MR4Zhw6DufTWasOebsOs+xZKHJOtvtQtertulrwV+0BtH5yWvyW7CxubsCTX9+KUQZ4ga7qmdGUFmrya8QWHwcxlReMF8Mw4QETrR8oy7tq2ivH5Tvya8n8aXZMGc4An/nRDpy52FfR8b5KCJCImt8YkYF/KDtnegfwz3sPodGajQajCTk9z/4mQ6iphMWv9AA9IeMWdyYdn+gBkVc5amwHWV6lHvVaI2YZzfinN95Ngv/htcT/p31CRNbdV8l8e++xD5HPNeHxhx5Bgf18kTN5T1kvjBfEjGjBJCai4gnjHqAnlvqS8e9NeujEjEul/NokDbai4V/2voafHD1S0evdWLeb8ojMNyly5fS//ffbcD0L33j4K4RX4rtMh/UUGLXmr6BWXN9MEFAhYfzmZ6hcXI+TpISRH8061Ui68gTWGUJP4aU9P8ZrB39S+Xkx1ummPSMkbebnJcxU1jm4D5eGhvB7j32HJcpUJHhxLIfxTZpxwGa8eKrHC51a9Tmp+N5P1RsQ01cJAwEflHw8/+pfYn/HgaQ+n7/a1vd6k+BUS2XvVD401TXhu488gQ0r71QUuLJsrWT8mSYtfkBMm0BAmFhNrgDX4oRqqeaJMw4c6TyIv/qPP0Xf8KUJ6sXuP1XluuEEyGsD5TXKgsqBNQvW4RtbnkDb4ttJQlGt/IQqLMJE7tWqOSBZCSrL6dFSqq3AnzhzDC/tewHt5w4nr3suvgN0+P8o3TeegFe3vYDHtj+xhLt/Q3kkeW5d693YuuHXsWHZPcixW4tCwo+trVU9QEs8G6HFqW5kdBiHTu3H64dfxpGuK8r665Tv7tz2D6e/tP23cT0E1OA5QR2iiIbs1i9u/9qTPPC12CtwlIofjZVvW/BZ3LVsC5bPW4u5DQuxaPay2NpRIuy61IkLA+dw8hdHceDUPpw49z9TXUysvWPXtl3bQ4yQtMJ1a18DAsbvRO/atvM5DXXPPbp9yzP8+GXBXTkngKYBdTWvE5RXdm87+HQEfLh2T57UIAdM95Js9+04LKSDbLzG31+Omxpx9xfxKR6AukkhMP0aKuUHsag5VEzE3fGSddsUVu6KFzIE+H/iJry0mX+bu8VfMwTMEDBDwAwBMwTMEHALv/5XgAEASpR5N6rB30UAAAAASUVORK5CYII=";
  23903. this._callbackGamepadConnected = ongamedpadconnected;
  23904. if (this.gamepadSupportAvailable) {
  23905. // Checking if the gamepad connected event is supported (like in Firefox)
  23906. if (this.gamepadEventSupported) {
  23907. window.addEventListener('gamepadconnected', function (evt) {
  23908. _this._onGamepadConnected(evt);
  23909. }, false);
  23910. window.addEventListener('gamepaddisconnected', function (evt) {
  23911. _this._onGamepadDisconnected(evt);
  23912. }, false);
  23913. }
  23914. else {
  23915. this._startMonitoringGamepads();
  23916. }
  23917. if (!this.oneGamepadConnected) {
  23918. this._insertGamepadDOMInstructions();
  23919. }
  23920. }
  23921. else {
  23922. this._insertGamepadDOMNotSupported();
  23923. }
  23924. }
  23925. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  23926. Gamepads.gamepadDOMInfo = document.createElement("div");
  23927. var buttonAImage = document.createElement("img");
  23928. buttonAImage.src = this.buttonADataURL;
  23929. var spanMessage = document.createElement("span");
  23930. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  23931. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  23932. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23933. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23934. Gamepads.gamepadDOMInfo.style.width = "100%";
  23935. Gamepads.gamepadDOMInfo.style.height = "48px";
  23936. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23937. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23938. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23939. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23940. buttonAImage.style.position = "relative";
  23941. buttonAImage.style.bottom = "8px";
  23942. spanMessage.style.position = "relative";
  23943. spanMessage.style.fontSize = "32px";
  23944. spanMessage.style.bottom = "32px";
  23945. spanMessage.style.color = "green";
  23946. document.body.appendChild(Gamepads.gamepadDOMInfo);
  23947. };
  23948. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  23949. Gamepads.gamepadDOMInfo = document.createElement("div");
  23950. var spanMessage = document.createElement("span");
  23951. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  23952. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23953. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23954. Gamepads.gamepadDOMInfo.style.width = "100%";
  23955. Gamepads.gamepadDOMInfo.style.height = "40px";
  23956. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23957. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23958. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23959. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23960. spanMessage.style.position = "relative";
  23961. spanMessage.style.fontSize = "32px";
  23962. spanMessage.style.color = "red";
  23963. document.body.appendChild(Gamepads.gamepadDOMInfo);
  23964. };
  23965. Gamepads.prototype.dispose = function () {
  23966. document.body.removeChild(Gamepads.gamepadDOMInfo);
  23967. };
  23968. Gamepads.prototype._onGamepadConnected = function (evt) {
  23969. var newGamepad = this._addNewGamepad(evt.gamepad);
  23970. if (this._callbackGamepadConnected)
  23971. this._callbackGamepadConnected(newGamepad);
  23972. this._startMonitoringGamepads();
  23973. };
  23974. Gamepads.prototype._addNewGamepad = function (gamepad) {
  23975. if (!this.oneGamepadConnected) {
  23976. this.oneGamepadConnected = true;
  23977. if (Gamepads.gamepadDOMInfo) {
  23978. document.body.removeChild(Gamepads.gamepadDOMInfo);
  23979. Gamepads.gamepadDOMInfo = null;
  23980. }
  23981. }
  23982. var newGamepad;
  23983. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  23984. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  23985. }
  23986. else {
  23987. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  23988. }
  23989. this.babylonGamepads.push(newGamepad);
  23990. return newGamepad;
  23991. };
  23992. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  23993. for (var i in this.babylonGamepads) {
  23994. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  23995. this.babylonGamepads.splice(i, 1);
  23996. break;
  23997. }
  23998. }
  23999. // If no gamepads are left, stop the polling loop.
  24000. if (this.babylonGamepads.length == 0) {
  24001. this._stopMonitoringGamepads();
  24002. }
  24003. };
  24004. Gamepads.prototype._startMonitoringGamepads = function () {
  24005. if (!this.isMonitoring) {
  24006. this.isMonitoring = true;
  24007. this._checkGamepadsStatus();
  24008. }
  24009. };
  24010. Gamepads.prototype._stopMonitoringGamepads = function () {
  24011. this.isMonitoring = false;
  24012. };
  24013. Gamepads.prototype._checkGamepadsStatus = function () {
  24014. var _this = this;
  24015. // updating gamepad objects
  24016. this._updateGamepadObjects();
  24017. for (var i in this.babylonGamepads) {
  24018. this.babylonGamepads[i].update();
  24019. }
  24020. if (this.isMonitoring) {
  24021. if (window.requestAnimationFrame) {
  24022. window.requestAnimationFrame(function () {
  24023. _this._checkGamepadsStatus();
  24024. });
  24025. }
  24026. else if (window.mozRequestAnimationFrame) {
  24027. window.mozRequestAnimationFrame(function () {
  24028. _this._checkGamepadsStatus();
  24029. });
  24030. }
  24031. else if (window.webkitRequestAnimationFrame) {
  24032. window.webkitRequestAnimationFrame(function () {
  24033. _this._checkGamepadsStatus();
  24034. });
  24035. }
  24036. }
  24037. };
  24038. // This function is called only on Chrome, which does not yet support
  24039. // connection/disconnection events, but requires you to monitor
  24040. // an array for changes.
  24041. Gamepads.prototype._updateGamepadObjects = function () {
  24042. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  24043. for (var i = 0; i < gamepads.length; i++) {
  24044. if (gamepads[i]) {
  24045. if (!(gamepads[i].index in this.babylonGamepads)) {
  24046. var newGamepad = this._addNewGamepad(gamepads[i]);
  24047. if (this._callbackGamepadConnected) {
  24048. this._callbackGamepadConnected(newGamepad);
  24049. }
  24050. }
  24051. else {
  24052. this.babylonGamepads[i].browserGamepad = gamepads[i];
  24053. }
  24054. }
  24055. }
  24056. };
  24057. return Gamepads;
  24058. })();
  24059. BABYLON.Gamepads = Gamepads;
  24060. var StickValues = (function () {
  24061. function StickValues(x, y) {
  24062. this.x = x;
  24063. this.y = y;
  24064. }
  24065. return StickValues;
  24066. })();
  24067. BABYLON.StickValues = StickValues;
  24068. var Gamepad = (function () {
  24069. function Gamepad(id, index, browserGamepad) {
  24070. this.id = id;
  24071. this.index = index;
  24072. this.browserGamepad = browserGamepad;
  24073. if (this.browserGamepad.axes.length >= 2) {
  24074. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24075. }
  24076. if (this.browserGamepad.axes.length >= 4) {
  24077. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24078. }
  24079. }
  24080. Gamepad.prototype.onleftstickchanged = function (callback) {
  24081. this._onleftstickchanged = callback;
  24082. };
  24083. Gamepad.prototype.onrightstickchanged = function (callback) {
  24084. this._onrightstickchanged = callback;
  24085. };
  24086. Object.defineProperty(Gamepad.prototype, "leftStick", {
  24087. get: function () {
  24088. return this._leftStick;
  24089. },
  24090. set: function (newValues) {
  24091. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  24092. this._onleftstickchanged(newValues);
  24093. }
  24094. this._leftStick = newValues;
  24095. },
  24096. enumerable: true,
  24097. configurable: true
  24098. });
  24099. Object.defineProperty(Gamepad.prototype, "rightStick", {
  24100. get: function () {
  24101. return this._rightStick;
  24102. },
  24103. set: function (newValues) {
  24104. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  24105. this._onrightstickchanged(newValues);
  24106. }
  24107. this._rightStick = newValues;
  24108. },
  24109. enumerable: true,
  24110. configurable: true
  24111. });
  24112. Gamepad.prototype.update = function () {
  24113. if (this._leftStick) {
  24114. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24115. }
  24116. if (this._rightStick) {
  24117. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24118. }
  24119. };
  24120. return Gamepad;
  24121. })();
  24122. BABYLON.Gamepad = Gamepad;
  24123. var GenericPad = (function (_super) {
  24124. __extends(GenericPad, _super);
  24125. function GenericPad(id, index, gamepad) {
  24126. _super.call(this, id, index, gamepad);
  24127. this.id = id;
  24128. this.index = index;
  24129. this.gamepad = gamepad;
  24130. this._buttons = new Array(gamepad.buttons.length);
  24131. }
  24132. GenericPad.prototype.onbuttondown = function (callback) {
  24133. this._onbuttondown = callback;
  24134. };
  24135. GenericPad.prototype.onbuttonup = function (callback) {
  24136. this._onbuttonup = callback;
  24137. };
  24138. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  24139. if (newValue !== currentValue) {
  24140. if (this._onbuttondown && newValue === 1) {
  24141. this._onbuttondown(buttonIndex);
  24142. }
  24143. if (this._onbuttonup && newValue === 0) {
  24144. this._onbuttonup(buttonIndex);
  24145. }
  24146. }
  24147. return newValue;
  24148. };
  24149. GenericPad.prototype.update = function () {
  24150. _super.prototype.update.call(this);
  24151. for (var index = 0; index < this._buttons.length; index++) {
  24152. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  24153. }
  24154. };
  24155. return GenericPad;
  24156. })(Gamepad);
  24157. BABYLON.GenericPad = GenericPad;
  24158. (function (Xbox360Button) {
  24159. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  24160. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  24161. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  24162. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  24163. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  24164. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  24165. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  24166. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  24167. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  24168. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  24169. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  24170. var Xbox360Button = BABYLON.Xbox360Button;
  24171. (function (Xbox360Dpad) {
  24172. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  24173. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  24174. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  24175. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  24176. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  24177. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  24178. var Xbox360Pad = (function (_super) {
  24179. __extends(Xbox360Pad, _super);
  24180. function Xbox360Pad() {
  24181. _super.apply(this, arguments);
  24182. this._leftTrigger = 0;
  24183. this._rightTrigger = 0;
  24184. this._buttonA = 0;
  24185. this._buttonB = 0;
  24186. this._buttonX = 0;
  24187. this._buttonY = 0;
  24188. this._buttonBack = 0;
  24189. this._buttonStart = 0;
  24190. this._buttonLB = 0;
  24191. this._buttonRB = 0;
  24192. this._buttonLeftStick = 0;
  24193. this._buttonRightStick = 0;
  24194. this._dPadUp = 0;
  24195. this._dPadDown = 0;
  24196. this._dPadLeft = 0;
  24197. this._dPadRight = 0;
  24198. }
  24199. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  24200. this._onlefttriggerchanged = callback;
  24201. };
  24202. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  24203. this._onrighttriggerchanged = callback;
  24204. };
  24205. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  24206. get: function () {
  24207. return this._leftTrigger;
  24208. },
  24209. set: function (newValue) {
  24210. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  24211. this._onlefttriggerchanged(newValue);
  24212. }
  24213. this._leftTrigger = newValue;
  24214. },
  24215. enumerable: true,
  24216. configurable: true
  24217. });
  24218. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  24219. get: function () {
  24220. return this._rightTrigger;
  24221. },
  24222. set: function (newValue) {
  24223. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  24224. this._onrighttriggerchanged(newValue);
  24225. }
  24226. this._rightTrigger = newValue;
  24227. },
  24228. enumerable: true,
  24229. configurable: true
  24230. });
  24231. Xbox360Pad.prototype.onbuttondown = function (callback) {
  24232. this._onbuttondown = callback;
  24233. };
  24234. Xbox360Pad.prototype.onbuttonup = function (callback) {
  24235. this._onbuttonup = callback;
  24236. };
  24237. Xbox360Pad.prototype.ondpaddown = function (callback) {
  24238. this._ondpaddown = callback;
  24239. };
  24240. Xbox360Pad.prototype.ondpadup = function (callback) {
  24241. this._ondpadup = callback;
  24242. };
  24243. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  24244. if (newValue !== currentValue) {
  24245. if (this._onbuttondown && newValue === 1) {
  24246. this._onbuttondown(buttonType);
  24247. }
  24248. if (this._onbuttonup && newValue === 0) {
  24249. this._onbuttonup(buttonType);
  24250. }
  24251. }
  24252. return newValue;
  24253. };
  24254. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  24255. if (newValue !== currentValue) {
  24256. if (this._ondpaddown && newValue === 1) {
  24257. this._ondpaddown(buttonType);
  24258. }
  24259. if (this._ondpadup && newValue === 0) {
  24260. this._ondpadup(buttonType);
  24261. }
  24262. }
  24263. return newValue;
  24264. };
  24265. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  24266. get: function () {
  24267. return this._buttonA;
  24268. },
  24269. set: function (value) {
  24270. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  24271. },
  24272. enumerable: true,
  24273. configurable: true
  24274. });
  24275. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  24276. get: function () {
  24277. return this._buttonB;
  24278. },
  24279. set: function (value) {
  24280. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  24281. },
  24282. enumerable: true,
  24283. configurable: true
  24284. });
  24285. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  24286. get: function () {
  24287. return this._buttonX;
  24288. },
  24289. set: function (value) {
  24290. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  24291. },
  24292. enumerable: true,
  24293. configurable: true
  24294. });
  24295. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  24296. get: function () {
  24297. return this._buttonY;
  24298. },
  24299. set: function (value) {
  24300. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  24301. },
  24302. enumerable: true,
  24303. configurable: true
  24304. });
  24305. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  24306. get: function () {
  24307. return this._buttonStart;
  24308. },
  24309. set: function (value) {
  24310. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  24311. },
  24312. enumerable: true,
  24313. configurable: true
  24314. });
  24315. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  24316. get: function () {
  24317. return this._buttonBack;
  24318. },
  24319. set: function (value) {
  24320. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  24321. },
  24322. enumerable: true,
  24323. configurable: true
  24324. });
  24325. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  24326. get: function () {
  24327. return this._buttonLB;
  24328. },
  24329. set: function (value) {
  24330. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  24331. },
  24332. enumerable: true,
  24333. configurable: true
  24334. });
  24335. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  24336. get: function () {
  24337. return this._buttonRB;
  24338. },
  24339. set: function (value) {
  24340. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  24341. },
  24342. enumerable: true,
  24343. configurable: true
  24344. });
  24345. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  24346. get: function () {
  24347. return this._buttonLeftStick;
  24348. },
  24349. set: function (value) {
  24350. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  24351. },
  24352. enumerable: true,
  24353. configurable: true
  24354. });
  24355. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  24356. get: function () {
  24357. return this._buttonRightStick;
  24358. },
  24359. set: function (value) {
  24360. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  24361. },
  24362. enumerable: true,
  24363. configurable: true
  24364. });
  24365. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  24366. get: function () {
  24367. return this._dPadUp;
  24368. },
  24369. set: function (value) {
  24370. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  24371. },
  24372. enumerable: true,
  24373. configurable: true
  24374. });
  24375. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  24376. get: function () {
  24377. return this._dPadDown;
  24378. },
  24379. set: function (value) {
  24380. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  24381. },
  24382. enumerable: true,
  24383. configurable: true
  24384. });
  24385. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  24386. get: function () {
  24387. return this._dPadLeft;
  24388. },
  24389. set: function (value) {
  24390. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  24391. },
  24392. enumerable: true,
  24393. configurable: true
  24394. });
  24395. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  24396. get: function () {
  24397. return this._dPadRight;
  24398. },
  24399. set: function (value) {
  24400. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  24401. },
  24402. enumerable: true,
  24403. configurable: true
  24404. });
  24405. Xbox360Pad.prototype.update = function () {
  24406. _super.prototype.update.call(this);
  24407. this.buttonA = this.browserGamepad.buttons[0].value;
  24408. this.buttonB = this.browserGamepad.buttons[1].value;
  24409. this.buttonX = this.browserGamepad.buttons[2].value;
  24410. this.buttonY = this.browserGamepad.buttons[3].value;
  24411. this.buttonLB = this.browserGamepad.buttons[4].value;
  24412. this.buttonRB = this.browserGamepad.buttons[5].value;
  24413. this.leftTrigger = this.browserGamepad.buttons[6].value;
  24414. this.rightTrigger = this.browserGamepad.buttons[7].value;
  24415. this.buttonBack = this.browserGamepad.buttons[8].value;
  24416. this.buttonStart = this.browserGamepad.buttons[9].value;
  24417. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  24418. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  24419. this.dPadUp = this.browserGamepad.buttons[12].value;
  24420. this.dPadDown = this.browserGamepad.buttons[13].value;
  24421. this.dPadLeft = this.browserGamepad.buttons[14].value;
  24422. this.dPadRight = this.browserGamepad.buttons[15].value;
  24423. };
  24424. return Xbox360Pad;
  24425. })(Gamepad);
  24426. BABYLON.Xbox360Pad = Xbox360Pad;
  24427. })(BABYLON || (BABYLON = {}));
  24428. //# sourceMappingURL=babylon.gamepads.js.map
  24429. var BABYLON;
  24430. (function (BABYLON) {
  24431. // We're mainly based on the logic defined into the FreeCamera code
  24432. var GamepadCamera = (function (_super) {
  24433. __extends(GamepadCamera, _super);
  24434. function GamepadCamera(name, position, scene) {
  24435. var _this = this;
  24436. _super.call(this, name, position, scene);
  24437. this.angularSensibility = 200;
  24438. this.moveSensibility = 75;
  24439. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  24440. _this._onNewGameConnected(gamepad);
  24441. });
  24442. }
  24443. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  24444. // Only the first gamepad can control the camera
  24445. if (gamepad.index === 0) {
  24446. this._gamepad = gamepad;
  24447. }
  24448. };
  24449. GamepadCamera.prototype._checkInputs = function () {
  24450. if (!this._gamepad) {
  24451. return;
  24452. }
  24453. var LSValues = this._gamepad.leftStick;
  24454. var normalizedLX = LSValues.x / this.moveSensibility;
  24455. var normalizedLY = LSValues.y / this.moveSensibility;
  24456. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  24457. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  24458. var RSValues = this._gamepad.rightStick;
  24459. var normalizedRX = RSValues.x / this.angularSensibility;
  24460. var normalizedRY = RSValues.y / this.angularSensibility;
  24461. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  24462. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  24463. ;
  24464. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24465. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  24466. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24467. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  24468. };
  24469. GamepadCamera.prototype.dispose = function () {
  24470. this._gamepads.dispose();
  24471. _super.prototype.dispose.call(this);
  24472. };
  24473. return GamepadCamera;
  24474. })(BABYLON.FreeCamera);
  24475. BABYLON.GamepadCamera = GamepadCamera;
  24476. })(BABYLON || (BABYLON = {}));
  24477. //# sourceMappingURL=babylon.gamepadCamera.js.map
  24478. var BABYLON;
  24479. (function (BABYLON) {
  24480. var LinesMesh = (function (_super) {
  24481. __extends(LinesMesh, _super);
  24482. function LinesMesh(name, scene, updatable) {
  24483. if (updatable === void 0) { updatable = false; }
  24484. _super.call(this, name, scene);
  24485. this.color = new BABYLON.Color3(1, 1, 1);
  24486. this.alpha = 1;
  24487. this._indices = new Array();
  24488. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  24489. attributes: ["position"],
  24490. uniforms: ["worldViewProjection", "color"],
  24491. needAlphaBlending: true
  24492. });
  24493. }
  24494. Object.defineProperty(LinesMesh.prototype, "material", {
  24495. get: function () {
  24496. return this._colorShader;
  24497. },
  24498. enumerable: true,
  24499. configurable: true
  24500. });
  24501. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  24502. get: function () {
  24503. return false;
  24504. },
  24505. enumerable: true,
  24506. configurable: true
  24507. });
  24508. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  24509. get: function () {
  24510. return false;
  24511. },
  24512. enumerable: true,
  24513. configurable: true
  24514. });
  24515. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  24516. var engine = this.getScene().getEngine();
  24517. var indexToBind = this._geometry.getIndexBuffer();
  24518. // VBOs
  24519. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  24520. // Color
  24521. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  24522. };
  24523. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  24524. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24525. return;
  24526. }
  24527. var engine = this.getScene().getEngine();
  24528. // Draw order
  24529. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  24530. };
  24531. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  24532. return null;
  24533. };
  24534. LinesMesh.prototype.dispose = function (doNotRecurse) {
  24535. this._colorShader.dispose();
  24536. _super.prototype.dispose.call(this, doNotRecurse);
  24537. };
  24538. return LinesMesh;
  24539. })(BABYLON.Mesh);
  24540. BABYLON.LinesMesh = LinesMesh;
  24541. })(BABYLON || (BABYLON = {}));
  24542. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  24543. (function (BABYLON) {
  24544. var OutlineRenderer = (function () {
  24545. function OutlineRenderer(scene) {
  24546. this._scene = scene;
  24547. }
  24548. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  24549. if (useOverlay === void 0) { useOverlay = false; }
  24550. var scene = this._scene;
  24551. var engine = this._scene.getEngine();
  24552. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24553. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  24554. return;
  24555. }
  24556. var mesh = subMesh.getRenderingMesh();
  24557. var material = subMesh.getMaterial();
  24558. engine.enableEffect(this._effect);
  24559. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  24560. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  24561. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24562. // Bones
  24563. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  24564. if (useBones) {
  24565. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24566. }
  24567. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  24568. // Alpha test
  24569. if (material && material.needAlphaTesting()) {
  24570. var alphaTexture = material.getAlphaTestTexture();
  24571. this._effect.setTexture("diffuseSampler", alphaTexture);
  24572. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  24573. }
  24574. if (hardwareInstancedRendering) {
  24575. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  24576. }
  24577. else {
  24578. if (batch.renderSelf[subMesh._id]) {
  24579. this._effect.setMatrix("world", mesh.getWorldMatrix());
  24580. // Draw
  24581. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  24582. }
  24583. if (batch.visibleInstances[subMesh._id]) {
  24584. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  24585. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  24586. this._effect.setMatrix("world", instance.getWorldMatrix());
  24587. // Draw
  24588. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  24589. }
  24590. }
  24591. }
  24592. };
  24593. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  24594. var defines = [];
  24595. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  24596. var mesh = subMesh.getMesh();
  24597. var material = subMesh.getMaterial();
  24598. // Alpha test
  24599. if (material && material.needAlphaTesting()) {
  24600. defines.push("#define ALPHATEST");
  24601. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24602. attribs.push(BABYLON.VertexBuffer.UVKind);
  24603. defines.push("#define UV1");
  24604. }
  24605. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24606. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  24607. defines.push("#define UV2");
  24608. }
  24609. }
  24610. // Bones
  24611. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24612. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24613. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24614. defines.push("#define BONES");
  24615. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24616. }
  24617. // Instances
  24618. if (useInstances) {
  24619. defines.push("#define INSTANCES");
  24620. attribs.push("world0");
  24621. attribs.push("world1");
  24622. attribs.push("world2");
  24623. attribs.push("world3");
  24624. }
  24625. // Get correct effect
  24626. var join = defines.join("\n");
  24627. if (this._cachedDefines != join) {
  24628. this._cachedDefines = join;
  24629. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  24630. }
  24631. return this._effect.isReady();
  24632. };
  24633. return OutlineRenderer;
  24634. })();
  24635. BABYLON.OutlineRenderer = OutlineRenderer;
  24636. })(BABYLON || (BABYLON = {}));
  24637. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  24638. (function (BABYLON) {
  24639. var MeshAssetTask = (function () {
  24640. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  24641. this.name = name;
  24642. this.meshesNames = meshesNames;
  24643. this.rootUrl = rootUrl;
  24644. this.sceneFilename = sceneFilename;
  24645. this.isCompleted = false;
  24646. }
  24647. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24648. var _this = this;
  24649. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  24650. _this.loadedMeshes = meshes;
  24651. _this.loadedParticleSystems = particleSystems;
  24652. _this.loadedSkeletons = skeletons;
  24653. _this.isCompleted = true;
  24654. if (_this.onSuccess) {
  24655. _this.onSuccess(_this);
  24656. }
  24657. onSuccess();
  24658. }, null, function () {
  24659. if (_this.onError) {
  24660. _this.onError(_this);
  24661. }
  24662. onError();
  24663. });
  24664. };
  24665. return MeshAssetTask;
  24666. })();
  24667. BABYLON.MeshAssetTask = MeshAssetTask;
  24668. var TextFileAssetTask = (function () {
  24669. function TextFileAssetTask(name, url) {
  24670. this.name = name;
  24671. this.url = url;
  24672. this.isCompleted = false;
  24673. }
  24674. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24675. var _this = this;
  24676. BABYLON.Tools.LoadFile(this.url, function (data) {
  24677. _this.text = data;
  24678. _this.isCompleted = true;
  24679. if (_this.onSuccess) {
  24680. _this.onSuccess(_this);
  24681. }
  24682. onSuccess();
  24683. }, null, scene.database, false, function () {
  24684. if (_this.onError) {
  24685. _this.onError(_this);
  24686. }
  24687. onError();
  24688. });
  24689. };
  24690. return TextFileAssetTask;
  24691. })();
  24692. BABYLON.TextFileAssetTask = TextFileAssetTask;
  24693. var BinaryFileAssetTask = (function () {
  24694. function BinaryFileAssetTask(name, url) {
  24695. this.name = name;
  24696. this.url = url;
  24697. this.isCompleted = false;
  24698. }
  24699. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24700. var _this = this;
  24701. BABYLON.Tools.LoadFile(this.url, function (data) {
  24702. _this.data = data;
  24703. _this.isCompleted = true;
  24704. if (_this.onSuccess) {
  24705. _this.onSuccess(_this);
  24706. }
  24707. onSuccess();
  24708. }, null, scene.database, true, function () {
  24709. if (_this.onError) {
  24710. _this.onError(_this);
  24711. }
  24712. onError();
  24713. });
  24714. };
  24715. return BinaryFileAssetTask;
  24716. })();
  24717. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  24718. var ImageAssetTask = (function () {
  24719. function ImageAssetTask(name, url) {
  24720. this.name = name;
  24721. this.url = url;
  24722. this.isCompleted = false;
  24723. }
  24724. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24725. var _this = this;
  24726. var img = new Image();
  24727. img.onload = function () {
  24728. _this.image = img;
  24729. _this.isCompleted = true;
  24730. if (_this.onSuccess) {
  24731. _this.onSuccess(_this);
  24732. }
  24733. onSuccess();
  24734. };
  24735. img.onerror = function () {
  24736. if (_this.onError) {
  24737. _this.onError(_this);
  24738. }
  24739. onError();
  24740. };
  24741. img.src = this.url;
  24742. };
  24743. return ImageAssetTask;
  24744. })();
  24745. BABYLON.ImageAssetTask = ImageAssetTask;
  24746. var TextureAssetTask = (function () {
  24747. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  24748. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24749. this.name = name;
  24750. this.url = url;
  24751. this.noMipmap = noMipmap;
  24752. this.invertY = invertY;
  24753. this.samplingMode = samplingMode;
  24754. this.isCompleted = false;
  24755. }
  24756. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24757. var _this = this;
  24758. var onload = function () {
  24759. _this.isCompleted = true;
  24760. if (_this.onSuccess) {
  24761. _this.onSuccess(_this);
  24762. }
  24763. onSuccess();
  24764. };
  24765. var onerror = function () {
  24766. if (_this.onError) {
  24767. _this.onError(_this);
  24768. }
  24769. onError();
  24770. };
  24771. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  24772. };
  24773. return TextureAssetTask;
  24774. })();
  24775. BABYLON.TextureAssetTask = TextureAssetTask;
  24776. var AssetsManager = (function () {
  24777. function AssetsManager(scene) {
  24778. this._tasks = new Array();
  24779. this._waitingTasksCount = 0;
  24780. this.useDefaultLoadingScreen = true;
  24781. this._scene = scene;
  24782. }
  24783. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  24784. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  24785. this._tasks.push(task);
  24786. return task;
  24787. };
  24788. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  24789. var task = new TextFileAssetTask(taskName, url);
  24790. this._tasks.push(task);
  24791. return task;
  24792. };
  24793. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  24794. var task = new BinaryFileAssetTask(taskName, url);
  24795. this._tasks.push(task);
  24796. return task;
  24797. };
  24798. AssetsManager.prototype.addImageTask = function (taskName, url) {
  24799. var task = new ImageAssetTask(taskName, url);
  24800. this._tasks.push(task);
  24801. return task;
  24802. };
  24803. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  24804. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24805. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  24806. this._tasks.push(task);
  24807. return task;
  24808. };
  24809. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  24810. this._waitingTasksCount--;
  24811. if (this._waitingTasksCount === 0) {
  24812. if (this.onFinish) {
  24813. this.onFinish(this._tasks);
  24814. }
  24815. this._scene.getEngine().hideLoadingUI();
  24816. }
  24817. };
  24818. AssetsManager.prototype._runTask = function (task) {
  24819. var _this = this;
  24820. task.run(this._scene, function () {
  24821. if (_this.onTaskSuccess) {
  24822. _this.onTaskSuccess(task);
  24823. }
  24824. _this._decreaseWaitingTasksCount();
  24825. }, function () {
  24826. if (_this.onTaskError) {
  24827. _this.onTaskError(task);
  24828. }
  24829. _this._decreaseWaitingTasksCount();
  24830. });
  24831. };
  24832. AssetsManager.prototype.reset = function () {
  24833. this._tasks = new Array();
  24834. return this;
  24835. };
  24836. AssetsManager.prototype.load = function () {
  24837. this._waitingTasksCount = this._tasks.length;
  24838. if (this._waitingTasksCount === 0) {
  24839. if (this.onFinish) {
  24840. this.onFinish(this._tasks);
  24841. }
  24842. return this;
  24843. }
  24844. if (this.useDefaultLoadingScreen) {
  24845. this._scene.getEngine().displayLoadingUI();
  24846. }
  24847. for (var index = 0; index < this._tasks.length; index++) {
  24848. var task = this._tasks[index];
  24849. this._runTask(task);
  24850. }
  24851. return this;
  24852. };
  24853. return AssetsManager;
  24854. })();
  24855. BABYLON.AssetsManager = AssetsManager;
  24856. })(BABYLON || (BABYLON = {}));
  24857. //# sourceMappingURL=babylon.assetsManager.js.map
  24858. var BABYLON;
  24859. (function (BABYLON) {
  24860. var VRDeviceOrientationCamera = (function (_super) {
  24861. __extends(VRDeviceOrientationCamera, _super);
  24862. function VRDeviceOrientationCamera(name, position, scene) {
  24863. _super.call(this, name, position, scene);
  24864. this._alpha = 0;
  24865. this._beta = 0;
  24866. this._gamma = 0;
  24867. }
  24868. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  24869. this._alpha = +evt.alpha | 0;
  24870. this._beta = +evt.beta | 0;
  24871. this._gamma = +evt.gamma | 0;
  24872. if (this._gamma < 0) {
  24873. this._gamma = 90 + this._gamma;
  24874. }
  24875. else {
  24876. // Incline it in the correct angle.
  24877. this._gamma = 270 - this._gamma;
  24878. }
  24879. this.rotation.x = this._gamma / 180.0 * Math.PI;
  24880. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  24881. this.rotation.z = this._beta / 180.0 * Math.PI;
  24882. };
  24883. return VRDeviceOrientationCamera;
  24884. })(BABYLON.OculusCamera);
  24885. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  24886. })(BABYLON || (BABYLON = {}));
  24887. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  24888. var BABYLON;
  24889. (function (BABYLON) {
  24890. var WebVRCamera = (function (_super) {
  24891. __extends(WebVRCamera, _super);
  24892. function WebVRCamera(name, position, scene) {
  24893. _super.call(this, name, position, scene);
  24894. this._hmdDevice = null;
  24895. this._sensorDevice = null;
  24896. this._cacheState = null;
  24897. this._cacheQuaternion = new BABYLON.Quaternion();
  24898. this._cacheRotation = BABYLON.Vector3.Zero();
  24899. this._vrEnabled = false;
  24900. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  24901. }
  24902. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  24903. var size = devices.length;
  24904. var i = 0;
  24905. // Reset devices.
  24906. this._sensorDevice = null;
  24907. this._hmdDevice = null;
  24908. while (i < size && this._hmdDevice === null) {
  24909. if (devices[i] instanceof HMDVRDevice) {
  24910. this._hmdDevice = devices[i];
  24911. }
  24912. i++;
  24913. }
  24914. i = 0;
  24915. while (i < size && this._sensorDevice === null) {
  24916. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  24917. this._sensorDevice = devices[i];
  24918. }
  24919. i++;
  24920. }
  24921. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  24922. };
  24923. WebVRCamera.prototype._update = function () {
  24924. if (this._vrEnabled) {
  24925. this._cacheState = this._sensorDevice.getState();
  24926. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  24927. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  24928. this.rotation.x = -this._cacheRotation.z;
  24929. this.rotation.y = -this._cacheRotation.y;
  24930. this.rotation.z = this._cacheRotation.x;
  24931. }
  24932. _super.prototype._update.call(this);
  24933. };
  24934. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  24935. _super.prototype.attachControl.call(this, element, noPreventDefault);
  24936. if (navigator.getVRDevices) {
  24937. navigator.getVRDevices().then(this._getWebVRDevices);
  24938. }
  24939. else if (navigator.mozGetVRDevices) {
  24940. navigator.mozGetVRDevices(this._getWebVRDevices);
  24941. }
  24942. };
  24943. WebVRCamera.prototype.detachControl = function (element) {
  24944. _super.prototype.detachControl.call(this, element);
  24945. this._vrEnabled = false;
  24946. };
  24947. return WebVRCamera;
  24948. })(BABYLON.OculusCamera);
  24949. BABYLON.WebVRCamera = WebVRCamera;
  24950. })(BABYLON || (BABYLON = {}));
  24951. //# sourceMappingURL=babylon.webVRCamera.js.map
  24952. var BABYLON;
  24953. (function (BABYLON) {
  24954. // Standard optimizations
  24955. var SceneOptimization = (function () {
  24956. function SceneOptimization(priority) {
  24957. if (priority === void 0) { priority = 0; }
  24958. this.priority = priority;
  24959. this.apply = function (scene) {
  24960. return true; // Return true if everything that can be done was applied
  24961. };
  24962. }
  24963. return SceneOptimization;
  24964. })();
  24965. BABYLON.SceneOptimization = SceneOptimization;
  24966. var TextureOptimization = (function (_super) {
  24967. __extends(TextureOptimization, _super);
  24968. function TextureOptimization(priority, maximumSize) {
  24969. var _this = this;
  24970. if (priority === void 0) { priority = 0; }
  24971. if (maximumSize === void 0) { maximumSize = 1024; }
  24972. _super.call(this, priority);
  24973. this.priority = priority;
  24974. this.maximumSize = maximumSize;
  24975. this.apply = function (scene) {
  24976. var allDone = true;
  24977. for (var index = 0; index < scene.textures.length; index++) {
  24978. var texture = scene.textures[index];
  24979. if (!texture.canRescale) {
  24980. continue;
  24981. }
  24982. var currentSize = texture.getSize();
  24983. var maxDimension = Math.max(currentSize.width, currentSize.height);
  24984. if (maxDimension > _this.maximumSize) {
  24985. texture.scale(0.5);
  24986. allDone = false;
  24987. }
  24988. }
  24989. return allDone;
  24990. };
  24991. }
  24992. return TextureOptimization;
  24993. })(SceneOptimization);
  24994. BABYLON.TextureOptimization = TextureOptimization;
  24995. var HardwareScalingOptimization = (function (_super) {
  24996. __extends(HardwareScalingOptimization, _super);
  24997. function HardwareScalingOptimization(priority, maximumScale) {
  24998. var _this = this;
  24999. if (priority === void 0) { priority = 0; }
  25000. if (maximumScale === void 0) { maximumScale = 2; }
  25001. _super.call(this, priority);
  25002. this.priority = priority;
  25003. this.maximumScale = maximumScale;
  25004. this._currentScale = 1;
  25005. this.apply = function (scene) {
  25006. _this._currentScale++;
  25007. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  25008. return _this._currentScale >= _this.maximumScale;
  25009. };
  25010. }
  25011. return HardwareScalingOptimization;
  25012. })(SceneOptimization);
  25013. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  25014. var ShadowsOptimization = (function (_super) {
  25015. __extends(ShadowsOptimization, _super);
  25016. function ShadowsOptimization() {
  25017. _super.apply(this, arguments);
  25018. this.apply = function (scene) {
  25019. scene.shadowsEnabled = false;
  25020. return true;
  25021. };
  25022. }
  25023. return ShadowsOptimization;
  25024. })(SceneOptimization);
  25025. BABYLON.ShadowsOptimization = ShadowsOptimization;
  25026. var PostProcessesOptimization = (function (_super) {
  25027. __extends(PostProcessesOptimization, _super);
  25028. function PostProcessesOptimization() {
  25029. _super.apply(this, arguments);
  25030. this.apply = function (scene) {
  25031. scene.postProcessesEnabled = false;
  25032. return true;
  25033. };
  25034. }
  25035. return PostProcessesOptimization;
  25036. })(SceneOptimization);
  25037. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  25038. var LensFlaresOptimization = (function (_super) {
  25039. __extends(LensFlaresOptimization, _super);
  25040. function LensFlaresOptimization() {
  25041. _super.apply(this, arguments);
  25042. this.apply = function (scene) {
  25043. scene.lensFlaresEnabled = false;
  25044. return true;
  25045. };
  25046. }
  25047. return LensFlaresOptimization;
  25048. })(SceneOptimization);
  25049. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  25050. var ParticlesOptimization = (function (_super) {
  25051. __extends(ParticlesOptimization, _super);
  25052. function ParticlesOptimization() {
  25053. _super.apply(this, arguments);
  25054. this.apply = function (scene) {
  25055. scene.particlesEnabled = false;
  25056. return true;
  25057. };
  25058. }
  25059. return ParticlesOptimization;
  25060. })(SceneOptimization);
  25061. BABYLON.ParticlesOptimization = ParticlesOptimization;
  25062. var RenderTargetsOptimization = (function (_super) {
  25063. __extends(RenderTargetsOptimization, _super);
  25064. function RenderTargetsOptimization() {
  25065. _super.apply(this, arguments);
  25066. this.apply = function (scene) {
  25067. scene.renderTargetsEnabled = false;
  25068. return true;
  25069. };
  25070. }
  25071. return RenderTargetsOptimization;
  25072. })(SceneOptimization);
  25073. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  25074. var MergeMeshesOptimization = (function (_super) {
  25075. __extends(MergeMeshesOptimization, _super);
  25076. function MergeMeshesOptimization() {
  25077. var _this = this;
  25078. _super.apply(this, arguments);
  25079. this._canBeMerged = function (abstractMesh) {
  25080. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  25081. return false;
  25082. }
  25083. var mesh = abstractMesh;
  25084. if (!mesh.isVisible || !mesh.isEnabled()) {
  25085. return false;
  25086. }
  25087. if (mesh.instances.length > 0) {
  25088. return false;
  25089. }
  25090. if (mesh.skeleton || mesh.hasLODLevels) {
  25091. return false;
  25092. }
  25093. return true;
  25094. };
  25095. this.apply = function (scene) {
  25096. var globalPool = scene.meshes.slice(0);
  25097. var globalLength = globalPool.length;
  25098. for (var index = 0; index < globalLength; index++) {
  25099. var currentPool = new Array();
  25100. var current = globalPool[index];
  25101. // Checks
  25102. if (!_this._canBeMerged(current)) {
  25103. continue;
  25104. }
  25105. currentPool.push(current);
  25106. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  25107. var otherMesh = globalPool[subIndex];
  25108. if (!_this._canBeMerged(otherMesh)) {
  25109. continue;
  25110. }
  25111. if (otherMesh.material !== current.material) {
  25112. continue;
  25113. }
  25114. if (otherMesh.checkCollisions !== current.checkCollisions) {
  25115. continue;
  25116. }
  25117. currentPool.push(otherMesh);
  25118. globalLength--;
  25119. globalPool.splice(subIndex, 1);
  25120. subIndex--;
  25121. }
  25122. if (currentPool.length < 2) {
  25123. continue;
  25124. }
  25125. // Merge meshes
  25126. BABYLON.Mesh.MergeMeshes(currentPool);
  25127. }
  25128. return true;
  25129. };
  25130. }
  25131. return MergeMeshesOptimization;
  25132. })(SceneOptimization);
  25133. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  25134. // Options
  25135. var SceneOptimizerOptions = (function () {
  25136. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  25137. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  25138. if (trackerDuration === void 0) { trackerDuration = 2000; }
  25139. this.targetFrameRate = targetFrameRate;
  25140. this.trackerDuration = trackerDuration;
  25141. this.optimizations = new Array();
  25142. }
  25143. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  25144. var result = new SceneOptimizerOptions(targetFrameRate);
  25145. var priority = 0;
  25146. result.optimizations.push(new MergeMeshesOptimization(priority));
  25147. result.optimizations.push(new ShadowsOptimization(priority));
  25148. result.optimizations.push(new LensFlaresOptimization(priority));
  25149. // Next priority
  25150. priority++;
  25151. result.optimizations.push(new PostProcessesOptimization(priority));
  25152. result.optimizations.push(new ParticlesOptimization(priority));
  25153. // Next priority
  25154. priority++;
  25155. result.optimizations.push(new TextureOptimization(priority, 1024));
  25156. return result;
  25157. };
  25158. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  25159. var result = new SceneOptimizerOptions(targetFrameRate);
  25160. var priority = 0;
  25161. result.optimizations.push(new MergeMeshesOptimization(priority));
  25162. result.optimizations.push(new ShadowsOptimization(priority));
  25163. result.optimizations.push(new LensFlaresOptimization(priority));
  25164. // Next priority
  25165. priority++;
  25166. result.optimizations.push(new PostProcessesOptimization(priority));
  25167. result.optimizations.push(new ParticlesOptimization(priority));
  25168. // Next priority
  25169. priority++;
  25170. result.optimizations.push(new TextureOptimization(priority, 512));
  25171. // Next priority
  25172. priority++;
  25173. result.optimizations.push(new RenderTargetsOptimization(priority));
  25174. // Next priority
  25175. priority++;
  25176. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  25177. return result;
  25178. };
  25179. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  25180. var result = new SceneOptimizerOptions(targetFrameRate);
  25181. var priority = 0;
  25182. result.optimizations.push(new MergeMeshesOptimization(priority));
  25183. result.optimizations.push(new ShadowsOptimization(priority));
  25184. result.optimizations.push(new LensFlaresOptimization(priority));
  25185. // Next priority
  25186. priority++;
  25187. result.optimizations.push(new PostProcessesOptimization(priority));
  25188. result.optimizations.push(new ParticlesOptimization(priority));
  25189. // Next priority
  25190. priority++;
  25191. result.optimizations.push(new TextureOptimization(priority, 256));
  25192. // Next priority
  25193. priority++;
  25194. result.optimizations.push(new RenderTargetsOptimization(priority));
  25195. // Next priority
  25196. priority++;
  25197. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  25198. return result;
  25199. };
  25200. return SceneOptimizerOptions;
  25201. })();
  25202. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  25203. // Scene optimizer tool
  25204. var SceneOptimizer = (function () {
  25205. function SceneOptimizer() {
  25206. }
  25207. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  25208. // TODO: add an epsilon
  25209. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  25210. if (onSuccess) {
  25211. onSuccess();
  25212. }
  25213. return;
  25214. }
  25215. // Apply current level of optimizations
  25216. var allDone = true;
  25217. var noOptimizationApplied = true;
  25218. for (var index = 0; index < options.optimizations.length; index++) {
  25219. var optimization = options.optimizations[index];
  25220. if (optimization.priority === currentPriorityLevel) {
  25221. noOptimizationApplied = false;
  25222. allDone = allDone && optimization.apply(scene);
  25223. }
  25224. }
  25225. // If no optimization was applied, this is a failure :(
  25226. if (noOptimizationApplied) {
  25227. if (onFailure) {
  25228. onFailure();
  25229. }
  25230. return;
  25231. }
  25232. // If all optimizations were done, move to next level
  25233. if (allDone) {
  25234. currentPriorityLevel++;
  25235. }
  25236. // Let's the system running for a specific amount of time before checking FPS
  25237. scene.executeWhenReady(function () {
  25238. setTimeout(function () {
  25239. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  25240. }, options.trackerDuration);
  25241. });
  25242. };
  25243. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  25244. if (!options) {
  25245. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  25246. }
  25247. // Let's the system running for a specific amount of time before checking FPS
  25248. scene.executeWhenReady(function () {
  25249. setTimeout(function () {
  25250. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  25251. }, options.trackerDuration);
  25252. });
  25253. };
  25254. return SceneOptimizer;
  25255. })();
  25256. BABYLON.SceneOptimizer = SceneOptimizer;
  25257. })(BABYLON || (BABYLON = {}));
  25258. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  25259. (function (BABYLON) {
  25260. var Internals;
  25261. (function (Internals) {
  25262. var MeshLODLevel = (function () {
  25263. function MeshLODLevel(distance, mesh) {
  25264. this.distance = distance;
  25265. this.mesh = mesh;
  25266. }
  25267. return MeshLODLevel;
  25268. })();
  25269. Internals.MeshLODLevel = MeshLODLevel;
  25270. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25271. })(BABYLON || (BABYLON = {}));
  25272. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  25273. (function (BABYLON) {
  25274. var AudioEngine = (function () {
  25275. function AudioEngine() {
  25276. this.audioContext = null;
  25277. this.canUseWebAudio = false;
  25278. try {
  25279. if (typeof AudioContext !== 'undefined') {
  25280. this.audioContext = new AudioContext();
  25281. this.canUseWebAudio = true;
  25282. }
  25283. else if (typeof webkitAudioContext !== 'undefined') {
  25284. this.audioContext = new webkitAudioContext();
  25285. this.canUseWebAudio = true;
  25286. }
  25287. else {
  25288. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  25289. }
  25290. }
  25291. catch (e) {
  25292. this.canUseWebAudio = false;
  25293. BABYLON.Tools.Error("Web Audio: " + e.message);
  25294. }
  25295. // create a global volume gain node
  25296. if (this.canUseWebAudio) {
  25297. this.masterGain = this.audioContext.createGain();
  25298. this.masterGain.gain.value = 1;
  25299. this.masterGain.connect(this.audioContext.destination);
  25300. }
  25301. }
  25302. AudioEngine.prototype.dispose = function () {
  25303. if (this.canUseWebAudio) {
  25304. if (this._connectedAnalyser) {
  25305. this._connectedAnalyser.stopDebugCanvas();
  25306. this._connectedAnalyser.dispose();
  25307. this.masterGain.disconnect();
  25308. this.masterGain.connect(this.audioContext.destination);
  25309. this._connectedAnalyser = null;
  25310. }
  25311. this.masterGain.gain.value = 1;
  25312. }
  25313. };
  25314. AudioEngine.prototype.getGlobalVolume = function () {
  25315. if (this.canUseWebAudio) {
  25316. return this.masterGain.gain.value;
  25317. }
  25318. else {
  25319. return -1;
  25320. }
  25321. };
  25322. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  25323. if (this.canUseWebAudio) {
  25324. this.masterGain.gain.value = newVolume;
  25325. }
  25326. };
  25327. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  25328. if (this._connectedAnalyser) {
  25329. this._connectedAnalyser.stopDebugCanvas();
  25330. }
  25331. this._connectedAnalyser = analyser;
  25332. if (this.canUseWebAudio) {
  25333. this.masterGain.disconnect();
  25334. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  25335. }
  25336. };
  25337. return AudioEngine;
  25338. })();
  25339. BABYLON.AudioEngine = AudioEngine;
  25340. })(BABYLON || (BABYLON = {}));
  25341. //# sourceMappingURL=babylon.audioengine.js.mapvar BABYLON;
  25342. (function (BABYLON) {
  25343. var Sound = (function () {
  25344. /**
  25345. * Create a sound and attach it to a scene
  25346. * @param name Name of your sound
  25347. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  25348. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  25349. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  25350. */
  25351. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  25352. var _this = this;
  25353. this.autoplay = false;
  25354. this.loop = false;
  25355. this.useCustomAttenuation = false;
  25356. this.spatialSound = false;
  25357. this.refDistance = 1;
  25358. this.rolloffFactor = 1;
  25359. this.maxDistance = 100;
  25360. this.distanceModel = "linear";
  25361. this.panningModel = "HRTF";
  25362. this.playbackRate = 1;
  25363. this._startTime = 0;
  25364. this._startOffset = 0;
  25365. this._position = BABYLON.Vector3.Zero();
  25366. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  25367. this._volume = 1;
  25368. this._isLoaded = false;
  25369. this._isReadyToPlay = false;
  25370. this._isPlaying = false;
  25371. this._isDirectional = false;
  25372. // Used if you'd like to create a directional sound.
  25373. // If not set, the sound will be omnidirectional
  25374. this._coneInnerAngle = 360;
  25375. this._coneOuterAngle = 360;
  25376. this._coneOuterGain = 0;
  25377. this.name = name;
  25378. this._scene = scene;
  25379. this._audioEngine = this._scene.getEngine().getAudioEngine();
  25380. this._readyToPlayCallback = readyToPlayCallback;
  25381. // Default custom attenuation function is a linear attenuation
  25382. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  25383. if (currentDistance < maxDistance) {
  25384. return currentVolume * (1 - currentDistance / maxDistance);
  25385. }
  25386. else {
  25387. return 0;
  25388. }
  25389. };
  25390. if (options) {
  25391. this.autoplay = options.autoplay || false;
  25392. this.loop = options.loop || false;
  25393. // if volume === 0, we need another way to check this option
  25394. if (options.volume !== undefined) {
  25395. this._volume = options.volume;
  25396. }
  25397. this.spatialSound = options.spatialSound || false;
  25398. this.maxDistance = options.maxDistance || 100;
  25399. this.useCustomAttenuation = options.useCustomAttenuation || false;
  25400. this.rolloffFactor = options.rolloffFactor || 1;
  25401. this.refDistance = options.refDistance || 1;
  25402. this.distanceModel = options.distanceModel || "linear";
  25403. this.panningModel = options.panningModel || "HRTF";
  25404. this.playbackRate = options.playbackRate || 1;
  25405. }
  25406. if (this._audioEngine.canUseWebAudio) {
  25407. this._soundGain = this._audioEngine.audioContext.createGain();
  25408. this._soundGain.gain.value = this._volume;
  25409. this._inputAudioNode = this._soundGain;
  25410. this._ouputAudioNode = this._soundGain;
  25411. if (this.spatialSound) {
  25412. this._createSpatialParameters();
  25413. }
  25414. this._scene.mainSoundTrack.AddSound(this);
  25415. if (typeof (urlOrArrayBuffer) === "string") {
  25416. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  25417. _this._soundLoaded(data);
  25418. }, null, null, true);
  25419. }
  25420. else {
  25421. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  25422. this._soundLoaded(urlOrArrayBuffer);
  25423. }
  25424. else {
  25425. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  25426. }
  25427. }
  25428. }
  25429. }
  25430. Sound.prototype.dispose = function () {
  25431. if (this._audioEngine.canUseWebAudio && this._isReadyToPlay) {
  25432. if (this._isPlaying) {
  25433. this.stop();
  25434. }
  25435. this._isReadyToPlay = false;
  25436. if (this.soundTrackId === -1) {
  25437. this._scene.mainSoundTrack.RemoveSound(this);
  25438. }
  25439. else {
  25440. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  25441. }
  25442. this._soundGain.disconnect();
  25443. this._soundSource.disconnect();
  25444. if (this._soundPanner) {
  25445. this._soundPanner.disconnect();
  25446. this._soundPanner = null;
  25447. }
  25448. this._audioBuffer = null;
  25449. this._soundGain = null;
  25450. this._soundSource = null;
  25451. if (this._connectedMesh) {
  25452. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  25453. this._connectedMesh = null;
  25454. }
  25455. }
  25456. };
  25457. Sound.prototype._soundLoaded = function (audioData) {
  25458. var _this = this;
  25459. this._isLoaded = true;
  25460. this._audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  25461. _this._audioBuffer = buffer;
  25462. _this._isReadyToPlay = true;
  25463. if (_this.autoplay) {
  25464. _this.play();
  25465. }
  25466. if (_this._readyToPlayCallback) {
  25467. _this._readyToPlayCallback();
  25468. }
  25469. }, function (error) {
  25470. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  25471. });
  25472. };
  25473. Sound.prototype.updateOptions = function (options) {
  25474. if (options) {
  25475. this.loop = options.loop || this.loop;
  25476. this.maxDistance = options.maxDistance || this.maxDistance;
  25477. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  25478. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  25479. this.refDistance = options.refDistance || this.refDistance;
  25480. this.distanceModel = options.distanceModel || this.distanceModel;
  25481. this.panningModel = options.panningModel || this.panningModel;
  25482. this.playbackRate = options.playbackRate || this.playbackRate;
  25483. }
  25484. };
  25485. Sound.prototype._createSpatialParameters = function () {
  25486. if (this._audioEngine.canUseWebAudio) {
  25487. this._soundPanner = this._audioEngine.audioContext.createPanner();
  25488. if (this.useCustomAttenuation) {
  25489. // Tricks to disable in a way embedded Web Audio attenuation
  25490. this._soundPanner.distanceModel = "linear";
  25491. this._soundPanner.maxDistance = Number.MAX_VALUE;
  25492. this._soundPanner.refDistance = 1;
  25493. this._soundPanner.rolloffFactor = 1;
  25494. this._soundPanner.panningModel = "HRTF";
  25495. }
  25496. else {
  25497. this._soundPanner.distanceModel = this.distanceModel;
  25498. this._soundPanner.maxDistance = this.maxDistance;
  25499. this._soundPanner.refDistance = this.refDistance;
  25500. this._soundPanner.rolloffFactor = this.rolloffFactor;
  25501. this._soundPanner.panningModel = this.panningModel;
  25502. }
  25503. this._soundPanner.connect(this._ouputAudioNode);
  25504. this._inputAudioNode = this._soundPanner;
  25505. }
  25506. };
  25507. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  25508. if (this._audioEngine.canUseWebAudio) {
  25509. this._ouputAudioNode.disconnect();
  25510. this._ouputAudioNode.connect(soundTrackAudioNode);
  25511. }
  25512. };
  25513. /**
  25514. * Transform this sound into a directional source
  25515. * @param coneInnerAngle Size of the inner cone in degree
  25516. * @param coneOuterAngle Size of the outer cone in degree
  25517. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  25518. */
  25519. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25520. if (coneOuterAngle < coneInnerAngle) {
  25521. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  25522. return;
  25523. }
  25524. this._coneInnerAngle = coneInnerAngle;
  25525. this._coneOuterAngle = coneOuterAngle;
  25526. this._coneOuterGain = coneOuterGain;
  25527. this._isDirectional = true;
  25528. if (this._isPlaying && this.loop) {
  25529. this.stop();
  25530. this.play();
  25531. }
  25532. };
  25533. Sound.prototype.setPosition = function (newPosition) {
  25534. this._position = newPosition;
  25535. if (this._isPlaying && this.spatialSound) {
  25536. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25537. }
  25538. };
  25539. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  25540. this._localDirection = newLocalDirection;
  25541. if (this._connectedMesh && this._isPlaying) {
  25542. this._updateDirection();
  25543. }
  25544. };
  25545. Sound.prototype._updateDirection = function () {
  25546. var mat = this._connectedMesh.getWorldMatrix();
  25547. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  25548. direction.normalize();
  25549. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  25550. };
  25551. Sound.prototype.updateDistanceFromListener = function () {
  25552. if (this._connectedMesh && this.useCustomAttenuation) {
  25553. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  25554. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  25555. }
  25556. };
  25557. Sound.prototype.setAttenuationFunction = function (callback) {
  25558. this._customAttenuationFunction = callback;
  25559. };
  25560. /**
  25561. * Play the sound
  25562. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  25563. */
  25564. Sound.prototype.play = function (time) {
  25565. if (this._isReadyToPlay) {
  25566. try {
  25567. var startTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  25568. if (!this._soundSource) {
  25569. if (this.spatialSound) {
  25570. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25571. if (this._isDirectional) {
  25572. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  25573. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  25574. this._soundPanner.coneOuterGain = this._coneOuterGain;
  25575. if (this._connectedMesh) {
  25576. this._updateDirection();
  25577. }
  25578. else {
  25579. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  25580. }
  25581. }
  25582. }
  25583. }
  25584. this._soundSource = this._audioEngine.audioContext.createBufferSource();
  25585. this._soundSource.buffer = this._audioBuffer;
  25586. this._soundSource.connect(this._inputAudioNode);
  25587. this._soundSource.loop = this.loop;
  25588. this._soundSource.playbackRate.value = this.playbackRate;
  25589. this._startTime = startTime;
  25590. if (this.onended) {
  25591. this._soundSource.onended = this.onended;
  25592. }
  25593. this._soundSource.start(startTime, this._startOffset % this._soundSource.buffer.duration);
  25594. this._isPlaying = true;
  25595. }
  25596. catch (ex) {
  25597. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  25598. }
  25599. }
  25600. };
  25601. /**
  25602. * Stop the sound
  25603. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  25604. */
  25605. Sound.prototype.stop = function (time) {
  25606. if (this._isPlaying) {
  25607. var stopTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  25608. this._soundSource.stop(stopTime);
  25609. this._isPlaying = false;
  25610. }
  25611. };
  25612. Sound.prototype.pause = function () {
  25613. if (this._isPlaying) {
  25614. this._soundSource.stop(0);
  25615. this._startOffset += this._audioEngine.audioContext.currentTime - this._startTime;
  25616. }
  25617. };
  25618. Sound.prototype.setVolume = function (newVolume) {
  25619. this._volume = newVolume;
  25620. if (this._audioEngine.canUseWebAudio) {
  25621. this._soundGain.gain.value = newVolume;
  25622. }
  25623. };
  25624. Sound.prototype.getVolume = function () {
  25625. return this._volume;
  25626. };
  25627. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  25628. var _this = this;
  25629. this._connectedMesh = meshToConnectTo;
  25630. if (!this.spatialSound) {
  25631. this._createSpatialParameters();
  25632. this.spatialSound = true;
  25633. if (this._isPlaying && this.loop) {
  25634. this.stop();
  25635. this.play();
  25636. }
  25637. }
  25638. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  25639. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  25640. };
  25641. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  25642. this.setPosition(connectedMesh.position);
  25643. if (this._isDirectional && this._isPlaying) {
  25644. this._updateDirection();
  25645. }
  25646. };
  25647. return Sound;
  25648. })();
  25649. BABYLON.Sound = Sound;
  25650. })(BABYLON || (BABYLON = {}));
  25651. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  25652. (function (BABYLON) {
  25653. var SoundTrack = (function () {
  25654. function SoundTrack(scene, options) {
  25655. this.id = -1;
  25656. this._isMainTrack = false;
  25657. this._scene = scene;
  25658. this._audioEngine = scene.getEngine().getAudioEngine();
  25659. this.soundCollection = new Array();
  25660. if (this._audioEngine.canUseWebAudio) {
  25661. this._trackGain = this._audioEngine.audioContext.createGain();
  25662. this._trackGain.connect(this._audioEngine.masterGain);
  25663. if (options) {
  25664. if (options.volume) {
  25665. this._trackGain.gain.value = options.volume;
  25666. }
  25667. if (options.mainTrack) {
  25668. this._isMainTrack = options.mainTrack;
  25669. }
  25670. }
  25671. }
  25672. if (!this._isMainTrack) {
  25673. this._scene.soundTracks.push(this);
  25674. this.id = this._scene.soundTracks.length - 1;
  25675. }
  25676. }
  25677. SoundTrack.prototype.dispose = function () {
  25678. if (this._audioEngine.canUseWebAudio) {
  25679. if (this._connectedAnalyser) {
  25680. this._connectedAnalyser.stopDebugCanvas();
  25681. }
  25682. while (this.soundCollection.length) {
  25683. this.soundCollection[0].dispose();
  25684. }
  25685. this._trackGain.disconnect();
  25686. this._trackGain = null;
  25687. }
  25688. };
  25689. SoundTrack.prototype.AddSound = function (sound) {
  25690. sound.connectToSoundTrackAudioNode(this._trackGain);
  25691. if (sound.soundTrackId) {
  25692. if (sound.soundTrackId === -1) {
  25693. this._scene.mainSoundTrack.RemoveSound(sound);
  25694. }
  25695. else {
  25696. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  25697. }
  25698. }
  25699. this.soundCollection.push(sound);
  25700. sound.soundTrackId = this.id;
  25701. };
  25702. SoundTrack.prototype.RemoveSound = function (sound) {
  25703. var index = this.soundCollection.indexOf(sound);
  25704. if (index !== -1) {
  25705. this.soundCollection.splice(index, 1);
  25706. }
  25707. };
  25708. SoundTrack.prototype.setVolume = function (newVolume) {
  25709. if (this._audioEngine.canUseWebAudio) {
  25710. this._trackGain.gain.value = newVolume;
  25711. }
  25712. };
  25713. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  25714. if (this._connectedAnalyser) {
  25715. this._connectedAnalyser.stopDebugCanvas();
  25716. }
  25717. this._connectedAnalyser = analyser;
  25718. if (this._audioEngine.canUseWebAudio) {
  25719. this._trackGain.disconnect();
  25720. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  25721. }
  25722. };
  25723. return SoundTrack;
  25724. })();
  25725. BABYLON.SoundTrack = SoundTrack;
  25726. })(BABYLON || (BABYLON = {}));
  25727. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  25728. (function (BABYLON) {
  25729. var DebugLayer = (function () {
  25730. function DebugLayer(scene) {
  25731. var _this = this;
  25732. this._enabled = false;
  25733. this._labelsEnabled = false;
  25734. this._displayStatistics = true;
  25735. this._displayTree = false;
  25736. this._displayLogs = false;
  25737. this._identityMatrix = BABYLON.Matrix.Identity();
  25738. this.axisRatio = 0.02;
  25739. this.accentColor = "orange";
  25740. this._scene = scene;
  25741. this._syncPositions = function () {
  25742. var engine = _this._scene.getEngine();
  25743. var canvasRect = engine.getRenderingCanvasClientRect();
  25744. if (_this._showUI) {
  25745. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  25746. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  25747. _this._statsDiv.style.width = "400px";
  25748. _this._statsDiv.style.height = "auto";
  25749. _this._statsSubsetDiv.style.maxHeight = "240px";
  25750. _this._optionsDiv.style.left = "0px";
  25751. _this._optionsDiv.style.top = "10px";
  25752. _this._optionsDiv.style.width = "200px";
  25753. _this._optionsDiv.style.height = "auto";
  25754. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  25755. _this._logDiv.style.left = "0px";
  25756. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  25757. _this._logDiv.style.width = "600px";
  25758. _this._logDiv.style.height = "160px";
  25759. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  25760. _this._treeDiv.style.top = "10px";
  25761. _this._treeDiv.style.width = "300px";
  25762. _this._treeDiv.style.height = "auto";
  25763. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  25764. }
  25765. _this._globalDiv.style.left = canvasRect.left + "px";
  25766. _this._globalDiv.style.top = canvasRect.top + "px";
  25767. _this._drawingCanvas.style.left = "0px";
  25768. _this._drawingCanvas.style.top = "0px";
  25769. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  25770. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  25771. var devicePixelRatio = window.devicePixelRatio || 1;
  25772. var context = _this._drawingContext;
  25773. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  25774. _this._ratio = devicePixelRatio / backingStoreRatio;
  25775. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  25776. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  25777. };
  25778. this._onCanvasClick = function (evt) {
  25779. _this._clickPosition = {
  25780. x: evt.clientX * _this._ratio,
  25781. y: evt.clientY * _this._ratio
  25782. };
  25783. };
  25784. this._syncData = function () {
  25785. if (_this._showUI) {
  25786. if (_this._displayStatistics) {
  25787. _this._displayStats();
  25788. _this._statsDiv.style.display = "";
  25789. }
  25790. else {
  25791. _this._statsDiv.style.display = "none";
  25792. }
  25793. if (_this._displayLogs) {
  25794. _this._logDiv.style.display = "";
  25795. }
  25796. else {
  25797. _this._logDiv.style.display = "none";
  25798. }
  25799. if (_this._displayTree) {
  25800. _this._treeDiv.style.display = "";
  25801. if (_this._needToRefreshMeshesTree) {
  25802. _this._needToRefreshMeshesTree = false;
  25803. _this._refreshMeshesTreeContent();
  25804. }
  25805. }
  25806. else {
  25807. _this._treeDiv.style.display = "none";
  25808. }
  25809. }
  25810. if (_this._labelsEnabled || !_this._showUI) {
  25811. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  25812. var engine = _this._scene.getEngine();
  25813. var viewport = _this._scene.activeCamera.viewport;
  25814. var globalViewport = viewport.toGlobal(engine);
  25815. // Meshes
  25816. var meshes = _this._scene.getActiveMeshes();
  25817. for (var index = 0; index < meshes.length; index++) {
  25818. var mesh = meshes.data[index];
  25819. var position = mesh.getBoundingInfo().boundingSphere.center;
  25820. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25821. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  25822. _this._renderAxis(projectedPosition, mesh, globalViewport);
  25823. }
  25824. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  25825. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  25826. mesh.renderOverlay = !mesh.renderOverlay;
  25827. }, function () {
  25828. return mesh.renderOverlay ? 'red' : 'black';
  25829. });
  25830. }
  25831. }
  25832. // Cameras
  25833. var cameras = _this._scene.cameras;
  25834. for (index = 0; index < cameras.length; index++) {
  25835. var camera = cameras[index];
  25836. if (camera === _this._scene.activeCamera) {
  25837. continue;
  25838. }
  25839. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25840. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  25841. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  25842. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  25843. _this._scene.activeCamera = camera;
  25844. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  25845. }, function () {
  25846. return "purple";
  25847. });
  25848. }
  25849. }
  25850. // Lights
  25851. var lights = _this._scene.lights;
  25852. for (index = 0; index < lights.length; index++) {
  25853. var light = lights[index];
  25854. if (light.position) {
  25855. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  25856. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  25857. _this._renderLabel(light.name, projectedPosition, -20, function () {
  25858. light.setEnabled(!light.isEnabled());
  25859. }, function () {
  25860. return light.isEnabled() ? "orange" : "gray";
  25861. });
  25862. }
  25863. }
  25864. }
  25865. }
  25866. _this._clickPosition = undefined;
  25867. };
  25868. }
  25869. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  25870. while (this._treeSubsetDiv.hasChildNodes()) {
  25871. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  25872. }
  25873. // Add meshes
  25874. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  25875. sortedArray.sort(function (a, b) {
  25876. if (a.name === b.name) {
  25877. return 0;
  25878. }
  25879. return (a.name > b.name) ? 1 : -1;
  25880. });
  25881. for (var index = 0; index < sortedArray.length; index++) {
  25882. var mesh = sortedArray[index];
  25883. if (!mesh.isEnabled()) {
  25884. continue;
  25885. }
  25886. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  25887. m.isVisible = element.checked;
  25888. }, mesh);
  25889. }
  25890. };
  25891. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  25892. this._drawingContext.beginPath();
  25893. this._drawingContext.moveTo(zero.x, zero.y);
  25894. this._drawingContext.lineTo(unit.x, unit.y);
  25895. this._drawingContext.strokeStyle = color;
  25896. this._drawingContext.lineWidth = 4;
  25897. this._drawingContext.stroke();
  25898. this._drawingContext.font = "normal 14px Segoe UI";
  25899. this._drawingContext.fillStyle = color;
  25900. this._drawingContext.fillText(label, unitText.x, unitText.y);
  25901. };
  25902. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  25903. var position = mesh.getBoundingInfo().boundingSphere.center;
  25904. var worldMatrix = mesh.getWorldMatrix();
  25905. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._scene.getTransformMatrix());
  25906. var unit = (unprojectedVector.subtract(position)).length();
  25907. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25908. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25909. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  25910. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25911. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25912. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  25913. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25914. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25915. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  25916. };
  25917. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  25918. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  25919. this._drawingContext.font = "normal 12px Segoe UI";
  25920. var textMetrics = this._drawingContext.measureText(text);
  25921. var centerX = projectedPosition.x - textMetrics.width / 2;
  25922. var centerY = projectedPosition.y;
  25923. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  25924. onClick();
  25925. }
  25926. this._drawingContext.beginPath();
  25927. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  25928. this._drawingContext.fillStyle = getFillStyle();
  25929. this._drawingContext.globalAlpha = 0.5;
  25930. this._drawingContext.fill();
  25931. this._drawingContext.globalAlpha = 1.0;
  25932. this._drawingContext.strokeStyle = '#FFFFFF';
  25933. this._drawingContext.lineWidth = 1;
  25934. this._drawingContext.stroke();
  25935. this._drawingContext.fillStyle = "#FFFFFF";
  25936. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  25937. this._drawingContext.beginPath();
  25938. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  25939. this._drawingContext.fill();
  25940. }
  25941. };
  25942. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  25943. if (!this._clickPosition) {
  25944. return false;
  25945. }
  25946. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  25947. return false;
  25948. }
  25949. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  25950. return false;
  25951. }
  25952. return true;
  25953. };
  25954. DebugLayer.prototype.isVisible = function () {
  25955. return this._enabled;
  25956. };
  25957. DebugLayer.prototype.hide = function () {
  25958. if (!this._enabled) {
  25959. return;
  25960. }
  25961. this._enabled = false;
  25962. var engine = this._scene.getEngine();
  25963. this._scene.unregisterAfterRender(this._syncData);
  25964. document.body.removeChild(this._globalDiv);
  25965. window.removeEventListener("resize", this._syncPositions);
  25966. this._scene.forceShowBoundingBoxes = false;
  25967. this._scene.forceWireframe = false;
  25968. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  25969. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  25970. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  25971. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  25972. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  25973. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  25974. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  25975. this._scene.shadowsEnabled = true;
  25976. this._scene.particlesEnabled = true;
  25977. this._scene.postProcessesEnabled = true;
  25978. this._scene.collisionsEnabled = true;
  25979. this._scene.lightsEnabled = true;
  25980. this._scene.texturesEnabled = true;
  25981. this._scene.lensFlaresEnabled = true;
  25982. this._scene.proceduralTexturesEnabled = true;
  25983. this._scene.renderTargetsEnabled = true;
  25984. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  25985. };
  25986. DebugLayer.prototype.show = function (showUI) {
  25987. if (showUI === void 0) { showUI = true; }
  25988. if (this._enabled) {
  25989. return;
  25990. }
  25991. this._enabled = true;
  25992. this._showUI = showUI;
  25993. var engine = this._scene.getEngine();
  25994. this._globalDiv = document.createElement("div");
  25995. document.body.appendChild(this._globalDiv);
  25996. this._generateDOMelements();
  25997. window.addEventListener("resize", this._syncPositions);
  25998. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  25999. this._syncPositions();
  26000. this._scene.registerAfterRender(this._syncData);
  26001. };
  26002. DebugLayer.prototype._clearLabels = function () {
  26003. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26004. for (var index = 0; index < this._scene.meshes.length; index++) {
  26005. var mesh = this._scene.meshes[index];
  26006. mesh.renderOverlay = false;
  26007. }
  26008. };
  26009. DebugLayer.prototype._generateheader = function (root, text) {
  26010. var header = document.createElement("div");
  26011. header.innerHTML = text + "&nbsp;";
  26012. header.style.textAlign = "right";
  26013. header.style.width = "100%";
  26014. header.style.color = "white";
  26015. header.style.backgroundColor = "Black";
  26016. header.style.padding = "5px 5px 4px 0px";
  26017. header.style.marginLeft = "-5px";
  26018. header.style.fontWeight = "bold";
  26019. root.appendChild(header);
  26020. };
  26021. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26022. var label = document.createElement("label");
  26023. label.innerHTML = title;
  26024. label.style.color = color;
  26025. root.appendChild(label);
  26026. root.appendChild(document.createElement("br"));
  26027. };
  26028. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26029. if (tag === void 0) { tag = null; }
  26030. var label = document.createElement("label");
  26031. var boundingBoxesCheckbox = document.createElement("input");
  26032. boundingBoxesCheckbox.type = "checkbox";
  26033. boundingBoxesCheckbox.checked = initialState;
  26034. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26035. task(evt.target, tag);
  26036. });
  26037. label.appendChild(boundingBoxesCheckbox);
  26038. var container = document.createElement("span");
  26039. var leftPart = document.createElement("span");
  26040. var rightPart = document.createElement("span");
  26041. rightPart.style.cssFloat = "right";
  26042. leftPart.innerHTML = leftTitle;
  26043. rightPart.innerHTML = rightTitle;
  26044. rightPart.style.fontSize = "12px";
  26045. rightPart.style.maxWidth = "200px";
  26046. container.appendChild(leftPart);
  26047. container.appendChild(rightPart);
  26048. label.appendChild(container);
  26049. root.appendChild(label);
  26050. root.appendChild(document.createElement("br"));
  26051. };
  26052. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  26053. if (tag === void 0) { tag = null; }
  26054. var label = document.createElement("label");
  26055. var boundingBoxesCheckbox = document.createElement("input");
  26056. boundingBoxesCheckbox.type = "checkbox";
  26057. boundingBoxesCheckbox.checked = initialState;
  26058. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26059. task(evt.target, tag);
  26060. });
  26061. label.appendChild(boundingBoxesCheckbox);
  26062. label.appendChild(document.createTextNode(title));
  26063. root.appendChild(label);
  26064. root.appendChild(document.createElement("br"));
  26065. };
  26066. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  26067. if (tag === void 0) { tag = null; }
  26068. var label = document.createElement("label");
  26069. var boundingBoxesRadio = document.createElement("input");
  26070. boundingBoxesRadio.type = "radio";
  26071. boundingBoxesRadio.name = name;
  26072. boundingBoxesRadio.checked = initialState;
  26073. boundingBoxesRadio.addEventListener("change", function (evt) {
  26074. task(evt.target, tag);
  26075. });
  26076. label.appendChild(boundingBoxesRadio);
  26077. label.appendChild(document.createTextNode(title));
  26078. root.appendChild(label);
  26079. root.appendChild(document.createElement("br"));
  26080. };
  26081. DebugLayer.prototype._generateDOMelements = function () {
  26082. var _this = this;
  26083. this._globalDiv.id = "DebugLayer";
  26084. this._globalDiv.style.position = "absolute";
  26085. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  26086. this._globalDiv.style.fontSize = "14px";
  26087. this._globalDiv.style.color = "white";
  26088. // Drawing canvas
  26089. this._drawingCanvas = document.createElement("canvas");
  26090. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  26091. this._drawingCanvas.style.position = "absolute";
  26092. this._drawingCanvas.style.pointerEvents = "none";
  26093. this._drawingContext = this._drawingCanvas.getContext("2d");
  26094. this._globalDiv.appendChild(this._drawingCanvas);
  26095. if (this._showUI) {
  26096. var background = "rgba(128, 128, 128, 0.4)";
  26097. var border = "rgb(180, 180, 180) solid 1px";
  26098. // Stats
  26099. this._statsDiv = document.createElement("div");
  26100. this._statsDiv.id = "DebugLayerStats";
  26101. this._statsDiv.style.border = border;
  26102. this._statsDiv.style.position = "absolute";
  26103. this._statsDiv.style.background = background;
  26104. this._statsDiv.style.padding = "0px 0px 0px 5px";
  26105. this._generateheader(this._statsDiv, "STATISTICS");
  26106. this._statsSubsetDiv = document.createElement("div");
  26107. this._statsSubsetDiv.style.paddingTop = "5px";
  26108. this._statsSubsetDiv.style.paddingBottom = "5px";
  26109. this._statsSubsetDiv.style.overflowY = "auto";
  26110. this._statsDiv.appendChild(this._statsSubsetDiv);
  26111. // Tree
  26112. this._treeDiv = document.createElement("div");
  26113. this._treeDiv.id = "DebugLayerTree";
  26114. this._treeDiv.style.border = border;
  26115. this._treeDiv.style.position = "absolute";
  26116. this._treeDiv.style.background = background;
  26117. this._treeDiv.style.padding = "0px 0px 0px 5px";
  26118. this._treeDiv.style.display = "none";
  26119. this._generateheader(this._treeDiv, "MESHES TREE");
  26120. this._treeSubsetDiv = document.createElement("div");
  26121. this._treeSubsetDiv.style.paddingTop = "5px";
  26122. this._treeSubsetDiv.style.paddingRight = "5px";
  26123. this._treeSubsetDiv.style.overflowY = "auto";
  26124. this._treeSubsetDiv.style.maxHeight = "300px";
  26125. this._treeDiv.appendChild(this._treeSubsetDiv);
  26126. this._needToRefreshMeshesTree = true;
  26127. // Logs
  26128. this._logDiv = document.createElement("div");
  26129. this._logDiv.style.border = border;
  26130. this._logDiv.id = "DebugLayerLogs";
  26131. this._logDiv.style.position = "absolute";
  26132. this._logDiv.style.background = background;
  26133. this._logDiv.style.padding = "0px 0px 0px 5px";
  26134. this._logDiv.style.display = "none";
  26135. this._generateheader(this._logDiv, "LOGS");
  26136. this._logSubsetDiv = document.createElement("div");
  26137. this._logSubsetDiv.style.height = "127px";
  26138. this._logSubsetDiv.style.paddingTop = "5px";
  26139. this._logSubsetDiv.style.overflowY = "auto";
  26140. this._logSubsetDiv.style.fontSize = "12px";
  26141. this._logSubsetDiv.style.fontFamily = "consolas";
  26142. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  26143. this._logDiv.appendChild(this._logSubsetDiv);
  26144. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  26145. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  26146. };
  26147. // Options
  26148. this._optionsDiv = document.createElement("div");
  26149. this._optionsDiv.id = "DebugLayerOptions";
  26150. this._optionsDiv.style.border = border;
  26151. this._optionsDiv.style.position = "absolute";
  26152. this._optionsDiv.style.background = background;
  26153. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  26154. this._optionsDiv.style.overflowY = "auto";
  26155. this._generateheader(this._optionsDiv, "OPTIONS");
  26156. this._optionsSubsetDiv = document.createElement("div");
  26157. this._optionsSubsetDiv.style.paddingTop = "5px";
  26158. this._optionsSubsetDiv.style.paddingBottom = "5px";
  26159. this._optionsSubsetDiv.style.overflowY = "auto";
  26160. this._optionsSubsetDiv.style.maxHeight = "200px";
  26161. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  26162. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  26163. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  26164. _this._displayStatistics = element.checked;
  26165. });
  26166. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  26167. _this._displayLogs = element.checked;
  26168. });
  26169. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  26170. _this._displayTree = element.checked;
  26171. _this._needToRefreshMeshesTree = true;
  26172. });
  26173. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26174. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  26175. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  26176. _this._scene.forceShowBoundingBoxes = element.checked;
  26177. });
  26178. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  26179. _this._labelsEnabled = element.checked;
  26180. if (!_this._labelsEnabled) {
  26181. _this._clearLabels();
  26182. }
  26183. });
  26184. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  26185. if (element.checked) {
  26186. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  26187. }
  26188. else {
  26189. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  26190. }
  26191. });
  26192. ;
  26193. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26194. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  26195. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  26196. if (element.checked) {
  26197. _this._scene.forceWireframe = false;
  26198. _this._scene.forcePointsCloud = false;
  26199. }
  26200. });
  26201. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  26202. if (element.checked) {
  26203. _this._scene.forceWireframe = true;
  26204. _this._scene.forcePointsCloud = false;
  26205. }
  26206. });
  26207. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  26208. if (element.checked) {
  26209. _this._scene.forceWireframe = false;
  26210. _this._scene.forcePointsCloud = true;
  26211. }
  26212. });
  26213. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26214. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  26215. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  26216. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  26217. });
  26218. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  26219. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  26220. });
  26221. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  26222. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  26223. });
  26224. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  26225. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  26226. });
  26227. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  26228. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  26229. });
  26230. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  26231. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  26232. });
  26233. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  26234. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  26235. });
  26236. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  26237. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  26238. });
  26239. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26240. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  26241. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  26242. _this._scene.animationsEnabled = element.checked;
  26243. });
  26244. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  26245. _this._scene.collisionsEnabled = element.checked;
  26246. });
  26247. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  26248. _this._scene.fogEnabled = element.checked;
  26249. });
  26250. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  26251. _this._scene.lensFlaresEnabled = element.checked;
  26252. });
  26253. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  26254. _this._scene.lightsEnabled = element.checked;
  26255. });
  26256. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  26257. _this._scene.particlesEnabled = element.checked;
  26258. });
  26259. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  26260. _this._scene.postProcessesEnabled = element.checked;
  26261. });
  26262. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  26263. _this._scene.proceduralTexturesEnabled = element.checked;
  26264. });
  26265. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  26266. _this._scene.renderTargetsEnabled = element.checked;
  26267. });
  26268. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  26269. _this._scene.shadowsEnabled = element.checked;
  26270. });
  26271. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  26272. _this._scene.skeletonsEnabled = element.checked;
  26273. });
  26274. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  26275. _this._scene.texturesEnabled = element.checked;
  26276. });
  26277. this._globalDiv.appendChild(this._statsDiv);
  26278. this._globalDiv.appendChild(this._logDiv);
  26279. this._globalDiv.appendChild(this._optionsDiv);
  26280. this._globalDiv.appendChild(this._treeDiv);
  26281. }
  26282. };
  26283. DebugLayer.prototype._displayStats = function () {
  26284. var scene = this._scene;
  26285. var engine = scene.getEngine();
  26286. var glInfo = engine.getGlInfo();
  26287. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Count</b><br>" + "Total meshes: " + scene.meshes.length + "<br>" + "Total vertices: " + scene.getTotalVertices() + "<br>" + "Total materials: " + scene.materials.length + "<br>" + "Total textures: " + scene.textures.length + "<br>" + "Active meshes: " + scene.getActiveMeshes().length + "<br>" + "Active vertices: " + scene.getActiveVertices() + "<br>" + "Active bones: " + scene.getActiveBones() + "<br>" + "Active particles: " + scene.getActiveParticles() + "<br>" + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>" + "<b>Duration</b><br>" + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>" + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>" + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>" + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>" + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>" + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>" + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>" + "</div>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Extensions</b><br>" + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>" + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>" + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>" + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>" + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>" + "<b>Caps.</b><br>" + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>" + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>" + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>" + "</div><br>" + "<b>Info</b><br>" + glInfo.version + "<br>" + glInfo.renderer + "<br>";
  26288. if (this.customStatsFunction) {
  26289. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  26290. }
  26291. };
  26292. return DebugLayer;
  26293. })();
  26294. BABYLON.DebugLayer = DebugLayer;
  26295. })(BABYLON || (BABYLON = {}));
  26296. //# sourceMappingURL=babylon.debugLayer.js.map
  26297. var BABYLON;
  26298. (function (BABYLON) {
  26299. var RawTexture = (function (_super) {
  26300. __extends(RawTexture, _super);
  26301. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  26302. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26303. if (invertY === void 0) { invertY = false; }
  26304. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26305. _super.call(this, null, scene, !generateMipMaps, invertY);
  26306. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  26307. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26308. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26309. }
  26310. // Statics
  26311. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26312. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26313. if (invertY === void 0) { invertY = false; }
  26314. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26315. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  26316. };
  26317. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26318. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26319. if (invertY === void 0) { invertY = false; }
  26320. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26321. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26322. };
  26323. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26324. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26325. if (invertY === void 0) { invertY = false; }
  26326. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26327. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26328. };
  26329. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26330. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26331. if (invertY === void 0) { invertY = false; }
  26332. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26333. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  26334. };
  26335. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26336. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26337. if (invertY === void 0) { invertY = false; }
  26338. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26339. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  26340. };
  26341. return RawTexture;
  26342. })(BABYLON.Texture);
  26343. BABYLON.RawTexture = RawTexture;
  26344. })(BABYLON || (BABYLON = {}));
  26345. //# sourceMappingURL=babylon.rawTexture.js.map
  26346. var BABYLON;
  26347. (function (BABYLON) {
  26348. var IndexedVector2 = (function (_super) {
  26349. __extends(IndexedVector2, _super);
  26350. function IndexedVector2(original, index) {
  26351. _super.call(this, original.x, original.y);
  26352. this.index = index;
  26353. }
  26354. return IndexedVector2;
  26355. })(BABYLON.Vector2);
  26356. var PolygonPoints = (function () {
  26357. function PolygonPoints() {
  26358. this.elements = new Array();
  26359. }
  26360. PolygonPoints.prototype.add = function (originalPoints) {
  26361. var _this = this;
  26362. var result = new Array();
  26363. originalPoints.forEach(function (point) {
  26364. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  26365. var newPoint = new IndexedVector2(point, _this.elements.length);
  26366. result.push(newPoint);
  26367. _this.elements.push(newPoint);
  26368. }
  26369. });
  26370. return result;
  26371. };
  26372. PolygonPoints.prototype.computeBounds = function () {
  26373. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26374. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26375. this.elements.forEach(function (point) {
  26376. // x
  26377. if (point.x < lmin.x) {
  26378. lmin.x = point.x;
  26379. }
  26380. else if (point.x > lmax.x) {
  26381. lmax.x = point.x;
  26382. }
  26383. // y
  26384. if (point.y < lmin.y) {
  26385. lmin.y = point.y;
  26386. }
  26387. else if (point.y > lmax.y) {
  26388. lmax.y = point.y;
  26389. }
  26390. });
  26391. return {
  26392. min: lmin,
  26393. max: lmax,
  26394. width: lmax.x - lmin.x,
  26395. height: lmax.y - lmin.y
  26396. };
  26397. };
  26398. return PolygonPoints;
  26399. })();
  26400. var Polygon = (function () {
  26401. function Polygon() {
  26402. }
  26403. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  26404. return [
  26405. new BABYLON.Vector2(xmin, ymin),
  26406. new BABYLON.Vector2(xmax, ymin),
  26407. new BABYLON.Vector2(xmax, ymax),
  26408. new BABYLON.Vector2(xmin, ymax)
  26409. ];
  26410. };
  26411. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  26412. if (cx === void 0) { cx = 0; }
  26413. if (cy === void 0) { cy = 0; }
  26414. if (numberOfSides === void 0) { numberOfSides = 32; }
  26415. var result = new Array();
  26416. var angle = 0;
  26417. var increment = (Math.PI * 2) / numberOfSides;
  26418. for (var i = 0; i < numberOfSides; i++) {
  26419. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  26420. angle -= increment;
  26421. }
  26422. return result;
  26423. };
  26424. Polygon.Parse = function (input) {
  26425. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  26426. var i, result = [];
  26427. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  26428. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  26429. }
  26430. return result;
  26431. };
  26432. Polygon.StartingAt = function (x, y) {
  26433. return BABYLON.Path2.StartingAt(x, y);
  26434. };
  26435. return Polygon;
  26436. })();
  26437. BABYLON.Polygon = Polygon;
  26438. var PolygonMeshBuilder = (function () {
  26439. function PolygonMeshBuilder(name, contours, scene) {
  26440. this._points = new PolygonPoints();
  26441. if (!("poly2tri" in window)) {
  26442. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  26443. }
  26444. this._name = name;
  26445. this._scene = scene;
  26446. var points;
  26447. if (contours instanceof BABYLON.Path2) {
  26448. points = contours.getPoints();
  26449. }
  26450. else {
  26451. points = contours;
  26452. }
  26453. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  26454. }
  26455. PolygonMeshBuilder.prototype.addHole = function (hole) {
  26456. this._swctx.addHole(this._points.add(hole));
  26457. return this;
  26458. };
  26459. PolygonMeshBuilder.prototype.build = function (updatable) {
  26460. if (updatable === void 0) { updatable = false; }
  26461. var result = new BABYLON.Mesh(this._name, this._scene);
  26462. var normals = [];
  26463. var positions = [];
  26464. var uvs = [];
  26465. var bounds = this._points.computeBounds();
  26466. this._points.elements.forEach(function (p) {
  26467. normals.push(0, 1.0, 0);
  26468. positions.push(p.x, 0, p.y);
  26469. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  26470. });
  26471. var indices = [];
  26472. this._swctx.triangulate();
  26473. this._swctx.getTriangles().forEach(function (triangle) {
  26474. triangle.getPoints().forEach(function (point) {
  26475. indices.push(point.index);
  26476. });
  26477. });
  26478. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  26479. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  26480. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  26481. result.setIndices(indices);
  26482. return result;
  26483. };
  26484. return PolygonMeshBuilder;
  26485. })();
  26486. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  26487. })(BABYLON || (BABYLON = {}));
  26488. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  26489. (function (BABYLON) {
  26490. var SimplificationSettings = (function () {
  26491. function SimplificationSettings(quality, distance) {
  26492. this.quality = quality;
  26493. this.distance = distance;
  26494. }
  26495. return SimplificationSettings;
  26496. })();
  26497. BABYLON.SimplificationSettings = SimplificationSettings;
  26498. /**
  26499. * The implemented types of simplification.
  26500. * At the moment only Quadratic Error Decimation is implemented.
  26501. */
  26502. (function (SimplificationType) {
  26503. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  26504. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  26505. var SimplificationType = BABYLON.SimplificationType;
  26506. var DecimationTriangle = (function () {
  26507. function DecimationTriangle(vertices) {
  26508. this.vertices = vertices;
  26509. this.error = new Array(4);
  26510. this.deleted = false;
  26511. this.isDirty = false;
  26512. this.borderFactor = 0;
  26513. }
  26514. return DecimationTriangle;
  26515. })();
  26516. BABYLON.DecimationTriangle = DecimationTriangle;
  26517. var DecimationVertex = (function () {
  26518. function DecimationVertex(position, normal, uv, id) {
  26519. this.position = position;
  26520. this.normal = normal;
  26521. this.uv = uv;
  26522. this.id = id;
  26523. this.isBorder = true;
  26524. this.q = new QuadraticMatrix();
  26525. this.triangleCount = 0;
  26526. this.triangleStart = 0;
  26527. }
  26528. return DecimationVertex;
  26529. })();
  26530. BABYLON.DecimationVertex = DecimationVertex;
  26531. var QuadraticMatrix = (function () {
  26532. function QuadraticMatrix(data) {
  26533. this.data = new Array(10);
  26534. for (var i = 0; i < 10; ++i) {
  26535. if (data && data[i]) {
  26536. this.data[i] = data[i];
  26537. }
  26538. else {
  26539. this.data[i] = 0;
  26540. }
  26541. }
  26542. }
  26543. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  26544. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] + this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] - this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  26545. return det;
  26546. };
  26547. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  26548. for (var i = 0; i < 10; ++i) {
  26549. this.data[i] += matrix.data[i];
  26550. }
  26551. };
  26552. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  26553. for (var i = 0; i < 10; ++i) {
  26554. this.data[i] += data[i];
  26555. }
  26556. };
  26557. QuadraticMatrix.prototype.add = function (matrix) {
  26558. var m = new QuadraticMatrix();
  26559. for (var i = 0; i < 10; ++i) {
  26560. m.data[i] = this.data[i] + matrix.data[i];
  26561. }
  26562. return m;
  26563. };
  26564. QuadraticMatrix.FromData = function (a, b, c, d) {
  26565. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  26566. };
  26567. //returning an array to avoid garbage collection
  26568. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  26569. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  26570. };
  26571. return QuadraticMatrix;
  26572. })();
  26573. BABYLON.QuadraticMatrix = QuadraticMatrix;
  26574. var Reference = (function () {
  26575. function Reference(vertexId, triangleId) {
  26576. this.vertexId = vertexId;
  26577. this.triangleId = triangleId;
  26578. }
  26579. return Reference;
  26580. })();
  26581. BABYLON.Reference = Reference;
  26582. /**
  26583. * An implementation of the Quadratic Error simplification algorithm.
  26584. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  26585. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  26586. * @author RaananW
  26587. */
  26588. var QuadraticErrorSimplification = (function () {
  26589. function QuadraticErrorSimplification(_mesh) {
  26590. this._mesh = _mesh;
  26591. this.initialised = false;
  26592. this.syncIterations = 5000;
  26593. this.aggressiveness = 7;
  26594. this.decimationIterations = 100;
  26595. }
  26596. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  26597. var _this = this;
  26598. this.initWithMesh(this._mesh, function () {
  26599. _this.runDecimation(settings, successCallback);
  26600. });
  26601. };
  26602. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  26603. var _this = this;
  26604. var targetCount = ~~(this.triangles.length * settings.quality);
  26605. var deletedTriangles = 0;
  26606. var triangleCount = this.triangles.length;
  26607. var iterationFunction = function (iteration, callback) {
  26608. setTimeout(function () {
  26609. if (iteration % 5 === 0) {
  26610. _this.updateMesh(iteration === 0);
  26611. }
  26612. for (var i = 0; i < _this.triangles.length; ++i) {
  26613. _this.triangles[i].isDirty = false;
  26614. }
  26615. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  26616. var trianglesIterator = function (i) {
  26617. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  26618. var t = _this.triangles[tIdx];
  26619. if (!t)
  26620. return;
  26621. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  26622. return;
  26623. }
  26624. for (var j = 0; j < 3; ++j) {
  26625. if (t.error[j] < threshold) {
  26626. var deleted0 = [];
  26627. var deleted1 = [];
  26628. var i0 = t.vertices[j];
  26629. var i1 = t.vertices[(j + 1) % 3];
  26630. var v0 = _this.vertices[i0];
  26631. var v1 = _this.vertices[i1];
  26632. if (v0.isBorder !== v1.isBorder)
  26633. continue;
  26634. var p = BABYLON.Vector3.Zero();
  26635. var n = BABYLON.Vector3.Zero();
  26636. var uv = BABYLON.Vector2.Zero();
  26637. var color = new BABYLON.Color4(0, 0, 0, 1);
  26638. _this.calculateError(v0, v1, p, n, uv, color);
  26639. var delTr = [];
  26640. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  26641. continue;
  26642. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  26643. continue;
  26644. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  26645. continue;
  26646. }
  26647. v0.normal = n;
  26648. if (v0.uv)
  26649. v0.uv = uv;
  26650. else if (v0.color)
  26651. v0.color = color;
  26652. v0.q = v1.q.add(v0.q);
  26653. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  26654. continue;
  26655. if (p.equals(v0.position))
  26656. continue;
  26657. v0.position = p;
  26658. var tStart = _this.references.length;
  26659. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  26660. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  26661. var tCount = _this.references.length - tStart;
  26662. if (tCount <= v0.triangleCount) {
  26663. if (tCount) {
  26664. for (var c = 0; c < tCount; c++) {
  26665. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  26666. }
  26667. }
  26668. }
  26669. else {
  26670. v0.triangleStart = tStart;
  26671. }
  26672. v0.triangleCount = tCount;
  26673. break;
  26674. }
  26675. }
  26676. };
  26677. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  26678. return (triangleCount - deletedTriangles <= targetCount);
  26679. });
  26680. }, 0);
  26681. };
  26682. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  26683. if (triangleCount - deletedTriangles <= targetCount)
  26684. loop.breakLoop();
  26685. else {
  26686. iterationFunction(loop.index, function () {
  26687. loop.executeNext();
  26688. });
  26689. }
  26690. }, function () {
  26691. setTimeout(function () {
  26692. successCallback(_this.reconstructMesh());
  26693. }, 0);
  26694. });
  26695. };
  26696. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  26697. var _this = this;
  26698. if (!mesh)
  26699. return;
  26700. this.vertices = [];
  26701. this.triangles = [];
  26702. this._mesh = mesh;
  26703. //It is assumed that a mesh has positions, normals and either uvs or colors.
  26704. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26705. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26706. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26707. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26708. var indices = mesh.getIndices();
  26709. var vertexInit = function (i) {
  26710. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), null, i);
  26711. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26712. vertex.uv = BABYLON.Vector2.FromArray(uvs, i * 2);
  26713. }
  26714. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26715. vertex.color = BABYLON.Color4.FromArray(colorsData, i * 4);
  26716. }
  26717. _this.vertices.push(vertex);
  26718. };
  26719. var totalVertices = mesh.getTotalVertices();
  26720. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  26721. var indicesInit = function (i) {
  26722. var pos = i * 3;
  26723. var i0 = indices[pos + 0];
  26724. var i1 = indices[pos + 1];
  26725. var i2 = indices[pos + 2];
  26726. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  26727. _this.triangles.push(triangle);
  26728. };
  26729. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  26730. _this.init(callback);
  26731. });
  26732. });
  26733. };
  26734. QuadraticErrorSimplification.prototype.init = function (callback) {
  26735. var _this = this;
  26736. var triangleInit1 = function (i) {
  26737. var t = _this.triangles[i];
  26738. t.normal = BABYLON.Vector3.Cross(_this.vertices[t.vertices[1]].position.subtract(_this.vertices[t.vertices[0]].position), _this.vertices[t.vertices[2]].position.subtract(_this.vertices[t.vertices[0]].position)).normalize();
  26739. for (var j = 0; j < 3; j++) {
  26740. _this.vertices[t.vertices[j]].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, _this.vertices[t.vertices[0]].position))));
  26741. }
  26742. };
  26743. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  26744. var triangleInit2 = function (i) {
  26745. var t = _this.triangles[i];
  26746. for (var j = 0; j < 3; ++j) {
  26747. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  26748. }
  26749. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  26750. };
  26751. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  26752. _this.initialised = true;
  26753. callback();
  26754. });
  26755. });
  26756. };
  26757. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  26758. var newTriangles = [];
  26759. var i;
  26760. for (i = 0; i < this.vertices.length; ++i) {
  26761. this.vertices[i].triangleCount = 0;
  26762. }
  26763. var t;
  26764. var j;
  26765. for (i = 0; i < this.triangles.length; ++i) {
  26766. if (!this.triangles[i].deleted) {
  26767. t = this.triangles[i];
  26768. for (j = 0; j < 3; ++j) {
  26769. this.vertices[t.vertices[j]].triangleCount = 1;
  26770. }
  26771. newTriangles.push(t);
  26772. }
  26773. }
  26774. var newVerticesOrder = [];
  26775. //compact vertices, get the IDs of the vertices used.
  26776. var dst = 0;
  26777. for (i = 0; i < this.vertices.length; ++i) {
  26778. if (this.vertices[i].triangleCount) {
  26779. this.vertices[i].triangleStart = dst;
  26780. this.vertices[dst].position = this.vertices[i].position;
  26781. this.vertices[dst].normal = this.vertices[i].normal;
  26782. this.vertices[dst].uv = this.vertices[i].uv;
  26783. this.vertices[dst].color = this.vertices[i].color;
  26784. newVerticesOrder.push(i);
  26785. dst++;
  26786. }
  26787. }
  26788. for (i = 0; i < newTriangles.length; ++i) {
  26789. t = newTriangles[i];
  26790. for (j = 0; j < 3; ++j) {
  26791. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  26792. }
  26793. }
  26794. this.vertices = this.vertices.slice(0, dst);
  26795. var newPositionData = [];
  26796. var newNormalData = [];
  26797. var newUVsData = [];
  26798. var newColorsData = [];
  26799. for (i = 0; i < newVerticesOrder.length; ++i) {
  26800. newPositionData.push(this.vertices[i].position.x);
  26801. newPositionData.push(this.vertices[i].position.y);
  26802. newPositionData.push(this.vertices[i].position.z);
  26803. newNormalData.push(this.vertices[i].normal.x);
  26804. newNormalData.push(this.vertices[i].normal.y);
  26805. newNormalData.push(this.vertices[i].normal.z);
  26806. if (this.vertices[i].uv) {
  26807. newUVsData.push(this.vertices[i].uv.x);
  26808. newUVsData.push(this.vertices[i].uv.y);
  26809. }
  26810. else if (this.vertices[i].color) {
  26811. newColorsData.push(this.vertices[i].color.r);
  26812. newColorsData.push(this.vertices[i].color.g);
  26813. newColorsData.push(this.vertices[i].color.b);
  26814. newColorsData.push(this.vertices[i].color.a);
  26815. }
  26816. }
  26817. var newIndicesArray = [];
  26818. for (i = 0; i < newTriangles.length; ++i) {
  26819. newIndicesArray.push(newTriangles[i].vertices[0]);
  26820. newIndicesArray.push(newTriangles[i].vertices[1]);
  26821. newIndicesArray.push(newTriangles[i].vertices[2]);
  26822. }
  26823. //not cloning, to avoid geometry problems. Creating a whole new mesh.
  26824. var newMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  26825. newMesh.material = this._mesh.material;
  26826. newMesh.parent = this._mesh.parent;
  26827. newMesh.setIndices(newIndicesArray);
  26828. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  26829. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  26830. if (newUVsData.length > 0)
  26831. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  26832. if (newColorsData.length > 0)
  26833. newMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  26834. //preparing the skeleton support
  26835. if (this._mesh.skeleton) {
  26836. }
  26837. return newMesh;
  26838. };
  26839. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  26840. for (var i = 0; i < vertex1.triangleCount; ++i) {
  26841. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  26842. if (t.deleted)
  26843. continue;
  26844. var s = this.references[vertex1.triangleStart + i].vertexId;
  26845. var id1 = t.vertices[(s + 1) % 3];
  26846. var id2 = t.vertices[(s + 2) % 3];
  26847. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  26848. deletedArray[i] = true;
  26849. delTr.push(t);
  26850. continue;
  26851. }
  26852. var d1 = this.vertices[id1].position.subtract(point);
  26853. d1 = d1.normalize();
  26854. var d2 = this.vertices[id2].position.subtract(point);
  26855. d2 = d2.normalize();
  26856. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  26857. return true;
  26858. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  26859. deletedArray[i] = false;
  26860. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  26861. return true;
  26862. }
  26863. return false;
  26864. };
  26865. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  26866. var newDeleted = deletedTriangles;
  26867. for (var i = 0; i < vertex.triangleCount; ++i) {
  26868. var ref = this.references[vertex.triangleStart + i];
  26869. var t = this.triangles[ref.triangleId];
  26870. if (t.deleted)
  26871. continue;
  26872. if (deletedArray[i]) {
  26873. t.deleted = true;
  26874. newDeleted++;
  26875. continue;
  26876. }
  26877. t.vertices[ref.vertexId] = vertexId;
  26878. t.isDirty = true;
  26879. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  26880. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  26881. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  26882. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  26883. this.references.push(ref);
  26884. }
  26885. return newDeleted;
  26886. };
  26887. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  26888. for (var i = 0; i < this.vertices.length; ++i) {
  26889. var vCount = [];
  26890. var vId = [];
  26891. var v = this.vertices[i];
  26892. var j;
  26893. for (j = 0; j < v.triangleCount; ++j) {
  26894. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  26895. for (var ii = 0; ii < 3; ii++) {
  26896. var ofs = 0;
  26897. var id = triangle.vertices[ii];
  26898. while (ofs < vCount.length) {
  26899. if (vId[ofs] === id)
  26900. break;
  26901. ++ofs;
  26902. }
  26903. if (ofs === vCount.length) {
  26904. vCount.push(1);
  26905. vId.push(id);
  26906. }
  26907. else {
  26908. vCount[ofs]++;
  26909. }
  26910. }
  26911. }
  26912. for (j = 0; j < vCount.length; ++j) {
  26913. if (vCount[j] === 1) {
  26914. this.vertices[vId[j]].isBorder = true;
  26915. }
  26916. else {
  26917. this.vertices[vId[j]].isBorder = false;
  26918. }
  26919. }
  26920. }
  26921. };
  26922. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  26923. if (identifyBorders === void 0) { identifyBorders = false; }
  26924. var i;
  26925. if (!identifyBorders) {
  26926. var newTrianglesVector = [];
  26927. for (i = 0; i < this.triangles.length; ++i) {
  26928. if (!this.triangles[i].deleted) {
  26929. newTrianglesVector.push(this.triangles[i]);
  26930. }
  26931. }
  26932. this.triangles = newTrianglesVector;
  26933. }
  26934. for (i = 0; i < this.vertices.length; ++i) {
  26935. this.vertices[i].triangleCount = 0;
  26936. this.vertices[i].triangleStart = 0;
  26937. }
  26938. var t;
  26939. var j;
  26940. var v;
  26941. for (i = 0; i < this.triangles.length; ++i) {
  26942. t = this.triangles[i];
  26943. for (j = 0; j < 3; ++j) {
  26944. v = this.vertices[t.vertices[j]];
  26945. v.triangleCount++;
  26946. }
  26947. }
  26948. var tStart = 0;
  26949. for (i = 0; i < this.vertices.length; ++i) {
  26950. this.vertices[i].triangleStart = tStart;
  26951. tStart += this.vertices[i].triangleCount;
  26952. this.vertices[i].triangleCount = 0;
  26953. }
  26954. var newReferences = new Array(this.triangles.length * 3);
  26955. for (i = 0; i < this.triangles.length; ++i) {
  26956. t = this.triangles[i];
  26957. for (j = 0; j < 3; ++j) {
  26958. v = this.vertices[t.vertices[j]];
  26959. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  26960. v.triangleCount++;
  26961. }
  26962. }
  26963. this.references = newReferences;
  26964. if (identifyBorders) {
  26965. this.identifyBorder();
  26966. }
  26967. };
  26968. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  26969. var x = point.x;
  26970. var y = point.y;
  26971. var z = point.z;
  26972. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  26973. };
  26974. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  26975. var q = vertex1.q.add(vertex2.q);
  26976. var border = vertex1.isBorder && vertex2.isBorder;
  26977. var error = 0;
  26978. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  26979. if (qDet !== 0 && !border) {
  26980. if (!pointResult) {
  26981. pointResult = BABYLON.Vector3.Zero();
  26982. }
  26983. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  26984. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  26985. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  26986. error = this.vertexError(q, pointResult);
  26987. //TODO this should be correctly calculated
  26988. if (normalResult) {
  26989. normalResult.copyFrom(vertex1.normal);
  26990. if (vertex1.uv)
  26991. uvResult.copyFrom(vertex1.uv);
  26992. else if (vertex1.color)
  26993. colorResult.copyFrom(vertex1.color);
  26994. }
  26995. }
  26996. else {
  26997. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  26998. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  26999. var error1 = this.vertexError(q, vertex1.position);
  27000. var error2 = this.vertexError(q, vertex2.position);
  27001. var error3 = this.vertexError(q, p3);
  27002. error = Math.min(error1, error2, error3);
  27003. if (error === error1) {
  27004. if (pointResult) {
  27005. pointResult.copyFrom(vertex1.position);
  27006. normalResult.copyFrom(vertex1.normal);
  27007. if (vertex1.uv)
  27008. uvResult.copyFrom(vertex1.uv);
  27009. else if (vertex1.color)
  27010. colorResult.copyFrom(vertex1.color);
  27011. }
  27012. }
  27013. else if (error === error2) {
  27014. if (pointResult) {
  27015. pointResult.copyFrom(vertex2.position);
  27016. normalResult.copyFrom(vertex2.normal);
  27017. if (vertex2.uv)
  27018. uvResult.copyFrom(vertex2.uv);
  27019. else if (vertex2.color)
  27020. colorResult.copyFrom(vertex2.color);
  27021. }
  27022. }
  27023. else {
  27024. if (pointResult) {
  27025. pointResult.copyFrom(p3);
  27026. normalResult.copyFrom(vertex1.normal);
  27027. if (vertex1.uv)
  27028. uvResult.copyFrom(vertex1.uv);
  27029. else if (vertex1.color)
  27030. colorResult.copyFrom(vertex1.color);
  27031. }
  27032. }
  27033. }
  27034. return error;
  27035. };
  27036. return QuadraticErrorSimplification;
  27037. })();
  27038. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  27039. })(BABYLON || (BABYLON = {}));
  27040. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  27041. (function (BABYLON) {
  27042. var Analyser = (function () {
  27043. function Analyser(scene) {
  27044. this.SMOOTHING = 0.75;
  27045. this.FFT_SIZE = 512;
  27046. this.BARGRAPHAMPLITUDE = 256;
  27047. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  27048. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  27049. this._scene = scene;
  27050. this._audioEngine = scene.getEngine().getAudioEngine();
  27051. if (this._audioEngine.canUseWebAudio) {
  27052. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  27053. this._webAudioAnalyser.minDecibels = -140;
  27054. this._webAudioAnalyser.maxDecibels = 0;
  27055. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27056. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27057. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  27058. }
  27059. }
  27060. Analyser.prototype.getFrequencyBinCount = function () {
  27061. if (this._audioEngine.canUseWebAudio) {
  27062. return this._webAudioAnalyser.frequencyBinCount;
  27063. }
  27064. else {
  27065. return 0;
  27066. }
  27067. };
  27068. Analyser.prototype.getByteFrequencyData = function () {
  27069. if (this._audioEngine.canUseWebAudio) {
  27070. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27071. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27072. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  27073. }
  27074. return this._byteFreqs;
  27075. };
  27076. Analyser.prototype.getByteTimeDomainData = function () {
  27077. if (this._audioEngine.canUseWebAudio) {
  27078. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27079. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27080. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  27081. }
  27082. return this._byteTime;
  27083. };
  27084. Analyser.prototype.getFloatFrequencyData = function () {
  27085. if (this._audioEngine.canUseWebAudio) {
  27086. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27087. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27088. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  27089. }
  27090. return this._floatFreqs;
  27091. };
  27092. Analyser.prototype.drawDebugCanvas = function () {
  27093. var _this = this;
  27094. if (this._audioEngine.canUseWebAudio) {
  27095. if (!this._debugCanvas) {
  27096. this._debugCanvas = document.createElement("canvas");
  27097. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  27098. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  27099. this._debugCanvas.style.position = "absolute";
  27100. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  27101. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  27102. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  27103. document.body.appendChild(this._debugCanvas);
  27104. this._registerFunc = function () {
  27105. _this.drawDebugCanvas();
  27106. };
  27107. this._scene.registerBeforeRender(this._registerFunc);
  27108. }
  27109. if (this._registerFunc) {
  27110. var workingArray = this.getByteFrequencyData();
  27111. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  27112. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  27113. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  27114. var value = workingArray[i];
  27115. var percent = value / this.BARGRAPHAMPLITUDE;
  27116. var height = this.DEBUGCANVASSIZE.height * percent;
  27117. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  27118. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  27119. var hue = i / this.getFrequencyBinCount() * 360;
  27120. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  27121. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  27122. }
  27123. }
  27124. }
  27125. };
  27126. Analyser.prototype.stopDebugCanvas = function () {
  27127. if (this._debugCanvas) {
  27128. this._scene.unregisterBeforeRender(this._registerFunc);
  27129. this._registerFunc = null;
  27130. document.body.removeChild(this._debugCanvas);
  27131. this._debugCanvas = null;
  27132. this._debugCanvasContext = null;
  27133. }
  27134. };
  27135. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  27136. if (this._audioEngine.canUseWebAudio) {
  27137. inputAudioNode.connect(this._webAudioAnalyser);
  27138. this._webAudioAnalyser.connect(outputAudioNode);
  27139. }
  27140. };
  27141. Analyser.prototype.dispose = function () {
  27142. if (this._audioEngine.canUseWebAudio) {
  27143. this._webAudioAnalyser.disconnect();
  27144. }
  27145. };
  27146. return Analyser;
  27147. })();
  27148. BABYLON.Analyser = Analyser;
  27149. })(BABYLON || (BABYLON = {}));
  27150. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  27151. (function (BABYLON) {
  27152. var DepthRenderer = (function () {
  27153. function DepthRenderer(scene, type) {
  27154. var _this = this;
  27155. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  27156. this._viewMatrix = BABYLON.Matrix.Zero();
  27157. this._projectionMatrix = BABYLON.Matrix.Zero();
  27158. this._transformMatrix = BABYLON.Matrix.Zero();
  27159. this._worldViewProjection = BABYLON.Matrix.Zero();
  27160. this._scene = scene;
  27161. var engine = scene.getEngine();
  27162. // Render target
  27163. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  27164. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27165. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27166. this._depthMap.refreshRate = 1;
  27167. this._depthMap.renderParticles = false;
  27168. this._depthMap.renderList = null;
  27169. // Custom render function
  27170. var renderSubMesh = function (subMesh) {
  27171. var mesh = subMesh.getRenderingMesh();
  27172. var scene = _this._scene;
  27173. var engine = scene.getEngine();
  27174. // Culling
  27175. engine.setState(subMesh.getMaterial().backFaceCulling);
  27176. // Managing instances
  27177. var batch = mesh._getInstancesRenderList(subMesh._id);
  27178. if (batch.mustReturn) {
  27179. return;
  27180. }
  27181. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  27182. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  27183. engine.enableEffect(_this._effect);
  27184. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  27185. var material = subMesh.getMaterial();
  27186. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27187. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  27188. // Alpha test
  27189. if (material && material.needAlphaTesting()) {
  27190. var alphaTexture = material.getAlphaTestTexture();
  27191. _this._effect.setTexture("diffuseSampler", alphaTexture);
  27192. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27193. }
  27194. // Bones
  27195. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  27196. if (useBones) {
  27197. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27198. }
  27199. if (hardwareInstancedRendering) {
  27200. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  27201. }
  27202. else {
  27203. if (batch.renderSelf[subMesh._id]) {
  27204. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  27205. // Draw
  27206. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  27207. }
  27208. if (batch.visibleInstances[subMesh._id]) {
  27209. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  27210. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  27211. _this._effect.setMatrix("world", instance.getWorldMatrix());
  27212. // Draw
  27213. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  27214. }
  27215. }
  27216. }
  27217. }
  27218. };
  27219. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  27220. var index;
  27221. for (index = 0; index < opaqueSubMeshes.length; index++) {
  27222. renderSubMesh(opaqueSubMeshes.data[index]);
  27223. }
  27224. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  27225. renderSubMesh(alphaTestSubMeshes.data[index]);
  27226. }
  27227. };
  27228. }
  27229. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  27230. var defines = [];
  27231. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27232. var mesh = subMesh.getMesh();
  27233. var scene = mesh.getScene();
  27234. var material = subMesh.getMaterial();
  27235. // Alpha test
  27236. if (material && material.needAlphaTesting()) {
  27237. defines.push("#define ALPHATEST");
  27238. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27239. attribs.push(BABYLON.VertexBuffer.UVKind);
  27240. defines.push("#define UV1");
  27241. }
  27242. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27243. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27244. defines.push("#define UV2");
  27245. }
  27246. }
  27247. // Bones
  27248. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27249. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27250. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27251. defines.push("#define BONES");
  27252. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27253. }
  27254. // Instances
  27255. if (useInstances) {
  27256. defines.push("#define INSTANCES");
  27257. attribs.push("world0");
  27258. attribs.push("world1");
  27259. attribs.push("world2");
  27260. attribs.push("world3");
  27261. }
  27262. // Get correct effect
  27263. var join = defines.join("\n");
  27264. if (this._cachedDefines !== join) {
  27265. this._cachedDefines = join;
  27266. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  27267. }
  27268. return this._effect.isReady();
  27269. };
  27270. DepthRenderer.prototype.getDepthMap = function () {
  27271. return this._depthMap;
  27272. };
  27273. // Methods
  27274. DepthRenderer.prototype.dispose = function () {
  27275. this._depthMap.dispose();
  27276. };
  27277. return DepthRenderer;
  27278. })();
  27279. BABYLON.DepthRenderer = DepthRenderer;
  27280. })(BABYLON || (BABYLON = {}));
  27281. //# sourceMappingURL=babylon.depthRenderer.js.map