babylon.2.0-beta.debug.js 1.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512
  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.getAspectRatio = function (camera) {
  3649. var viewport = camera.viewport;
  3650. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3651. };
  3652. Engine.prototype.getRenderWidth = function () {
  3653. if (this._currentRenderTarget) {
  3654. return this._currentRenderTarget._width;
  3655. }
  3656. return this._renderingCanvas.width;
  3657. };
  3658. Engine.prototype.getRenderHeight = function () {
  3659. if (this._currentRenderTarget) {
  3660. return this._currentRenderTarget._height;
  3661. }
  3662. return this._renderingCanvas.height;
  3663. };
  3664. Engine.prototype.getRenderingCanvas = function () {
  3665. return this._renderingCanvas;
  3666. };
  3667. Engine.prototype.getRenderingCanvasClientRect = function () {
  3668. return this._renderingCanvas.getBoundingClientRect();
  3669. };
  3670. Engine.prototype.setHardwareScalingLevel = function (level) {
  3671. this._hardwareScalingLevel = level;
  3672. this.resize();
  3673. };
  3674. Engine.prototype.getHardwareScalingLevel = function () {
  3675. return this._hardwareScalingLevel;
  3676. };
  3677. Engine.prototype.getLoadedTexturesCache = function () {
  3678. return this._loadedTexturesCache;
  3679. };
  3680. Engine.prototype.getCaps = function () {
  3681. return this._caps;
  3682. };
  3683. Object.defineProperty(Engine.prototype, "drawCalls", {
  3684. get: function () {
  3685. return this._drawCalls;
  3686. },
  3687. enumerable: true,
  3688. configurable: true
  3689. });
  3690. // Methods
  3691. Engine.prototype.resetDrawCalls = function () {
  3692. this._drawCalls = 0;
  3693. };
  3694. Engine.prototype.setDepthFunctionToGreater = function () {
  3695. this._depthCullingState.depthFunc = this._gl.GREATER;
  3696. };
  3697. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3698. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3699. };
  3700. Engine.prototype.setDepthFunctionToLess = function () {
  3701. this._depthCullingState.depthFunc = this._gl.LESS;
  3702. };
  3703. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3704. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3705. };
  3706. /**
  3707. * stop executing a render loop function and remove it from the execution array
  3708. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  3709. */
  3710. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3711. if (!renderFunction) {
  3712. this._activeRenderLoops = [];
  3713. return;
  3714. }
  3715. var index = this._activeRenderLoops.indexOf(renderFunction);
  3716. if (index >= 0) {
  3717. this._activeRenderLoops.splice(index, 1);
  3718. }
  3719. };
  3720. Engine.prototype._renderLoop = function () {
  3721. var _this = this;
  3722. var shouldRender = true;
  3723. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3724. shouldRender = false;
  3725. }
  3726. if (shouldRender) {
  3727. // Start new frame
  3728. this.beginFrame();
  3729. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3730. var renderFunction = this._activeRenderLoops[index];
  3731. renderFunction();
  3732. }
  3733. // Present
  3734. this.endFrame();
  3735. }
  3736. if (this._activeRenderLoops.length > 0) {
  3737. // Register new frame
  3738. BABYLON.Tools.QueueNewFrame(function () {
  3739. _this._renderLoop();
  3740. });
  3741. }
  3742. else {
  3743. this._renderingQueueLaunched = false;
  3744. }
  3745. };
  3746. /**
  3747. * Register and execute a render loop. The engine can have more than one render function.
  3748. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  3749. * @example
  3750. * engine.runRenderLoop(function () {
  3751. * scene.render()
  3752. * })
  3753. */
  3754. Engine.prototype.runRenderLoop = function (renderFunction) {
  3755. var _this = this;
  3756. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3757. return;
  3758. }
  3759. this._activeRenderLoops.push(renderFunction);
  3760. if (!this._renderingQueueLaunched) {
  3761. this._renderingQueueLaunched = true;
  3762. BABYLON.Tools.QueueNewFrame(function () {
  3763. _this._renderLoop();
  3764. });
  3765. }
  3766. };
  3767. /**
  3768. * Toggle full screen mode.
  3769. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  3770. */
  3771. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3772. if (this.isFullscreen) {
  3773. BABYLON.Tools.ExitFullscreen();
  3774. }
  3775. else {
  3776. this._pointerLockRequested = requestPointerLock;
  3777. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3778. }
  3779. };
  3780. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3781. this.applyStates();
  3782. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3783. if (this._depthCullingState.depthMask) {
  3784. this._gl.clearDepth(1.0);
  3785. }
  3786. var mode = 0;
  3787. if (backBuffer)
  3788. mode |= this._gl.COLOR_BUFFER_BIT;
  3789. if (depthStencil && this._depthCullingState.depthMask)
  3790. mode |= this._gl.DEPTH_BUFFER_BIT;
  3791. this._gl.clear(mode);
  3792. };
  3793. /**
  3794. * Set the WebGL's viewport
  3795. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  3796. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  3797. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  3798. */
  3799. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3800. var width = requiredWidth || this._renderingCanvas.width;
  3801. var height = requiredHeight || this._renderingCanvas.height;
  3802. var x = viewport.x || 0;
  3803. var y = viewport.y || 0;
  3804. this._cachedViewport = viewport;
  3805. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3806. };
  3807. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3808. this._cachedViewport = null;
  3809. this._gl.viewport(x, y, width, height);
  3810. };
  3811. Engine.prototype.beginFrame = function () {
  3812. this._measureFps();
  3813. };
  3814. Engine.prototype.endFrame = function () {
  3815. this.flushFramebuffer();
  3816. };
  3817. /**
  3818. * resize the view according to the canvas' size.
  3819. * @example
  3820. * window.addEventListener("resize", function () {
  3821. * engine.resize();
  3822. * });
  3823. */
  3824. Engine.prototype.resize = function () {
  3825. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3826. };
  3827. /**
  3828. * force a specific size of the canvas
  3829. * @param {number} width - the new canvas' width
  3830. * @param {number} height - the new canvas' height
  3831. */
  3832. Engine.prototype.setSize = function (width, height) {
  3833. this._renderingCanvas.width = width;
  3834. this._renderingCanvas.height = height;
  3835. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3836. };
  3837. Engine.prototype.bindFramebuffer = function (texture) {
  3838. this._currentRenderTarget = texture;
  3839. var gl = this._gl;
  3840. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3841. this._gl.viewport(0, 0, texture._width, texture._height);
  3842. this.wipeCaches();
  3843. };
  3844. Engine.prototype.unBindFramebuffer = function (texture) {
  3845. this._currentRenderTarget = null;
  3846. if (texture.generateMipMaps) {
  3847. var gl = this._gl;
  3848. gl.bindTexture(gl.TEXTURE_2D, texture);
  3849. gl.generateMipmap(gl.TEXTURE_2D);
  3850. gl.bindTexture(gl.TEXTURE_2D, null);
  3851. }
  3852. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3853. };
  3854. Engine.prototype.flushFramebuffer = function () {
  3855. // this._gl.flush();
  3856. };
  3857. Engine.prototype.restoreDefaultFramebuffer = function () {
  3858. this._currentRenderTarget = null;
  3859. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3860. this.setViewport(this._cachedViewport);
  3861. this.wipeCaches();
  3862. };
  3863. // VBOs
  3864. Engine.prototype._resetVertexBufferBinding = function () {
  3865. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3866. this._cachedVertexBuffers = null;
  3867. };
  3868. Engine.prototype.createVertexBuffer = function (vertices) {
  3869. var vbo = this._gl.createBuffer();
  3870. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3871. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3872. this._resetVertexBufferBinding();
  3873. vbo.references = 1;
  3874. return vbo;
  3875. };
  3876. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3877. var vbo = this._gl.createBuffer();
  3878. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3879. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3880. this._resetVertexBufferBinding();
  3881. vbo.references = 1;
  3882. return vbo;
  3883. };
  3884. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3885. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3886. if (offset === undefined) {
  3887. offset = 0;
  3888. }
  3889. if (vertices instanceof Float32Array) {
  3890. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3891. }
  3892. else {
  3893. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3894. }
  3895. this._resetVertexBufferBinding();
  3896. };
  3897. Engine.prototype._resetIndexBufferBinding = function () {
  3898. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3899. this._cachedIndexBuffer = null;
  3900. };
  3901. Engine.prototype.createIndexBuffer = function (indices) {
  3902. var vbo = this._gl.createBuffer();
  3903. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3904. // Check for 32 bits indices
  3905. var arrayBuffer;
  3906. var need32Bits = false;
  3907. if (this._caps.uintIndices) {
  3908. for (var index = 0; index < indices.length; index++) {
  3909. if (indices[index] > 65535) {
  3910. need32Bits = true;
  3911. break;
  3912. }
  3913. }
  3914. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3915. }
  3916. else {
  3917. arrayBuffer = new Uint16Array(indices);
  3918. }
  3919. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3920. this._resetIndexBufferBinding();
  3921. vbo.references = 1;
  3922. vbo.is32Bits = need32Bits;
  3923. return vbo;
  3924. };
  3925. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3926. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3927. this._cachedVertexBuffers = vertexBuffer;
  3928. this._cachedEffectForVertexBuffers = effect;
  3929. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3930. var offset = 0;
  3931. for (var index = 0; index < vertexDeclaration.length; index++) {
  3932. var order = effect.getAttributeLocation(index);
  3933. if (order >= 0) {
  3934. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3935. }
  3936. offset += vertexDeclaration[index] * 4;
  3937. }
  3938. }
  3939. if (this._cachedIndexBuffer !== indexBuffer) {
  3940. this._cachedIndexBuffer = indexBuffer;
  3941. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3942. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3943. }
  3944. };
  3945. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3946. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3947. this._cachedVertexBuffers = vertexBuffers;
  3948. this._cachedEffectForVertexBuffers = effect;
  3949. var attributes = effect.getAttributesNames();
  3950. for (var index = 0; index < attributes.length; index++) {
  3951. var order = effect.getAttributeLocation(index);
  3952. if (order >= 0) {
  3953. var vertexBuffer = vertexBuffers[attributes[index]];
  3954. if (!vertexBuffer) {
  3955. continue;
  3956. }
  3957. var stride = vertexBuffer.getStrideSize();
  3958. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3959. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3960. }
  3961. }
  3962. }
  3963. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3964. this._cachedIndexBuffer = indexBuffer;
  3965. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3966. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3967. }
  3968. };
  3969. Engine.prototype._releaseBuffer = function (buffer) {
  3970. buffer.references--;
  3971. if (buffer.references === 0) {
  3972. this._gl.deleteBuffer(buffer);
  3973. return true;
  3974. }
  3975. return false;
  3976. };
  3977. Engine.prototype.createInstancesBuffer = function (capacity) {
  3978. var buffer = this._gl.createBuffer();
  3979. buffer.capacity = capacity;
  3980. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3981. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3982. return buffer;
  3983. };
  3984. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3985. this._gl.deleteBuffer(buffer);
  3986. };
  3987. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3988. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3989. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3990. for (var index = 0; index < 4; index++) {
  3991. var offsetLocation = offsetLocations[index];
  3992. this._gl.enableVertexAttribArray(offsetLocation);
  3993. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3994. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3995. }
  3996. };
  3997. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3998. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3999. for (var index = 0; index < 4; index++) {
  4000. var offsetLocation = offsetLocations[index];
  4001. this._gl.disableVertexAttribArray(offsetLocation);
  4002. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4003. }
  4004. };
  4005. Engine.prototype.applyStates = function () {
  4006. this._depthCullingState.apply(this._gl);
  4007. this._alphaState.apply(this._gl);
  4008. };
  4009. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4010. // Apply states
  4011. this.applyStates();
  4012. this._drawCalls++;
  4013. // Render
  4014. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4015. if (instancesCount) {
  4016. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4017. return;
  4018. }
  4019. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4020. };
  4021. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4022. // Apply states
  4023. this.applyStates();
  4024. this._drawCalls++;
  4025. if (instancesCount) {
  4026. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4027. return;
  4028. }
  4029. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4030. };
  4031. // Shaders
  4032. Engine.prototype._releaseEffect = function (effect) {
  4033. if (this._compiledEffects[effect._key]) {
  4034. delete this._compiledEffects[effect._key];
  4035. if (effect.getProgram()) {
  4036. this._gl.deleteProgram(effect.getProgram());
  4037. }
  4038. }
  4039. };
  4040. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4041. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4042. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4043. var name = vertex + "+" + fragment + "@" + defines;
  4044. if (this._compiledEffects[name]) {
  4045. return this._compiledEffects[name];
  4046. }
  4047. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4048. effect._key = name;
  4049. this._compiledEffects[name] = effect;
  4050. return effect;
  4051. };
  4052. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4053. if (uniformsNames === void 0) { uniformsNames = []; }
  4054. if (samplers === void 0) { samplers = []; }
  4055. if (defines === void 0) { defines = ""; }
  4056. return this.createEffect({
  4057. vertex: "particles",
  4058. fragmentElement: fragmentName
  4059. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4060. };
  4061. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4062. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4063. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4064. var shaderProgram = this._gl.createProgram();
  4065. this._gl.attachShader(shaderProgram, vertexShader);
  4066. this._gl.attachShader(shaderProgram, fragmentShader);
  4067. this._gl.linkProgram(shaderProgram);
  4068. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4069. if (!linked) {
  4070. var error = this._gl.getProgramInfoLog(shaderProgram);
  4071. if (error) {
  4072. throw new Error(error);
  4073. }
  4074. }
  4075. this._gl.deleteShader(vertexShader);
  4076. this._gl.deleteShader(fragmentShader);
  4077. return shaderProgram;
  4078. };
  4079. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4080. var results = [];
  4081. for (var index = 0; index < uniformsNames.length; index++) {
  4082. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4083. }
  4084. return results;
  4085. };
  4086. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4087. var results = [];
  4088. for (var index = 0; index < attributesNames.length; index++) {
  4089. try {
  4090. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4091. }
  4092. catch (e) {
  4093. results.push(-1);
  4094. }
  4095. }
  4096. return results;
  4097. };
  4098. Engine.prototype.enableEffect = function (effect) {
  4099. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4100. if (effect && effect.onBind) {
  4101. effect.onBind(effect);
  4102. }
  4103. return;
  4104. }
  4105. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4106. // Use program
  4107. this._gl.useProgram(effect.getProgram());
  4108. for (var i in this._vertexAttribArrays) {
  4109. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4110. continue;
  4111. }
  4112. this._vertexAttribArrays[i] = false;
  4113. this._gl.disableVertexAttribArray(i);
  4114. }
  4115. var attributesCount = effect.getAttributesCount();
  4116. for (var index = 0; index < attributesCount; index++) {
  4117. // Attributes
  4118. var order = effect.getAttributeLocation(index);
  4119. if (order >= 0) {
  4120. this._vertexAttribArrays[order] = true;
  4121. this._gl.enableVertexAttribArray(order);
  4122. }
  4123. }
  4124. this._currentEffect = effect;
  4125. if (effect.onBind) {
  4126. effect.onBind(effect);
  4127. }
  4128. };
  4129. Engine.prototype.setArray = function (uniform, array) {
  4130. if (!uniform)
  4131. return;
  4132. this._gl.uniform1fv(uniform, array);
  4133. };
  4134. Engine.prototype.setArray2 = function (uniform, array) {
  4135. if (!uniform || array.length % 2 !== 0)
  4136. return;
  4137. this._gl.uniform2fv(uniform, array);
  4138. };
  4139. Engine.prototype.setArray3 = function (uniform, array) {
  4140. if (!uniform || array.length % 3 !== 0)
  4141. return;
  4142. this._gl.uniform3fv(uniform, array);
  4143. };
  4144. Engine.prototype.setArray4 = function (uniform, array) {
  4145. if (!uniform || array.length % 4 !== 0)
  4146. return;
  4147. this._gl.uniform4fv(uniform, array);
  4148. };
  4149. Engine.prototype.setMatrices = function (uniform, matrices) {
  4150. if (!uniform)
  4151. return;
  4152. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4153. };
  4154. Engine.prototype.setMatrix = function (uniform, matrix) {
  4155. if (!uniform)
  4156. return;
  4157. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4158. };
  4159. Engine.prototype.setFloat = function (uniform, value) {
  4160. if (!uniform)
  4161. return;
  4162. this._gl.uniform1f(uniform, value);
  4163. };
  4164. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4165. if (!uniform)
  4166. return;
  4167. this._gl.uniform2f(uniform, x, y);
  4168. };
  4169. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4170. if (!uniform)
  4171. return;
  4172. this._gl.uniform3f(uniform, x, y, z);
  4173. };
  4174. Engine.prototype.setBool = function (uniform, bool) {
  4175. if (!uniform)
  4176. return;
  4177. this._gl.uniform1i(uniform, bool);
  4178. };
  4179. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4180. if (!uniform)
  4181. return;
  4182. this._gl.uniform4f(uniform, x, y, z, w);
  4183. };
  4184. Engine.prototype.setColor3 = function (uniform, color3) {
  4185. if (!uniform)
  4186. return;
  4187. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4188. };
  4189. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4190. if (!uniform)
  4191. return;
  4192. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4193. };
  4194. // States
  4195. Engine.prototype.setState = function (culling, force) {
  4196. // Culling
  4197. if (this._depthCullingState.cull !== culling || force) {
  4198. if (culling) {
  4199. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4200. this._depthCullingState.cull = true;
  4201. }
  4202. else {
  4203. this._depthCullingState.cull = false;
  4204. }
  4205. }
  4206. };
  4207. Engine.prototype.setDepthBuffer = function (enable) {
  4208. this._depthCullingState.depthTest = enable;
  4209. };
  4210. Engine.prototype.getDepthWrite = function () {
  4211. return this._depthCullingState.depthMask;
  4212. };
  4213. Engine.prototype.setDepthWrite = function (enable) {
  4214. this._depthCullingState.depthMask = enable;
  4215. };
  4216. Engine.prototype.setColorWrite = function (enable) {
  4217. this._gl.colorMask(enable, enable, enable, enable);
  4218. };
  4219. Engine.prototype.setAlphaMode = function (mode) {
  4220. switch (mode) {
  4221. case Engine.ALPHA_DISABLE:
  4222. this.setDepthWrite(true);
  4223. this._alphaState.alphaBlend = false;
  4224. break;
  4225. case Engine.ALPHA_COMBINE:
  4226. this.setDepthWrite(false);
  4227. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4228. this._alphaState.alphaBlend = true;
  4229. break;
  4230. case Engine.ALPHA_ADD:
  4231. this.setDepthWrite(false);
  4232. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4233. this._alphaState.alphaBlend = true;
  4234. break;
  4235. }
  4236. this._alphaMode = mode;
  4237. };
  4238. Engine.prototype.getAlphaMode = function () {
  4239. return this._alphaMode;
  4240. };
  4241. Engine.prototype.setAlphaTesting = function (enable) {
  4242. this._alphaTest = enable;
  4243. };
  4244. Engine.prototype.getAlphaTesting = function () {
  4245. return this._alphaTest;
  4246. };
  4247. // Textures
  4248. Engine.prototype.wipeCaches = function () {
  4249. this._activeTexturesCache = [];
  4250. this._currentEffect = null;
  4251. this._depthCullingState.reset();
  4252. this._alphaState.reset();
  4253. this._cachedVertexBuffers = null;
  4254. this._cachedIndexBuffer = null;
  4255. this._cachedEffectForVertexBuffers = null;
  4256. };
  4257. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4258. var gl = this._gl;
  4259. gl.bindTexture(gl.TEXTURE_2D, texture);
  4260. var magFilter = gl.NEAREST;
  4261. var minFilter = gl.NEAREST;
  4262. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4263. magFilter = gl.LINEAR;
  4264. minFilter = gl.LINEAR;
  4265. }
  4266. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4267. magFilter = gl.LINEAR;
  4268. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4269. }
  4270. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4271. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4272. gl.bindTexture(gl.TEXTURE_2D, null);
  4273. texture.samplingMode = samplingMode;
  4274. };
  4275. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4276. var _this = this;
  4277. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4278. if (onLoad === void 0) { onLoad = null; }
  4279. if (onError === void 0) { onError = null; }
  4280. if (buffer === void 0) { buffer = null; }
  4281. var texture = this._gl.createTexture();
  4282. var extension;
  4283. var fromData = false;
  4284. if (url.substr(0, 5) === "data:") {
  4285. fromData = true;
  4286. }
  4287. if (!fromData)
  4288. extension = url.substr(url.length - 4, 4).toLowerCase();
  4289. else {
  4290. var oldUrl = url;
  4291. fromData = oldUrl.split(':');
  4292. url = oldUrl;
  4293. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4294. }
  4295. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4296. var isTGA = (extension === ".tga");
  4297. scene._addPendingData(texture);
  4298. texture.url = url;
  4299. texture.noMipmap = noMipmap;
  4300. texture.references = 1;
  4301. this._loadedTexturesCache.push(texture);
  4302. var onerror = function () {
  4303. scene._removePendingData(texture);
  4304. if (onError) {
  4305. onError();
  4306. }
  4307. };
  4308. if (isTGA) {
  4309. var callback = function (arrayBuffer) {
  4310. var data = new Uint8Array(arrayBuffer);
  4311. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4312. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4313. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4314. if (onLoad) {
  4315. onLoad();
  4316. }
  4317. }, samplingMode);
  4318. };
  4319. if (!(fromData instanceof Array))
  4320. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4321. callback(arrayBuffer);
  4322. }, onerror, scene.database, true);
  4323. else
  4324. callback(buffer);
  4325. }
  4326. else if (isDDS) {
  4327. callback = function (data) {
  4328. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4329. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4330. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4331. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4332. if (onLoad) {
  4333. onLoad();
  4334. }
  4335. }, samplingMode);
  4336. };
  4337. if (!(fromData instanceof Array))
  4338. BABYLON.Tools.LoadFile(url, function (data) {
  4339. callback(data);
  4340. }, onerror, scene.database, true);
  4341. else
  4342. callback(buffer);
  4343. }
  4344. else {
  4345. var onload = function (img) {
  4346. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4347. var isPot = (img.width === potWidth && img.height === potHeight);
  4348. if (!isPot) {
  4349. _this._workingCanvas.width = potWidth;
  4350. _this._workingCanvas.height = potHeight;
  4351. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4352. _this._workingContext.imageSmoothingEnabled = false;
  4353. _this._workingContext.mozImageSmoothingEnabled = false;
  4354. _this._workingContext.oImageSmoothingEnabled = false;
  4355. _this._workingContext.webkitImageSmoothingEnabled = false;
  4356. _this._workingContext.msImageSmoothingEnabled = false;
  4357. }
  4358. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4359. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4360. _this._workingContext.imageSmoothingEnabled = true;
  4361. _this._workingContext.mozImageSmoothingEnabled = true;
  4362. _this._workingContext.oImageSmoothingEnabled = true;
  4363. _this._workingContext.webkitImageSmoothingEnabled = true;
  4364. _this._workingContext.msImageSmoothingEnabled = true;
  4365. }
  4366. }
  4367. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4368. if (onLoad) {
  4369. onLoad();
  4370. }
  4371. }, samplingMode);
  4372. };
  4373. if (!(fromData instanceof Array))
  4374. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4375. else
  4376. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4377. }
  4378. return texture;
  4379. };
  4380. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4381. var texture = this._gl.createTexture();
  4382. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4383. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4384. // Format
  4385. var internalFormat = this._gl.RGBA;
  4386. switch (format) {
  4387. case Engine.TEXTUREFORMAT_ALPHA:
  4388. internalFormat = this._gl.ALPHA;
  4389. break;
  4390. case Engine.TEXTUREFORMAT_LUMINANCE:
  4391. internalFormat = this._gl.LUMINANCE;
  4392. break;
  4393. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4394. internalFormat = this._gl.LUMINANCE_ALPHA;
  4395. break;
  4396. case Engine.TEXTUREFORMAT_RGB:
  4397. internalFormat = this._gl.RGB;
  4398. break;
  4399. case Engine.TEXTUREFORMAT_RGBA:
  4400. internalFormat = this._gl.RGBA;
  4401. break;
  4402. }
  4403. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4404. if (generateMipMaps) {
  4405. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4406. }
  4407. // Filters
  4408. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4409. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4410. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4411. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4412. this._activeTexturesCache = [];
  4413. texture._baseWidth = width;
  4414. texture._baseHeight = height;
  4415. texture._width = width;
  4416. texture._height = height;
  4417. texture.isReady = true;
  4418. texture.references = 1;
  4419. texture.samplingMode = samplingMode;
  4420. this._loadedTexturesCache.push(texture);
  4421. return texture;
  4422. };
  4423. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4424. var texture = this._gl.createTexture();
  4425. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4426. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4427. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4428. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4429. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4430. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4431. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4432. this._activeTexturesCache = [];
  4433. texture._baseWidth = width;
  4434. texture._baseHeight = height;
  4435. texture._width = width;
  4436. texture._height = height;
  4437. texture.isReady = false;
  4438. texture.generateMipMaps = generateMipMaps;
  4439. texture.references = 1;
  4440. texture.samplingMode = samplingMode;
  4441. this._loadedTexturesCache.push(texture);
  4442. return texture;
  4443. };
  4444. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4445. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4446. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4447. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4448. if (texture.generateMipMaps) {
  4449. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4450. }
  4451. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4452. this._activeTexturesCache = [];
  4453. texture.isReady = true;
  4454. };
  4455. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4456. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4457. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4458. // Scale the video if it is a NPOT using the current working canvas
  4459. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4460. if (!texture._workingCanvas) {
  4461. texture._workingCanvas = document.createElement("canvas");
  4462. texture._workingContext = texture._workingCanvas.getContext("2d");
  4463. texture._workingCanvas.width = texture._width;
  4464. texture._workingCanvas.height = texture._height;
  4465. }
  4466. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4467. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4468. }
  4469. else {
  4470. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4471. }
  4472. if (texture.generateMipMaps) {
  4473. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4474. }
  4475. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4476. this._activeTexturesCache = [];
  4477. texture.isReady = true;
  4478. };
  4479. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4480. // old version had a "generateMipMaps" arg instead of options.
  4481. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4482. // in the same way, generateDepthBuffer is defaulted to true
  4483. var generateMipMaps = false;
  4484. var generateDepthBuffer = true;
  4485. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4486. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4487. if (options !== undefined) {
  4488. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4489. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4490. type = options.type === undefined ? type : options.type;
  4491. if (options.samplingMode !== undefined) {
  4492. samplingMode = options.samplingMode;
  4493. }
  4494. if (type === Engine.TEXTURETYPE_FLOAT) {
  4495. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4496. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4497. }
  4498. }
  4499. var gl = this._gl;
  4500. var texture = gl.createTexture();
  4501. gl.bindTexture(gl.TEXTURE_2D, texture);
  4502. var width = size.width || size;
  4503. var height = size.height || size;
  4504. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4505. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4506. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4507. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4508. }
  4509. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4510. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4511. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4512. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4513. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4514. var depthBuffer;
  4515. // Create the depth buffer
  4516. if (generateDepthBuffer) {
  4517. depthBuffer = gl.createRenderbuffer();
  4518. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4519. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4520. }
  4521. // Create the framebuffer
  4522. var framebuffer = gl.createFramebuffer();
  4523. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4524. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4525. if (generateDepthBuffer) {
  4526. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4527. }
  4528. // Unbind
  4529. gl.bindTexture(gl.TEXTURE_2D, null);
  4530. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4531. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4532. texture._framebuffer = framebuffer;
  4533. if (generateDepthBuffer) {
  4534. texture._depthBuffer = depthBuffer;
  4535. }
  4536. texture._width = width;
  4537. texture._height = height;
  4538. texture.isReady = true;
  4539. texture.generateMipMaps = generateMipMaps;
  4540. texture.references = 1;
  4541. texture.samplingMode = samplingMode;
  4542. this._activeTexturesCache = [];
  4543. this._loadedTexturesCache.push(texture);
  4544. return texture;
  4545. };
  4546. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4547. var _this = this;
  4548. var gl = this._gl;
  4549. var texture = gl.createTexture();
  4550. texture.isCube = true;
  4551. texture.url = rootUrl;
  4552. texture.references = 1;
  4553. this._loadedTexturesCache.push(texture);
  4554. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4555. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4556. if (isDDS) {
  4557. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4558. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4559. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4560. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4561. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4562. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4563. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4564. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4565. }
  4566. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4567. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4568. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4569. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4570. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4571. _this._activeTexturesCache = [];
  4572. texture._width = info.width;
  4573. texture._height = info.height;
  4574. texture.isReady = true;
  4575. }, null, null, true);
  4576. }
  4577. else {
  4578. cascadeLoad(rootUrl, scene, function (imgs) {
  4579. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4580. var height = width;
  4581. _this._workingCanvas.width = width;
  4582. _this._workingCanvas.height = height;
  4583. var faces = [
  4584. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4585. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4586. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4587. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4588. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4589. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4590. ];
  4591. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4592. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4593. for (var index = 0; index < faces.length; index++) {
  4594. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4595. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4596. }
  4597. if (!noMipmap) {
  4598. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4599. }
  4600. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4601. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4602. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4603. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4604. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4605. _this._activeTexturesCache = [];
  4606. texture._width = width;
  4607. texture._height = height;
  4608. texture.isReady = true;
  4609. }, extensions);
  4610. }
  4611. return texture;
  4612. };
  4613. Engine.prototype._releaseTexture = function (texture) {
  4614. var gl = this._gl;
  4615. if (texture._framebuffer) {
  4616. gl.deleteFramebuffer(texture._framebuffer);
  4617. }
  4618. if (texture._depthBuffer) {
  4619. gl.deleteRenderbuffer(texture._depthBuffer);
  4620. }
  4621. gl.deleteTexture(texture);
  4622. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4623. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4624. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4625. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4626. this._activeTexturesCache[channel] = null;
  4627. }
  4628. var index = this._loadedTexturesCache.indexOf(texture);
  4629. if (index !== -1) {
  4630. this._loadedTexturesCache.splice(index, 1);
  4631. }
  4632. };
  4633. Engine.prototype.bindSamplers = function (effect) {
  4634. this._gl.useProgram(effect.getProgram());
  4635. var samplers = effect.getSamplers();
  4636. for (var index = 0; index < samplers.length; index++) {
  4637. var uniform = effect.getUniform(samplers[index]);
  4638. this._gl.uniform1i(uniform, index);
  4639. }
  4640. this._currentEffect = null;
  4641. };
  4642. Engine.prototype._bindTexture = function (channel, texture) {
  4643. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4644. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4645. this._activeTexturesCache[channel] = null;
  4646. };
  4647. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4648. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4649. };
  4650. Engine.prototype.setTexture = function (channel, texture) {
  4651. if (channel < 0) {
  4652. return;
  4653. }
  4654. // Not ready?
  4655. if (!texture || !texture.isReady()) {
  4656. if (this._activeTexturesCache[channel] != null) {
  4657. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4658. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4659. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4660. this._activeTexturesCache[channel] = null;
  4661. }
  4662. return;
  4663. }
  4664. // Video
  4665. if (texture instanceof BABYLON.VideoTexture) {
  4666. if (texture.update()) {
  4667. this._activeTexturesCache[channel] = null;
  4668. }
  4669. }
  4670. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4671. texture.delayLoad();
  4672. return;
  4673. }
  4674. if (this._activeTexturesCache[channel] === texture) {
  4675. return;
  4676. }
  4677. this._activeTexturesCache[channel] = texture;
  4678. var internalTexture = texture.getInternalTexture();
  4679. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4680. if (internalTexture.isCube) {
  4681. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4682. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4683. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4684. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4685. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4686. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4687. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4688. }
  4689. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4690. }
  4691. else {
  4692. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4693. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4694. internalTexture._cachedWrapU = texture.wrapU;
  4695. switch (texture.wrapU) {
  4696. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4697. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4698. break;
  4699. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4700. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4701. break;
  4702. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4703. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4704. break;
  4705. }
  4706. }
  4707. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4708. internalTexture._cachedWrapV = texture.wrapV;
  4709. switch (texture.wrapV) {
  4710. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4711. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4712. break;
  4713. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4714. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4715. break;
  4716. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4717. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4718. break;
  4719. }
  4720. }
  4721. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4722. }
  4723. };
  4724. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4725. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4726. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4727. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4728. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4729. }
  4730. };
  4731. Engine.prototype.readPixels = function (x, y, width, height) {
  4732. var data = new Uint8Array(height * width * 4);
  4733. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4734. return data;
  4735. };
  4736. // Dispose
  4737. Engine.prototype.dispose = function () {
  4738. this.hideLoadingUI();
  4739. this.stopRenderLoop();
  4740. while (this.scenes.length) {
  4741. this.scenes[0].dispose();
  4742. }
  4743. // Release audio engine
  4744. Engine.audioEngine.dispose();
  4745. for (var name in this._compiledEffects) {
  4746. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4747. }
  4748. for (var i in this._vertexAttribArrays) {
  4749. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4750. continue;
  4751. }
  4752. this._gl.disableVertexAttribArray(i);
  4753. }
  4754. // Events
  4755. window.removeEventListener("blur", this._onBlur);
  4756. window.removeEventListener("focus", this._onFocus);
  4757. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4758. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4759. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4760. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4761. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4762. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4763. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4764. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4765. };
  4766. // Loading screen
  4767. Engine.prototype.displayLoadingUI = function () {
  4768. var _this = this;
  4769. this._loadingDiv = document.createElement("div");
  4770. this._loadingDiv.style.opacity = "0";
  4771. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4772. // Loading text
  4773. this._loadingTextDiv = document.createElement("div");
  4774. this._loadingTextDiv.style.position = "absolute";
  4775. this._loadingTextDiv.style.left = "0";
  4776. this._loadingTextDiv.style.top = "50%";
  4777. this._loadingTextDiv.style.marginTop = "80px";
  4778. this._loadingTextDiv.style.width = "100%";
  4779. this._loadingTextDiv.style.height = "20px";
  4780. this._loadingTextDiv.style.fontFamily = "Arial";
  4781. this._loadingTextDiv.style.fontSize = "14px";
  4782. this._loadingTextDiv.style.color = "white";
  4783. this._loadingTextDiv.style.textAlign = "center";
  4784. this._loadingTextDiv.innerHTML = "Loading";
  4785. this._loadingDiv.appendChild(this._loadingTextDiv);
  4786. // Loading img
  4787. var imgBack = new Image();
  4788. 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==";
  4789. imgBack.style.position = "absolute";
  4790. imgBack.style.left = "50%";
  4791. imgBack.style.top = "50%";
  4792. imgBack.style.marginLeft = "-50px";
  4793. imgBack.style.marginTop = "-50px";
  4794. imgBack.style.transition = "transform 1.0s ease";
  4795. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4796. var deg = 360;
  4797. var onTransitionEnd = function () {
  4798. deg += 360;
  4799. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4800. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4801. };
  4802. imgBack.addEventListener("transitionend", onTransitionEnd);
  4803. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4804. this._loadingDiv.appendChild(imgBack);
  4805. // front image
  4806. var imgFront = new Image();
  4807. 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=";
  4808. imgFront.style.position = "absolute";
  4809. imgFront.style.left = "50%";
  4810. imgFront.style.top = "50%";
  4811. imgFront.style.marginLeft = "-50px";
  4812. imgFront.style.marginTop = "-50px";
  4813. this._loadingDiv.appendChild(imgFront);
  4814. // Resize
  4815. this._resizeLoadingUI = function () {
  4816. var canvasRect = _this.getRenderingCanvasClientRect();
  4817. _this._loadingDiv.style.position = "absolute";
  4818. _this._loadingDiv.style.left = canvasRect.left + "px";
  4819. _this._loadingDiv.style.top = canvasRect.top + "px";
  4820. _this._loadingDiv.style.width = canvasRect.width + "px";
  4821. _this._loadingDiv.style.height = canvasRect.height + "px";
  4822. };
  4823. this._resizeLoadingUI();
  4824. window.addEventListener("resize", this._resizeLoadingUI);
  4825. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4826. document.body.appendChild(this._loadingDiv);
  4827. setTimeout(function () {
  4828. _this._loadingDiv.style.opacity = "1";
  4829. imgBack.style.transform = "rotateZ(360deg)";
  4830. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4831. }, 0);
  4832. };
  4833. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4834. set: function (text) {
  4835. if (!this._loadingDiv) {
  4836. return;
  4837. }
  4838. this._loadingTextDiv.innerHTML = text;
  4839. },
  4840. enumerable: true,
  4841. configurable: true
  4842. });
  4843. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4844. get: function () {
  4845. return this._loadingDivBackgroundColor;
  4846. },
  4847. set: function (color) {
  4848. this._loadingDivBackgroundColor = color;
  4849. if (!this._loadingDiv) {
  4850. return;
  4851. }
  4852. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4853. },
  4854. enumerable: true,
  4855. configurable: true
  4856. });
  4857. Engine.prototype.hideLoadingUI = function () {
  4858. var _this = this;
  4859. if (!this._loadingDiv) {
  4860. return;
  4861. }
  4862. var onTransitionEnd = function () {
  4863. if (!_this._loadingDiv) {
  4864. return;
  4865. }
  4866. document.body.removeChild(_this._loadingDiv);
  4867. window.removeEventListener("resize", _this._resizeLoadingUI);
  4868. _this._loadingDiv = null;
  4869. };
  4870. this._loadingDiv.style.opacity = "0";
  4871. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4872. };
  4873. // FPS
  4874. Engine.prototype.getFps = function () {
  4875. return this.fps;
  4876. };
  4877. Engine.prototype.getDeltaTime = function () {
  4878. return this.deltaTime;
  4879. };
  4880. Engine.prototype._measureFps = function () {
  4881. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4882. var length = this.previousFramesDuration.length;
  4883. if (length >= 2) {
  4884. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4885. }
  4886. if (length >= this.fpsRange) {
  4887. if (length > this.fpsRange) {
  4888. this.previousFramesDuration.splice(0, 1);
  4889. length = this.previousFramesDuration.length;
  4890. }
  4891. var sum = 0;
  4892. for (var id = 0; id < length - 1; id++) {
  4893. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4894. }
  4895. this.fps = 1000.0 / (sum / (length - 1));
  4896. }
  4897. };
  4898. // Statics
  4899. Engine.isSupported = function () {
  4900. try {
  4901. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4902. if (navigator.isCocoonJS) {
  4903. return true;
  4904. }
  4905. var tempcanvas = document.createElement("canvas");
  4906. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4907. return gl != null && !!window.WebGLRenderingContext;
  4908. }
  4909. catch (e) {
  4910. return false;
  4911. }
  4912. };
  4913. // Const statics
  4914. Engine._ALPHA_DISABLE = 0;
  4915. Engine._ALPHA_ADD = 1;
  4916. Engine._ALPHA_COMBINE = 2;
  4917. Engine._DELAYLOADSTATE_NONE = 0;
  4918. Engine._DELAYLOADSTATE_LOADED = 1;
  4919. Engine._DELAYLOADSTATE_LOADING = 2;
  4920. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4921. Engine._TEXTUREFORMAT_ALPHA = 0;
  4922. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  4923. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  4924. Engine._TEXTUREFORMAT_RGB = 4;
  4925. Engine._TEXTUREFORMAT_RGBA = 4;
  4926. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  4927. Engine._TEXTURETYPE_FLOAT = 1;
  4928. // Updatable statics so stick with vars here
  4929. Engine.Epsilon = 0.001;
  4930. Engine.CollisionsEpsilon = 0.001;
  4931. Engine.ShadersRepository = "Babylon/Shaders/";
  4932. return Engine;
  4933. })();
  4934. BABYLON.Engine = Engine;
  4935. })(BABYLON || (BABYLON = {}));
  4936. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  4937. (function (BABYLON) {
  4938. /**
  4939. * Node is the basic class for all scene objects (Mesh, Light Camera).
  4940. */
  4941. var Node = (function () {
  4942. /**
  4943. * @constructor
  4944. * @param {string} name - the name and id to be given to this node
  4945. * @param {BABYLON.Scene} the scene this node will be added to
  4946. */
  4947. function Node(name, scene) {
  4948. this.state = "";
  4949. this.animations = new Array();
  4950. this._childrenFlag = -1;
  4951. this._isEnabled = true;
  4952. this._isReady = true;
  4953. this._currentRenderId = -1;
  4954. this.name = name;
  4955. this.id = name;
  4956. this._scene = scene;
  4957. this._initCache();
  4958. }
  4959. Node.prototype.getScene = function () {
  4960. return this._scene;
  4961. };
  4962. Node.prototype.getEngine = function () {
  4963. return this._scene.getEngine();
  4964. };
  4965. // override it in derived class
  4966. Node.prototype.getWorldMatrix = function () {
  4967. return BABYLON.Matrix.Identity();
  4968. };
  4969. // override it in derived class if you add new variables to the cache
  4970. // and call the parent class method
  4971. Node.prototype._initCache = function () {
  4972. this._cache = {};
  4973. this._cache.parent = undefined;
  4974. };
  4975. Node.prototype.updateCache = function (force) {
  4976. if (!force && this.isSynchronized())
  4977. return;
  4978. this._cache.parent = this.parent;
  4979. this._updateCache();
  4980. };
  4981. // override it in derived class if you add new variables to the cache
  4982. // and call the parent class method if !ignoreParentClass
  4983. Node.prototype._updateCache = function (ignoreParentClass) {
  4984. };
  4985. // override it in derived class if you add new variables to the cache
  4986. Node.prototype._isSynchronized = function () {
  4987. return true;
  4988. };
  4989. Node.prototype.isSynchronizedWithParent = function () {
  4990. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4991. };
  4992. Node.prototype.isSynchronized = function (updateCache) {
  4993. var check = this.hasNewParent();
  4994. check = check || !this.isSynchronizedWithParent();
  4995. check = check || !this._isSynchronized();
  4996. if (updateCache)
  4997. this.updateCache(true);
  4998. return !check;
  4999. };
  5000. Node.prototype.hasNewParent = function (update) {
  5001. if (this._cache.parent === this.parent)
  5002. return false;
  5003. if (update)
  5004. this._cache.parent = this.parent;
  5005. return true;
  5006. };
  5007. /**
  5008. * Is this node ready to be used/rendered
  5009. * @return {boolean} is it ready
  5010. */
  5011. Node.prototype.isReady = function () {
  5012. return this._isReady;
  5013. };
  5014. /**
  5015. * Is this node enabled.
  5016. * If the node has a parent and is enabled, the parent will be inspected as well.
  5017. * @return {boolean} whether this node (and its parent) is enabled.
  5018. * @see setEnabled
  5019. */
  5020. Node.prototype.isEnabled = function () {
  5021. if (!this._isEnabled) {
  5022. return false;
  5023. }
  5024. if (this.parent) {
  5025. return this.parent.isEnabled();
  5026. }
  5027. return true;
  5028. };
  5029. /**
  5030. * Set the enabled state of this node.
  5031. * @param {boolean} value - the new enabled state
  5032. * @see isEnabled
  5033. */
  5034. Node.prototype.setEnabled = function (value) {
  5035. this._isEnabled = value;
  5036. };
  5037. /**
  5038. * Is this node a descendant of the given node.
  5039. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5040. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5041. * @see parent
  5042. */
  5043. Node.prototype.isDescendantOf = function (ancestor) {
  5044. if (this.parent) {
  5045. if (this.parent === ancestor) {
  5046. return true;
  5047. }
  5048. return this.parent.isDescendantOf(ancestor);
  5049. }
  5050. return false;
  5051. };
  5052. Node.prototype._getDescendants = function (list, results) {
  5053. for (var index = 0; index < list.length; index++) {
  5054. var item = list[index];
  5055. if (item.isDescendantOf(this)) {
  5056. results.push(item);
  5057. }
  5058. }
  5059. };
  5060. /**
  5061. * Will return all nodes that have this node as parent.
  5062. * @return {BABYLON.Node[]} all children nodes of all types.
  5063. */
  5064. Node.prototype.getDescendants = function () {
  5065. var results = [];
  5066. this._getDescendants(this._scene.meshes, results);
  5067. this._getDescendants(this._scene.lights, results);
  5068. this._getDescendants(this._scene.cameras, results);
  5069. return results;
  5070. };
  5071. Node.prototype._setReady = function (state) {
  5072. if (state == this._isReady) {
  5073. return;
  5074. }
  5075. if (!state) {
  5076. this._isReady = false;
  5077. return;
  5078. }
  5079. this._isReady = true;
  5080. if (this.onReady) {
  5081. this.onReady(this);
  5082. }
  5083. };
  5084. return Node;
  5085. })();
  5086. BABYLON.Node = Node;
  5087. })(BABYLON || (BABYLON = {}));
  5088. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5089. (function (BABYLON) {
  5090. var BoundingSphere = (function () {
  5091. function BoundingSphere(minimum, maximum) {
  5092. this.minimum = minimum;
  5093. this.maximum = maximum;
  5094. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5095. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5096. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5097. this.radius = distance * 0.5;
  5098. this.centerWorld = BABYLON.Vector3.Zero();
  5099. this._update(BABYLON.Matrix.Identity());
  5100. }
  5101. // Methods
  5102. BoundingSphere.prototype._update = function (world) {
  5103. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5104. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5105. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5106. };
  5107. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5108. for (var i = 0; i < 6; i++) {
  5109. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5110. return false;
  5111. }
  5112. return true;
  5113. };
  5114. BoundingSphere.prototype.intersectsPoint = function (point) {
  5115. var x = this.centerWorld.x - point.x;
  5116. var y = this.centerWorld.y - point.y;
  5117. var z = this.centerWorld.z - point.z;
  5118. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5119. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5120. return false;
  5121. return true;
  5122. };
  5123. // Statics
  5124. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5125. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5126. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5127. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5128. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5129. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5130. return false;
  5131. return true;
  5132. };
  5133. return BoundingSphere;
  5134. })();
  5135. BABYLON.BoundingSphere = BoundingSphere;
  5136. })(BABYLON || (BABYLON = {}));
  5137. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5138. (function (BABYLON) {
  5139. var BoundingBox = (function () {
  5140. function BoundingBox(minimum, maximum) {
  5141. this.minimum = minimum;
  5142. this.maximum = maximum;
  5143. this.vectors = new Array();
  5144. this.vectorsWorld = new Array();
  5145. // Bounding vectors
  5146. this.vectors.push(this.minimum.clone());
  5147. this.vectors.push(this.maximum.clone());
  5148. this.vectors.push(this.minimum.clone());
  5149. this.vectors[2].x = this.maximum.x;
  5150. this.vectors.push(this.minimum.clone());
  5151. this.vectors[3].y = this.maximum.y;
  5152. this.vectors.push(this.minimum.clone());
  5153. this.vectors[4].z = this.maximum.z;
  5154. this.vectors.push(this.maximum.clone());
  5155. this.vectors[5].z = this.minimum.z;
  5156. this.vectors.push(this.maximum.clone());
  5157. this.vectors[6].x = this.minimum.x;
  5158. this.vectors.push(this.maximum.clone());
  5159. this.vectors[7].y = this.minimum.y;
  5160. // OBB
  5161. this.center = this.maximum.add(this.minimum).scale(0.5);
  5162. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5163. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5164. for (var index = 0; index < this.vectors.length; index++) {
  5165. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5166. }
  5167. this.minimumWorld = BABYLON.Vector3.Zero();
  5168. this.maximumWorld = BABYLON.Vector3.Zero();
  5169. this._update(BABYLON.Matrix.Identity());
  5170. }
  5171. // Methods
  5172. BoundingBox.prototype.getWorldMatrix = function () {
  5173. return this._worldMatrix;
  5174. };
  5175. BoundingBox.prototype._update = function (world) {
  5176. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5177. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5178. for (var index = 0; index < this.vectors.length; index++) {
  5179. var v = this.vectorsWorld[index];
  5180. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5181. if (v.x < this.minimumWorld.x)
  5182. this.minimumWorld.x = v.x;
  5183. if (v.y < this.minimumWorld.y)
  5184. this.minimumWorld.y = v.y;
  5185. if (v.z < this.minimumWorld.z)
  5186. this.minimumWorld.z = v.z;
  5187. if (v.x > this.maximumWorld.x)
  5188. this.maximumWorld.x = v.x;
  5189. if (v.y > this.maximumWorld.y)
  5190. this.maximumWorld.y = v.y;
  5191. if (v.z > this.maximumWorld.z)
  5192. this.maximumWorld.z = v.z;
  5193. }
  5194. // OBB
  5195. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5196. this.center.scaleInPlace(0.5);
  5197. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5198. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5199. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5200. this._worldMatrix = world;
  5201. };
  5202. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5203. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5204. };
  5205. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5206. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5207. };
  5208. BoundingBox.prototype.intersectsPoint = function (point) {
  5209. var delta = BABYLON.Engine.Epsilon;
  5210. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5211. return false;
  5212. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5213. return false;
  5214. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5215. return false;
  5216. return true;
  5217. };
  5218. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5219. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5220. };
  5221. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5222. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5223. return false;
  5224. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5225. return false;
  5226. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5227. return false;
  5228. return true;
  5229. };
  5230. // Statics
  5231. BoundingBox.Intersects = function (box0, box1) {
  5232. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5233. return false;
  5234. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5235. return false;
  5236. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5237. return false;
  5238. return true;
  5239. };
  5240. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5241. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5242. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5243. return (num <= (sphereRadius * sphereRadius));
  5244. };
  5245. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5246. for (var p = 0; p < 6; p++) {
  5247. for (var i = 0; i < 8; i++) {
  5248. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5249. return false;
  5250. }
  5251. }
  5252. }
  5253. return true;
  5254. };
  5255. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5256. for (var p = 0; p < 6; p++) {
  5257. var inCount = 8;
  5258. for (var i = 0; i < 8; i++) {
  5259. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5260. --inCount;
  5261. }
  5262. else {
  5263. break;
  5264. }
  5265. }
  5266. if (inCount == 0)
  5267. return false;
  5268. }
  5269. return true;
  5270. };
  5271. return BoundingBox;
  5272. })();
  5273. BABYLON.BoundingBox = BoundingBox;
  5274. })(BABYLON || (BABYLON = {}));
  5275. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5276. (function (BABYLON) {
  5277. var computeBoxExtents = function (axis, box) {
  5278. var p = BABYLON.Vector3.Dot(box.center, axis);
  5279. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5280. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5281. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5282. var r = r0 + r1 + r2;
  5283. return {
  5284. min: p - r,
  5285. max: p + r
  5286. };
  5287. };
  5288. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5289. var axisOverlap = function (axis, box0, box1) {
  5290. var result0 = computeBoxExtents(axis, box0);
  5291. var result1 = computeBoxExtents(axis, box1);
  5292. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5293. };
  5294. var BoundingInfo = (function () {
  5295. function BoundingInfo(minimum, maximum) {
  5296. this.minimum = minimum;
  5297. this.maximum = maximum;
  5298. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5299. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5300. }
  5301. // Methods
  5302. BoundingInfo.prototype._update = function (world) {
  5303. this.boundingBox._update(world);
  5304. this.boundingSphere._update(world);
  5305. };
  5306. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5307. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5308. return false;
  5309. return this.boundingBox.isInFrustum(frustumPlanes);
  5310. };
  5311. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5312. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5313. };
  5314. BoundingInfo.prototype._checkCollision = function (collider) {
  5315. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5316. };
  5317. BoundingInfo.prototype.intersectsPoint = function (point) {
  5318. if (!this.boundingSphere.centerWorld) {
  5319. return false;
  5320. }
  5321. if (!this.boundingSphere.intersectsPoint(point)) {
  5322. return false;
  5323. }
  5324. if (!this.boundingBox.intersectsPoint(point)) {
  5325. return false;
  5326. }
  5327. return true;
  5328. };
  5329. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5330. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5331. return false;
  5332. }
  5333. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5334. return false;
  5335. }
  5336. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5337. return false;
  5338. }
  5339. if (!precise) {
  5340. return true;
  5341. }
  5342. var box0 = this.boundingBox;
  5343. var box1 = boundingInfo.boundingBox;
  5344. if (!axisOverlap(box0.directions[0], box0, box1))
  5345. return false;
  5346. if (!axisOverlap(box0.directions[1], box0, box1))
  5347. return false;
  5348. if (!axisOverlap(box0.directions[2], box0, box1))
  5349. return false;
  5350. if (!axisOverlap(box1.directions[0], box0, box1))
  5351. return false;
  5352. if (!axisOverlap(box1.directions[1], box0, box1))
  5353. return false;
  5354. if (!axisOverlap(box1.directions[2], box0, box1))
  5355. return false;
  5356. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5357. return false;
  5358. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5359. return false;
  5360. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5361. return false;
  5362. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5363. return false;
  5364. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5365. return false;
  5366. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5367. return false;
  5368. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5369. return false;
  5370. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5371. return false;
  5372. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5373. return false;
  5374. return true;
  5375. };
  5376. return BoundingInfo;
  5377. })();
  5378. BABYLON.BoundingInfo = BoundingInfo;
  5379. })(BABYLON || (BABYLON = {}));
  5380. //# sourceMappingURL=babylon.boundingInfo.js.map
  5381. var BABYLON;
  5382. (function (BABYLON) {
  5383. var Light = (function (_super) {
  5384. __extends(Light, _super);
  5385. function Light(name, scene) {
  5386. _super.call(this, name, scene);
  5387. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5388. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5389. this.intensity = 1.0;
  5390. this.range = Number.MAX_VALUE;
  5391. this.includedOnlyMeshes = new Array();
  5392. this.excludedMeshes = new Array();
  5393. this._excludedMeshesIds = new Array();
  5394. this._includedOnlyMeshesIds = new Array();
  5395. scene.lights.push(this);
  5396. }
  5397. Light.prototype.getShadowGenerator = function () {
  5398. return this._shadowGenerator;
  5399. };
  5400. Light.prototype.getAbsolutePosition = function () {
  5401. return BABYLON.Vector3.Zero();
  5402. };
  5403. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5404. };
  5405. Light.prototype._getWorldMatrix = function () {
  5406. return BABYLON.Matrix.Identity();
  5407. };
  5408. Light.prototype.canAffectMesh = function (mesh) {
  5409. if (!mesh) {
  5410. return true;
  5411. }
  5412. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5413. return false;
  5414. }
  5415. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5416. return false;
  5417. }
  5418. return true;
  5419. };
  5420. Light.prototype.getWorldMatrix = function () {
  5421. this._currentRenderId = this.getScene().getRenderId();
  5422. var worldMatrix = this._getWorldMatrix();
  5423. if (this.parent && this.parent.getWorldMatrix) {
  5424. if (!this._parentedWorldMatrix) {
  5425. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5426. }
  5427. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5428. return this._parentedWorldMatrix;
  5429. }
  5430. return worldMatrix;
  5431. };
  5432. Light.prototype.dispose = function () {
  5433. if (this._shadowGenerator) {
  5434. this._shadowGenerator.dispose();
  5435. this._shadowGenerator = null;
  5436. }
  5437. // Remove from scene
  5438. var index = this.getScene().lights.indexOf(this);
  5439. this.getScene().lights.splice(index, 1);
  5440. };
  5441. return Light;
  5442. })(BABYLON.Node);
  5443. BABYLON.Light = Light;
  5444. })(BABYLON || (BABYLON = {}));
  5445. //# sourceMappingURL=babylon.light.js.map
  5446. var BABYLON;
  5447. (function (BABYLON) {
  5448. var PointLight = (function (_super) {
  5449. __extends(PointLight, _super);
  5450. function PointLight(name, position, scene) {
  5451. _super.call(this, name, scene);
  5452. this.position = position;
  5453. }
  5454. PointLight.prototype.getAbsolutePosition = function () {
  5455. return this._transformedPosition ? this._transformedPosition : this.position;
  5456. };
  5457. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5458. if (this.parent && this.parent.getWorldMatrix) {
  5459. if (!this._transformedPosition) {
  5460. this._transformedPosition = BABYLON.Vector3.Zero();
  5461. }
  5462. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5463. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5464. return;
  5465. }
  5466. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5467. };
  5468. PointLight.prototype.getShadowGenerator = function () {
  5469. return null;
  5470. };
  5471. PointLight.prototype._getWorldMatrix = function () {
  5472. if (!this._worldMatrix) {
  5473. this._worldMatrix = BABYLON.Matrix.Identity();
  5474. }
  5475. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5476. return this._worldMatrix;
  5477. };
  5478. return PointLight;
  5479. })(BABYLON.Light);
  5480. BABYLON.PointLight = PointLight;
  5481. })(BABYLON || (BABYLON = {}));
  5482. //# sourceMappingURL=babylon.pointLight.js.map
  5483. var BABYLON;
  5484. (function (BABYLON) {
  5485. var SpotLight = (function (_super) {
  5486. __extends(SpotLight, _super);
  5487. function SpotLight(name, position, direction, angle, exponent, scene) {
  5488. _super.call(this, name, scene);
  5489. this.position = position;
  5490. this.direction = direction;
  5491. this.angle = angle;
  5492. this.exponent = exponent;
  5493. }
  5494. SpotLight.prototype.getAbsolutePosition = function () {
  5495. return this.transformedPosition ? this.transformedPosition : this.position;
  5496. };
  5497. SpotLight.prototype.setDirectionToTarget = function (target) {
  5498. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5499. return this.direction;
  5500. };
  5501. SpotLight.prototype.computeTransformedPosition = function () {
  5502. if (this.parent && this.parent.getWorldMatrix) {
  5503. if (!this.transformedPosition) {
  5504. this.transformedPosition = BABYLON.Vector3.Zero();
  5505. }
  5506. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5507. return true;
  5508. }
  5509. return false;
  5510. };
  5511. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5512. var normalizeDirection;
  5513. if (this.parent && this.parent.getWorldMatrix) {
  5514. if (!this._transformedDirection) {
  5515. this._transformedDirection = BABYLON.Vector3.Zero();
  5516. }
  5517. this.computeTransformedPosition();
  5518. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5519. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5520. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5521. }
  5522. else {
  5523. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5524. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5525. }
  5526. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5527. };
  5528. SpotLight.prototype._getWorldMatrix = function () {
  5529. if (!this._worldMatrix) {
  5530. this._worldMatrix = BABYLON.Matrix.Identity();
  5531. }
  5532. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5533. return this._worldMatrix;
  5534. };
  5535. return SpotLight;
  5536. })(BABYLON.Light);
  5537. BABYLON.SpotLight = SpotLight;
  5538. })(BABYLON || (BABYLON = {}));
  5539. //# sourceMappingURL=babylon.spotLight.js.map
  5540. var BABYLON;
  5541. (function (BABYLON) {
  5542. var DirectionalLight = (function (_super) {
  5543. __extends(DirectionalLight, _super);
  5544. function DirectionalLight(name, direction, scene) {
  5545. _super.call(this, name, scene);
  5546. this.direction = direction;
  5547. this.position = direction.scale(-1);
  5548. }
  5549. DirectionalLight.prototype.getAbsolutePosition = function () {
  5550. return this.transformedPosition ? this.transformedPosition : this.position;
  5551. };
  5552. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5553. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5554. return this.direction;
  5555. };
  5556. DirectionalLight.prototype.computeTransformedPosition = function () {
  5557. if (this.parent && this.parent.getWorldMatrix) {
  5558. if (!this.transformedPosition) {
  5559. this.transformedPosition = BABYLON.Vector3.Zero();
  5560. }
  5561. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5562. return true;
  5563. }
  5564. return false;
  5565. };
  5566. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5567. if (this.parent && this.parent.getWorldMatrix) {
  5568. if (!this._transformedDirection) {
  5569. this._transformedDirection = BABYLON.Vector3.Zero();
  5570. }
  5571. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5572. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5573. return;
  5574. }
  5575. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5576. };
  5577. DirectionalLight.prototype._getWorldMatrix = function () {
  5578. if (!this._worldMatrix) {
  5579. this._worldMatrix = BABYLON.Matrix.Identity();
  5580. }
  5581. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5582. return this._worldMatrix;
  5583. };
  5584. return DirectionalLight;
  5585. })(BABYLON.Light);
  5586. BABYLON.DirectionalLight = DirectionalLight;
  5587. })(BABYLON || (BABYLON = {}));
  5588. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5589. (function (BABYLON) {
  5590. var ShadowGenerator = (function () {
  5591. function ShadowGenerator(mapSize, light) {
  5592. var _this = this;
  5593. // Members
  5594. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5595. this._darkness = 0;
  5596. this._transparencyShadow = false;
  5597. this._viewMatrix = BABYLON.Matrix.Zero();
  5598. this._projectionMatrix = BABYLON.Matrix.Zero();
  5599. this._transformMatrix = BABYLON.Matrix.Zero();
  5600. this._worldViewProjection = BABYLON.Matrix.Zero();
  5601. this._light = light;
  5602. this._scene = light.getScene();
  5603. light._shadowGenerator = this;
  5604. // Render target
  5605. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5606. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5607. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5608. this._shadowMap.renderParticles = false;
  5609. // Custom render function
  5610. var renderSubMesh = function (subMesh) {
  5611. var mesh = subMesh.getRenderingMesh();
  5612. var scene = _this._scene;
  5613. var engine = scene.getEngine();
  5614. // Culling
  5615. engine.setState(subMesh.getMaterial().backFaceCulling);
  5616. // Managing instances
  5617. var batch = mesh._getInstancesRenderList(subMesh._id);
  5618. if (batch.mustReturn) {
  5619. return;
  5620. }
  5621. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5622. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5623. engine.enableEffect(_this._effect);
  5624. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5625. var material = subMesh.getMaterial();
  5626. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5627. // Alpha test
  5628. if (material && material.needAlphaTesting()) {
  5629. var alphaTexture = material.getAlphaTestTexture();
  5630. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5631. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5632. }
  5633. // Bones
  5634. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  5635. if (useBones) {
  5636. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5637. }
  5638. if (hardwareInstancedRendering) {
  5639. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  5640. }
  5641. else {
  5642. if (batch.renderSelf[subMesh._id]) {
  5643. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  5644. // Draw
  5645. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5646. }
  5647. if (batch.visibleInstances[subMesh._id]) {
  5648. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  5649. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  5650. _this._effect.setMatrix("world", instance.getWorldMatrix());
  5651. // Draw
  5652. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5653. }
  5654. }
  5655. }
  5656. }
  5657. else {
  5658. // Need to reset refresh rate of the shadowMap
  5659. _this._shadowMap.resetRefreshCounter();
  5660. }
  5661. };
  5662. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5663. var index;
  5664. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5665. renderSubMesh(opaqueSubMeshes.data[index]);
  5666. }
  5667. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5668. renderSubMesh(alphaTestSubMeshes.data[index]);
  5669. }
  5670. if (_this._transparencyShadow) {
  5671. for (index = 0; index < transparentSubMeshes.length; index++) {
  5672. renderSubMesh(transparentSubMeshes.data[index]);
  5673. }
  5674. }
  5675. };
  5676. }
  5677. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5678. // Static
  5679. get: function () {
  5680. return ShadowGenerator._FILTER_NONE;
  5681. },
  5682. enumerable: true,
  5683. configurable: true
  5684. });
  5685. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5686. get: function () {
  5687. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5688. },
  5689. enumerable: true,
  5690. configurable: true
  5691. });
  5692. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5693. get: function () {
  5694. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5695. },
  5696. enumerable: true,
  5697. configurable: true
  5698. });
  5699. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5700. get: function () {
  5701. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5702. },
  5703. set: function (value) {
  5704. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5705. },
  5706. enumerable: true,
  5707. configurable: true
  5708. });
  5709. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5710. get: function () {
  5711. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5712. },
  5713. set: function (value) {
  5714. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5715. },
  5716. enumerable: true,
  5717. configurable: true
  5718. });
  5719. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5720. var defines = [];
  5721. if (this.useVarianceShadowMap) {
  5722. defines.push("#define VSM");
  5723. }
  5724. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5725. var mesh = subMesh.getMesh();
  5726. var scene = mesh.getScene();
  5727. var material = subMesh.getMaterial();
  5728. // Alpha test
  5729. if (material && material.needAlphaTesting()) {
  5730. defines.push("#define ALPHATEST");
  5731. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5732. attribs.push(BABYLON.VertexBuffer.UVKind);
  5733. defines.push("#define UV1");
  5734. }
  5735. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5736. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5737. defines.push("#define UV2");
  5738. }
  5739. }
  5740. // Bones
  5741. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  5742. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5743. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5744. defines.push("#define BONES");
  5745. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5746. }
  5747. // Instances
  5748. if (useInstances) {
  5749. defines.push("#define INSTANCES");
  5750. attribs.push("world0");
  5751. attribs.push("world1");
  5752. attribs.push("world2");
  5753. attribs.push("world3");
  5754. }
  5755. // Get correct effect
  5756. var join = defines.join("\n");
  5757. if (this._cachedDefines !== join) {
  5758. this._cachedDefines = join;
  5759. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5760. }
  5761. return this._effect.isReady();
  5762. };
  5763. ShadowGenerator.prototype.getShadowMap = function () {
  5764. return this._shadowMap;
  5765. };
  5766. ShadowGenerator.prototype.getLight = function () {
  5767. return this._light;
  5768. };
  5769. // Methods
  5770. ShadowGenerator.prototype.getTransformMatrix = function () {
  5771. var lightPosition = this._light.position;
  5772. var lightDirection = this._light.direction;
  5773. if (this._light.computeTransformedPosition()) {
  5774. lightPosition = this._light.transformedPosition;
  5775. }
  5776. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5777. this._cachedPosition = lightPosition.clone();
  5778. this._cachedDirection = lightDirection.clone();
  5779. var activeCamera = this._scene.activeCamera;
  5780. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5781. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5782. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5783. }
  5784. return this._transformMatrix;
  5785. };
  5786. ShadowGenerator.prototype.getDarkness = function () {
  5787. return this._darkness;
  5788. };
  5789. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5790. if (darkness >= 1.0)
  5791. this._darkness = 1.0;
  5792. else if (darkness <= 0.0)
  5793. this._darkness = 0.0;
  5794. else
  5795. this._darkness = darkness;
  5796. };
  5797. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5798. this._transparencyShadow = hasShadow;
  5799. };
  5800. ShadowGenerator.prototype.dispose = function () {
  5801. this._shadowMap.dispose();
  5802. };
  5803. ShadowGenerator._FILTER_NONE = 0;
  5804. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5805. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5806. return ShadowGenerator;
  5807. })();
  5808. BABYLON.ShadowGenerator = ShadowGenerator;
  5809. })(BABYLON || (BABYLON = {}));
  5810. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5811. var BABYLON;
  5812. (function (BABYLON) {
  5813. var HemisphericLight = (function (_super) {
  5814. __extends(HemisphericLight, _super);
  5815. function HemisphericLight(name, direction, scene) {
  5816. _super.call(this, name, scene);
  5817. this.direction = direction;
  5818. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5819. }
  5820. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5821. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5822. return this.direction;
  5823. };
  5824. HemisphericLight.prototype.getShadowGenerator = function () {
  5825. return null;
  5826. };
  5827. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5828. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5829. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5830. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5831. };
  5832. HemisphericLight.prototype._getWorldMatrix = function () {
  5833. if (!this._worldMatrix) {
  5834. this._worldMatrix = BABYLON.Matrix.Identity();
  5835. }
  5836. return this._worldMatrix;
  5837. };
  5838. return HemisphericLight;
  5839. })(BABYLON.Light);
  5840. BABYLON.HemisphericLight = HemisphericLight;
  5841. })(BABYLON || (BABYLON = {}));
  5842. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  5843. (function (BABYLON) {
  5844. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5845. if (boxMin.x > sphereCenter.x + sphereRadius)
  5846. return false;
  5847. if (sphereCenter.x - sphereRadius > boxMax.x)
  5848. return false;
  5849. if (boxMin.y > sphereCenter.y + sphereRadius)
  5850. return false;
  5851. if (sphereCenter.y - sphereRadius > boxMax.y)
  5852. return false;
  5853. if (boxMin.z > sphereCenter.z + sphereRadius)
  5854. return false;
  5855. if (sphereCenter.z - sphereRadius > boxMax.z)
  5856. return false;
  5857. return true;
  5858. };
  5859. var getLowestRoot = function (a, b, c, maxR) {
  5860. var determinant = b * b - 4.0 * a * c;
  5861. var result = { root: 0, found: false };
  5862. if (determinant < 0)
  5863. return result;
  5864. var sqrtD = Math.sqrt(determinant);
  5865. var r1 = (-b - sqrtD) / (2.0 * a);
  5866. var r2 = (-b + sqrtD) / (2.0 * a);
  5867. if (r1 > r2) {
  5868. var temp = r2;
  5869. r2 = r1;
  5870. r1 = temp;
  5871. }
  5872. if (r1 > 0 && r1 < maxR) {
  5873. result.root = r1;
  5874. result.found = true;
  5875. return result;
  5876. }
  5877. if (r2 > 0 && r2 < maxR) {
  5878. result.root = r2;
  5879. result.found = true;
  5880. return result;
  5881. }
  5882. return result;
  5883. };
  5884. var Collider = (function () {
  5885. function Collider() {
  5886. this.radius = new BABYLON.Vector3(1, 1, 1);
  5887. this.retry = 0;
  5888. this.basePointWorld = BABYLON.Vector3.Zero();
  5889. this.velocityWorld = BABYLON.Vector3.Zero();
  5890. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5891. this._collisionPoint = BABYLON.Vector3.Zero();
  5892. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5893. this._tempVector = BABYLON.Vector3.Zero();
  5894. this._tempVector2 = BABYLON.Vector3.Zero();
  5895. this._tempVector3 = BABYLON.Vector3.Zero();
  5896. this._tempVector4 = BABYLON.Vector3.Zero();
  5897. this._edge = BABYLON.Vector3.Zero();
  5898. this._baseToVertex = BABYLON.Vector3.Zero();
  5899. this._destinationPoint = BABYLON.Vector3.Zero();
  5900. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5901. this._displacementVector = BABYLON.Vector3.Zero();
  5902. }
  5903. // Methods
  5904. Collider.prototype._initialize = function (source, dir, e) {
  5905. this.velocity = dir;
  5906. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5907. this.basePoint = source;
  5908. source.multiplyToRef(this.radius, this.basePointWorld);
  5909. dir.multiplyToRef(this.radius, this.velocityWorld);
  5910. this.velocityWorldLength = this.velocityWorld.length();
  5911. this.epsilon = e;
  5912. this.collisionFound = false;
  5913. };
  5914. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5915. pa.subtractToRef(point, this._tempVector);
  5916. pb.subtractToRef(point, this._tempVector2);
  5917. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5918. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5919. if (d < 0)
  5920. return false;
  5921. pc.subtractToRef(point, this._tempVector3);
  5922. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5923. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5924. if (d < 0)
  5925. return false;
  5926. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5927. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5928. return d >= 0;
  5929. };
  5930. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5931. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5932. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5933. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5934. return false;
  5935. }
  5936. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5937. return false;
  5938. return true;
  5939. };
  5940. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5941. var t0;
  5942. var embeddedInPlane = false;
  5943. if (!subMesh._trianglePlanes) {
  5944. subMesh._trianglePlanes = [];
  5945. }
  5946. if (!subMesh._trianglePlanes[faceIndex]) {
  5947. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5948. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5949. }
  5950. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5951. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5952. return;
  5953. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5954. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5955. if (normalDotVelocity == 0) {
  5956. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5957. return;
  5958. embeddedInPlane = true;
  5959. t0 = 0;
  5960. }
  5961. else {
  5962. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5963. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5964. if (t0 > t1) {
  5965. var temp = t1;
  5966. t1 = t0;
  5967. t0 = temp;
  5968. }
  5969. if (t0 > 1.0 || t1 < 0.0)
  5970. return;
  5971. if (t0 < 0)
  5972. t0 = 0;
  5973. if (t0 > 1.0)
  5974. t0 = 1.0;
  5975. }
  5976. this._collisionPoint.copyFromFloats(0, 0, 0);
  5977. var found = false;
  5978. var t = 1.0;
  5979. if (!embeddedInPlane) {
  5980. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5981. this.velocity.scaleToRef(t0, this._tempVector);
  5982. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5983. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5984. found = true;
  5985. t = t0;
  5986. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5987. }
  5988. }
  5989. if (!found) {
  5990. var velocitySquaredLength = this.velocity.lengthSquared();
  5991. var a = velocitySquaredLength;
  5992. this.basePoint.subtractToRef(p1, this._tempVector);
  5993. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5994. var c = this._tempVector.lengthSquared() - 1.0;
  5995. var lowestRoot = getLowestRoot(a, b, c, t);
  5996. if (lowestRoot.found) {
  5997. t = lowestRoot.root;
  5998. found = true;
  5999. this._collisionPoint.copyFrom(p1);
  6000. }
  6001. this.basePoint.subtractToRef(p2, this._tempVector);
  6002. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6003. c = this._tempVector.lengthSquared() - 1.0;
  6004. lowestRoot = getLowestRoot(a, b, c, t);
  6005. if (lowestRoot.found) {
  6006. t = lowestRoot.root;
  6007. found = true;
  6008. this._collisionPoint.copyFrom(p2);
  6009. }
  6010. this.basePoint.subtractToRef(p3, this._tempVector);
  6011. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6012. c = this._tempVector.lengthSquared() - 1.0;
  6013. lowestRoot = getLowestRoot(a, b, c, t);
  6014. if (lowestRoot.found) {
  6015. t = lowestRoot.root;
  6016. found = true;
  6017. this._collisionPoint.copyFrom(p3);
  6018. }
  6019. p2.subtractToRef(p1, this._edge);
  6020. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6021. var edgeSquaredLength = this._edge.lengthSquared();
  6022. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6023. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6024. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6025. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6026. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6027. lowestRoot = getLowestRoot(a, b, c, t);
  6028. if (lowestRoot.found) {
  6029. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6030. if (f >= 0.0 && f <= 1.0) {
  6031. t = lowestRoot.root;
  6032. found = true;
  6033. this._edge.scaleInPlace(f);
  6034. p1.addToRef(this._edge, this._collisionPoint);
  6035. }
  6036. }
  6037. p3.subtractToRef(p2, this._edge);
  6038. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6039. edgeSquaredLength = this._edge.lengthSquared();
  6040. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6041. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6042. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6043. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6044. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6045. lowestRoot = getLowestRoot(a, b, c, t);
  6046. if (lowestRoot.found) {
  6047. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6048. if (f >= 0.0 && f <= 1.0) {
  6049. t = lowestRoot.root;
  6050. found = true;
  6051. this._edge.scaleInPlace(f);
  6052. p2.addToRef(this._edge, this._collisionPoint);
  6053. }
  6054. }
  6055. p1.subtractToRef(p3, this._edge);
  6056. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6057. edgeSquaredLength = this._edge.lengthSquared();
  6058. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6059. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6060. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6061. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6062. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6063. lowestRoot = getLowestRoot(a, b, c, t);
  6064. if (lowestRoot.found) {
  6065. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6066. if (f >= 0.0 && f <= 1.0) {
  6067. t = lowestRoot.root;
  6068. found = true;
  6069. this._edge.scaleInPlace(f);
  6070. p3.addToRef(this._edge, this._collisionPoint);
  6071. }
  6072. }
  6073. }
  6074. if (found) {
  6075. var distToCollision = t * this.velocity.length();
  6076. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6077. if (!this.intersectionPoint) {
  6078. this.intersectionPoint = this._collisionPoint.clone();
  6079. }
  6080. else {
  6081. this.intersectionPoint.copyFrom(this._collisionPoint);
  6082. }
  6083. this.nearestDistance = distToCollision;
  6084. this.collisionFound = true;
  6085. this.collidedMesh = subMesh.getMesh();
  6086. }
  6087. }
  6088. };
  6089. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6090. for (var i = indexStart; i < indexEnd; i += 3) {
  6091. var p1 = pts[indices[i] - decal];
  6092. var p2 = pts[indices[i + 1] - decal];
  6093. var p3 = pts[indices[i + 2] - decal];
  6094. this._testTriangle(i, subMesh, p3, p2, p1);
  6095. }
  6096. };
  6097. Collider.prototype._getResponse = function (pos, vel) {
  6098. pos.addToRef(vel, this._destinationPoint);
  6099. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6100. this.basePoint.addToRef(vel, pos);
  6101. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6102. this._slidePlaneNormal.normalize();
  6103. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6104. pos.addInPlace(this._displacementVector);
  6105. this.intersectionPoint.addInPlace(this._displacementVector);
  6106. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6107. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6108. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6109. };
  6110. return Collider;
  6111. })();
  6112. BABYLON.Collider = Collider;
  6113. })(BABYLON || (BABYLON = {}));
  6114. //# sourceMappingURL=babylon.collider.js.map
  6115. var BABYLON;
  6116. (function (BABYLON) {
  6117. var Camera = (function (_super) {
  6118. __extends(Camera, _super);
  6119. function Camera(name, position, scene) {
  6120. _super.call(this, name, scene);
  6121. this.position = position;
  6122. // Members
  6123. this.upVector = BABYLON.Vector3.Up();
  6124. this.orthoLeft = null;
  6125. this.orthoRight = null;
  6126. this.orthoBottom = null;
  6127. this.orthoTop = null;
  6128. this.fov = 0.8;
  6129. this.minZ = 1.0;
  6130. this.maxZ = 10000.0;
  6131. this.inertia = 0.9;
  6132. this.mode = Camera.PERSPECTIVE_CAMERA;
  6133. this.isIntermediate = false;
  6134. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6135. this.subCameras = [];
  6136. this.layerMask = 0xFFFFFFFF;
  6137. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6138. this._projectionMatrix = new BABYLON.Matrix();
  6139. this._postProcesses = new Array();
  6140. this._postProcessesTakenIndices = [];
  6141. scene.cameras.push(this);
  6142. if (!scene.activeCamera) {
  6143. scene.activeCamera = this;
  6144. }
  6145. }
  6146. //Cache
  6147. Camera.prototype._initCache = function () {
  6148. _super.prototype._initCache.call(this);
  6149. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6150. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6151. this._cache.mode = undefined;
  6152. this._cache.minZ = undefined;
  6153. this._cache.maxZ = undefined;
  6154. this._cache.fov = undefined;
  6155. this._cache.aspectRatio = undefined;
  6156. this._cache.orthoLeft = undefined;
  6157. this._cache.orthoRight = undefined;
  6158. this._cache.orthoBottom = undefined;
  6159. this._cache.orthoTop = undefined;
  6160. this._cache.renderWidth = undefined;
  6161. this._cache.renderHeight = undefined;
  6162. };
  6163. Camera.prototype._updateCache = function (ignoreParentClass) {
  6164. if (!ignoreParentClass) {
  6165. _super.prototype._updateCache.call(this);
  6166. }
  6167. var engine = this.getEngine();
  6168. this._cache.position.copyFrom(this.position);
  6169. this._cache.upVector.copyFrom(this.upVector);
  6170. this._cache.mode = this.mode;
  6171. this._cache.minZ = this.minZ;
  6172. this._cache.maxZ = this.maxZ;
  6173. this._cache.fov = this.fov;
  6174. this._cache.aspectRatio = engine.getAspectRatio(this);
  6175. this._cache.orthoLeft = this.orthoLeft;
  6176. this._cache.orthoRight = this.orthoRight;
  6177. this._cache.orthoBottom = this.orthoBottom;
  6178. this._cache.orthoTop = this.orthoTop;
  6179. this._cache.renderWidth = engine.getRenderWidth();
  6180. this._cache.renderHeight = engine.getRenderHeight();
  6181. };
  6182. Camera.prototype._updateFromScene = function () {
  6183. this.updateCache();
  6184. this._update();
  6185. };
  6186. // Synchronized
  6187. Camera.prototype._isSynchronized = function () {
  6188. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6189. };
  6190. Camera.prototype._isSynchronizedViewMatrix = function () {
  6191. if (!_super.prototype._isSynchronized.call(this))
  6192. return false;
  6193. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6194. };
  6195. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6196. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6197. if (!check) {
  6198. return false;
  6199. }
  6200. var engine = this.getEngine();
  6201. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6202. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6203. }
  6204. else {
  6205. 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();
  6206. }
  6207. return check;
  6208. };
  6209. // Controls
  6210. Camera.prototype.attachControl = function (element) {
  6211. };
  6212. Camera.prototype.detachControl = function (element) {
  6213. };
  6214. Camera.prototype._update = function () {
  6215. };
  6216. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6217. if (insertAt === void 0) { insertAt = null; }
  6218. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6219. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6220. return 0;
  6221. }
  6222. if (insertAt == null || insertAt < 0) {
  6223. this._postProcesses.push(postProcess);
  6224. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6225. return this._postProcesses.length - 1;
  6226. }
  6227. var add = 0;
  6228. if (this._postProcesses[insertAt]) {
  6229. var start = this._postProcesses.length - 1;
  6230. for (var i = start; i >= insertAt + 1; --i) {
  6231. this._postProcesses[i + 1] = this._postProcesses[i];
  6232. }
  6233. add = 1;
  6234. }
  6235. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6236. if (this._postProcessesTakenIndices[i] < insertAt) {
  6237. continue;
  6238. }
  6239. start = this._postProcessesTakenIndices.length - 1;
  6240. for (var j = start; j >= i; --j) {
  6241. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6242. }
  6243. this._postProcessesTakenIndices[i] = insertAt;
  6244. break;
  6245. }
  6246. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6247. this._postProcessesTakenIndices.push(insertAt);
  6248. }
  6249. var result = insertAt + add;
  6250. this._postProcesses[result] = postProcess;
  6251. return result;
  6252. };
  6253. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6254. if (atIndices === void 0) { atIndices = null; }
  6255. var result = [];
  6256. if (!atIndices) {
  6257. var length = this._postProcesses.length;
  6258. for (var i = 0; i < length; i++) {
  6259. if (this._postProcesses[i] !== postProcess) {
  6260. continue;
  6261. }
  6262. delete this._postProcesses[i];
  6263. var index = this._postProcessesTakenIndices.indexOf(i);
  6264. this._postProcessesTakenIndices.splice(index, 1);
  6265. }
  6266. }
  6267. else {
  6268. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6269. for (i = 0; i < atIndices.length; i++) {
  6270. var foundPostProcess = this._postProcesses[atIndices[i]];
  6271. if (foundPostProcess !== postProcess) {
  6272. result.push(i);
  6273. continue;
  6274. }
  6275. delete this._postProcesses[atIndices[i]];
  6276. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6277. this._postProcessesTakenIndices.splice(index, 1);
  6278. }
  6279. }
  6280. return result;
  6281. };
  6282. Camera.prototype.getWorldMatrix = function () {
  6283. if (!this._worldMatrix) {
  6284. this._worldMatrix = BABYLON.Matrix.Identity();
  6285. }
  6286. var viewMatrix = this.getViewMatrix();
  6287. viewMatrix.invertToRef(this._worldMatrix);
  6288. return this._worldMatrix;
  6289. };
  6290. Camera.prototype._getViewMatrix = function () {
  6291. return BABYLON.Matrix.Identity();
  6292. };
  6293. Camera.prototype.getViewMatrix = function () {
  6294. this._computedViewMatrix = this._computeViewMatrix();
  6295. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6296. return this._computedViewMatrix;
  6297. }
  6298. if (!this._worldMatrix) {
  6299. this._worldMatrix = BABYLON.Matrix.Identity();
  6300. }
  6301. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6302. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6303. this._computedViewMatrix.invert();
  6304. this._currentRenderId = this.getScene().getRenderId();
  6305. return this._computedViewMatrix;
  6306. };
  6307. Camera.prototype._computeViewMatrix = function (force) {
  6308. if (!force && this._isSynchronizedViewMatrix()) {
  6309. return this._computedViewMatrix;
  6310. }
  6311. this._computedViewMatrix = this._getViewMatrix();
  6312. if (!this.parent || !this.parent.getWorldMatrix) {
  6313. this._currentRenderId = this.getScene().getRenderId();
  6314. }
  6315. return this._computedViewMatrix;
  6316. };
  6317. Camera.prototype.getProjectionMatrix = function (force) {
  6318. if (!force && this._isSynchronizedProjectionMatrix()) {
  6319. return this._projectionMatrix;
  6320. }
  6321. var engine = this.getEngine();
  6322. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6323. if (this.minZ <= 0) {
  6324. this.minZ = 0.1;
  6325. }
  6326. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  6327. return this._projectionMatrix;
  6328. }
  6329. var halfWidth = engine.getRenderWidth() / 2.0;
  6330. var halfHeight = engine.getRenderHeight() / 2.0;
  6331. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6332. return this._projectionMatrix;
  6333. };
  6334. Camera.prototype.dispose = function () {
  6335. // Remove from scene
  6336. var index = this.getScene().cameras.indexOf(this);
  6337. this.getScene().cameras.splice(index, 1);
  6338. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6339. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6340. }
  6341. };
  6342. // Statics
  6343. Camera.PERSPECTIVE_CAMERA = 0;
  6344. Camera.ORTHOGRAPHIC_CAMERA = 1;
  6345. return Camera;
  6346. })(BABYLON.Node);
  6347. BABYLON.Camera = Camera;
  6348. })(BABYLON || (BABYLON = {}));
  6349. //# sourceMappingURL=babylon.camera.js.map
  6350. var BABYLON;
  6351. (function (BABYLON) {
  6352. var TargetCamera = (function (_super) {
  6353. __extends(TargetCamera, _super);
  6354. function TargetCamera(name, position, scene) {
  6355. _super.call(this, name, position, scene);
  6356. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6357. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6358. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6359. this.speed = 2.0;
  6360. this.noRotationConstraint = false;
  6361. this.lockedTarget = null;
  6362. this._currentTarget = BABYLON.Vector3.Zero();
  6363. this._viewMatrix = BABYLON.Matrix.Zero();
  6364. this._camMatrix = BABYLON.Matrix.Zero();
  6365. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6366. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6367. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6368. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6369. this._lookAtTemp = BABYLON.Matrix.Zero();
  6370. this._tempMatrix = BABYLON.Matrix.Zero();
  6371. }
  6372. TargetCamera.prototype._getLockedTargetPosition = function () {
  6373. if (!this.lockedTarget) {
  6374. return null;
  6375. }
  6376. return this.lockedTarget.position || this.lockedTarget;
  6377. };
  6378. // Cache
  6379. TargetCamera.prototype._initCache = function () {
  6380. _super.prototype._initCache.call(this);
  6381. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6382. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6383. };
  6384. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6385. if (!ignoreParentClass) {
  6386. _super.prototype._updateCache.call(this);
  6387. }
  6388. var lockedTargetPosition = this._getLockedTargetPosition();
  6389. if (!lockedTargetPosition) {
  6390. this._cache.lockedTarget = null;
  6391. }
  6392. else {
  6393. if (!this._cache.lockedTarget) {
  6394. this._cache.lockedTarget = lockedTargetPosition.clone();
  6395. }
  6396. else {
  6397. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6398. }
  6399. }
  6400. this._cache.rotation.copyFrom(this.rotation);
  6401. };
  6402. // Synchronized
  6403. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6404. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6405. return false;
  6406. }
  6407. var lockedTargetPosition = this._getLockedTargetPosition();
  6408. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6409. };
  6410. // Methods
  6411. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6412. var engine = this.getEngine();
  6413. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6414. };
  6415. // Target
  6416. TargetCamera.prototype.setTarget = function (target) {
  6417. this.upVector.normalize();
  6418. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6419. this._camMatrix.invert();
  6420. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6421. var vDir = target.subtract(this.position);
  6422. if (vDir.x >= 0.0) {
  6423. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6424. }
  6425. else {
  6426. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6427. }
  6428. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6429. if (isNaN(this.rotation.x)) {
  6430. this.rotation.x = 0;
  6431. }
  6432. if (isNaN(this.rotation.y)) {
  6433. this.rotation.y = 0;
  6434. }
  6435. if (isNaN(this.rotation.z)) {
  6436. this.rotation.z = 0;
  6437. }
  6438. };
  6439. TargetCamera.prototype.getTarget = function () {
  6440. return this._currentTarget;
  6441. };
  6442. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6443. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6444. };
  6445. TargetCamera.prototype._updatePosition = function () {
  6446. this.position.addInPlace(this.cameraDirection);
  6447. };
  6448. TargetCamera.prototype._update = function () {
  6449. var needToMove = this._decideIfNeedsToMove();
  6450. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6451. // Move
  6452. if (needToMove) {
  6453. this._updatePosition();
  6454. }
  6455. // Rotate
  6456. if (needToRotate) {
  6457. this.rotation.x += this.cameraRotation.x;
  6458. this.rotation.y += this.cameraRotation.y;
  6459. if (!this.noRotationConstraint) {
  6460. var limit = (Math.PI / 2) * 0.95;
  6461. if (this.rotation.x > limit)
  6462. this.rotation.x = limit;
  6463. if (this.rotation.x < -limit)
  6464. this.rotation.x = -limit;
  6465. }
  6466. }
  6467. // Inertia
  6468. if (needToMove) {
  6469. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6470. this.cameraDirection.x = 0;
  6471. }
  6472. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6473. this.cameraDirection.y = 0;
  6474. }
  6475. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6476. this.cameraDirection.z = 0;
  6477. }
  6478. this.cameraDirection.scaleInPlace(this.inertia);
  6479. }
  6480. if (needToRotate) {
  6481. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6482. this.cameraRotation.x = 0;
  6483. }
  6484. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6485. this.cameraRotation.y = 0;
  6486. }
  6487. this.cameraRotation.scaleInPlace(this.inertia);
  6488. }
  6489. };
  6490. TargetCamera.prototype._getViewMatrix = function () {
  6491. if (!this.lockedTarget) {
  6492. // Compute
  6493. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6494. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6495. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6496. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6497. this._lookAtTemp.invert();
  6498. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6499. }
  6500. else {
  6501. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6502. }
  6503. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6504. // Computing target and final matrix
  6505. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6506. }
  6507. else {
  6508. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6509. }
  6510. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6511. return this._viewMatrix;
  6512. };
  6513. return TargetCamera;
  6514. })(BABYLON.Camera);
  6515. BABYLON.TargetCamera = TargetCamera;
  6516. })(BABYLON || (BABYLON = {}));
  6517. //# sourceMappingURL=babylon.targetCamera.js.map
  6518. var BABYLON;
  6519. (function (BABYLON) {
  6520. var FollowCamera = (function (_super) {
  6521. __extends(FollowCamera, _super);
  6522. function FollowCamera(name, position, scene) {
  6523. _super.call(this, name, position, scene);
  6524. this.radius = 12;
  6525. this.rotationOffset = 0;
  6526. this.heightOffset = 4;
  6527. this.cameraAcceleration = 0.05;
  6528. this.maxCameraSpeed = 20;
  6529. }
  6530. FollowCamera.prototype.getRadians = function (degrees) {
  6531. return degrees * Math.PI / 180;
  6532. };
  6533. FollowCamera.prototype.follow = function (cameraTarget) {
  6534. if (!cameraTarget)
  6535. return;
  6536. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6537. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6538. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6539. var dx = targetX - this.position.x;
  6540. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6541. var dz = (targetZ) - this.position.z;
  6542. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  6543. var vy = dy * this.cameraAcceleration;
  6544. var vz = dz * this.cameraAcceleration * 2;
  6545. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6546. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6547. }
  6548. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6549. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6550. }
  6551. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6552. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6553. }
  6554. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6555. this.setTarget(cameraTarget.position);
  6556. };
  6557. FollowCamera.prototype._update = function () {
  6558. _super.prototype._update.call(this);
  6559. this.follow(this.target);
  6560. };
  6561. return FollowCamera;
  6562. })(BABYLON.TargetCamera);
  6563. BABYLON.FollowCamera = FollowCamera;
  6564. })(BABYLON || (BABYLON = {}));
  6565. //# sourceMappingURL=babylon.followCamera.js.map
  6566. var BABYLON;
  6567. (function (BABYLON) {
  6568. var FreeCamera = (function (_super) {
  6569. __extends(FreeCamera, _super);
  6570. function FreeCamera(name, position, scene) {
  6571. _super.call(this, name, position, scene);
  6572. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6573. this.keysUp = [38];
  6574. this.keysDown = [40];
  6575. this.keysLeft = [37];
  6576. this.keysRight = [39];
  6577. this.checkCollisions = false;
  6578. this.applyGravity = false;
  6579. this.angularSensibility = 2000.0;
  6580. this._keys = [];
  6581. this._collider = new BABYLON.Collider();
  6582. this._needMoveForGravity = true;
  6583. this._oldPosition = BABYLON.Vector3.Zero();
  6584. this._diffPosition = BABYLON.Vector3.Zero();
  6585. this._newPosition = BABYLON.Vector3.Zero();
  6586. }
  6587. // Controls
  6588. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6589. var _this = this;
  6590. var previousPosition;
  6591. var engine = this.getEngine();
  6592. if (this._attachedElement) {
  6593. return;
  6594. }
  6595. this._attachedElement = element;
  6596. if (this._onMouseDown === undefined) {
  6597. this._onMouseDown = function (evt) {
  6598. previousPosition = {
  6599. x: evt.clientX,
  6600. y: evt.clientY
  6601. };
  6602. if (!noPreventDefault) {
  6603. evt.preventDefault();
  6604. }
  6605. };
  6606. this._onMouseUp = function (evt) {
  6607. previousPosition = null;
  6608. if (!noPreventDefault) {
  6609. evt.preventDefault();
  6610. }
  6611. };
  6612. this._onMouseOut = function (evt) {
  6613. previousPosition = null;
  6614. _this._keys = [];
  6615. if (!noPreventDefault) {
  6616. evt.preventDefault();
  6617. }
  6618. };
  6619. this._onMouseMove = function (evt) {
  6620. if (!previousPosition && !engine.isPointerLock) {
  6621. return;
  6622. }
  6623. var offsetX;
  6624. var offsetY;
  6625. if (!engine.isPointerLock) {
  6626. offsetX = evt.clientX - previousPosition.x;
  6627. offsetY = evt.clientY - previousPosition.y;
  6628. }
  6629. else {
  6630. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6631. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6632. }
  6633. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6634. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6635. previousPosition = {
  6636. x: evt.clientX,
  6637. y: evt.clientY
  6638. };
  6639. if (!noPreventDefault) {
  6640. evt.preventDefault();
  6641. }
  6642. };
  6643. this._onKeyDown = function (evt) {
  6644. 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) {
  6645. var index = _this._keys.indexOf(evt.keyCode);
  6646. if (index === -1) {
  6647. _this._keys.push(evt.keyCode);
  6648. }
  6649. if (!noPreventDefault) {
  6650. evt.preventDefault();
  6651. }
  6652. }
  6653. };
  6654. this._onKeyUp = function (evt) {
  6655. 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) {
  6656. var index = _this._keys.indexOf(evt.keyCode);
  6657. if (index >= 0) {
  6658. _this._keys.splice(index, 1);
  6659. }
  6660. if (!noPreventDefault) {
  6661. evt.preventDefault();
  6662. }
  6663. }
  6664. };
  6665. this._onLostFocus = function () {
  6666. _this._keys = [];
  6667. };
  6668. this._reset = function () {
  6669. _this._keys = [];
  6670. previousPosition = null;
  6671. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6672. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6673. };
  6674. }
  6675. element.addEventListener("mousedown", this._onMouseDown, false);
  6676. element.addEventListener("mouseup", this._onMouseUp, false);
  6677. element.addEventListener("mouseout", this._onMouseOut, false);
  6678. element.addEventListener("mousemove", this._onMouseMove, false);
  6679. BABYLON.Tools.RegisterTopRootEvents([
  6680. { name: "keydown", handler: this._onKeyDown },
  6681. { name: "keyup", handler: this._onKeyUp },
  6682. { name: "blur", handler: this._onLostFocus }
  6683. ]);
  6684. };
  6685. FreeCamera.prototype.detachControl = function (element) {
  6686. if (this._attachedElement != element) {
  6687. return;
  6688. }
  6689. element.removeEventListener("mousedown", this._onMouseDown);
  6690. element.removeEventListener("mouseup", this._onMouseUp);
  6691. element.removeEventListener("mouseout", this._onMouseOut);
  6692. element.removeEventListener("mousemove", this._onMouseMove);
  6693. BABYLON.Tools.UnregisterTopRootEvents([
  6694. { name: "keydown", handler: this._onKeyDown },
  6695. { name: "keyup", handler: this._onKeyUp },
  6696. { name: "blur", handler: this._onLostFocus }
  6697. ]);
  6698. this._attachedElement = null;
  6699. if (this._reset) {
  6700. this._reset();
  6701. }
  6702. };
  6703. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6704. var globalPosition;
  6705. if (this.parent) {
  6706. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6707. }
  6708. else {
  6709. globalPosition = this.position;
  6710. }
  6711. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6712. this._collider.radius = this.ellipsoid;
  6713. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6714. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6715. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6716. this.position.addInPlace(this._diffPosition);
  6717. if (this.onCollide) {
  6718. this.onCollide(this._collider.collidedMesh);
  6719. }
  6720. }
  6721. };
  6722. FreeCamera.prototype._checkInputs = function () {
  6723. if (!this._localDirection) {
  6724. this._localDirection = BABYLON.Vector3.Zero();
  6725. this._transformedDirection = BABYLON.Vector3.Zero();
  6726. }
  6727. for (var index = 0; index < this._keys.length; index++) {
  6728. var keyCode = this._keys[index];
  6729. var speed = this._computeLocalCameraSpeed();
  6730. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6731. this._localDirection.copyFromFloats(-speed, 0, 0);
  6732. }
  6733. else if (this.keysUp.indexOf(keyCode) !== -1) {
  6734. this._localDirection.copyFromFloats(0, 0, speed);
  6735. }
  6736. else if (this.keysRight.indexOf(keyCode) !== -1) {
  6737. this._localDirection.copyFromFloats(speed, 0, 0);
  6738. }
  6739. else if (this.keysDown.indexOf(keyCode) !== -1) {
  6740. this._localDirection.copyFromFloats(0, 0, -speed);
  6741. }
  6742. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6743. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6744. this.cameraDirection.addInPlace(this._transformedDirection);
  6745. }
  6746. };
  6747. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6748. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6749. };
  6750. FreeCamera.prototype._updatePosition = function () {
  6751. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6752. this._collideWithWorld(this.cameraDirection);
  6753. if (this.applyGravity) {
  6754. var oldPosition = this.position;
  6755. this._collideWithWorld(this.getScene().gravity);
  6756. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6757. }
  6758. }
  6759. else {
  6760. this.position.addInPlace(this.cameraDirection);
  6761. }
  6762. };
  6763. FreeCamera.prototype._update = function () {
  6764. this._checkInputs();
  6765. _super.prototype._update.call(this);
  6766. };
  6767. return FreeCamera;
  6768. })(BABYLON.TargetCamera);
  6769. BABYLON.FreeCamera = FreeCamera;
  6770. })(BABYLON || (BABYLON = {}));
  6771. //# sourceMappingURL=babylon.freeCamera.js.map
  6772. var BABYLON;
  6773. (function (BABYLON) {
  6774. // We're mainly based on the logic defined into the FreeCamera code
  6775. var TouchCamera = (function (_super) {
  6776. __extends(TouchCamera, _super);
  6777. function TouchCamera(name, position, scene) {
  6778. _super.call(this, name, position, scene);
  6779. this._offsetX = null;
  6780. this._offsetY = null;
  6781. this._pointerCount = 0;
  6782. this._pointerPressed = [];
  6783. this.angularSensibility = 200000.0;
  6784. this.moveSensibility = 500.0;
  6785. }
  6786. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6787. var _this = this;
  6788. var previousPosition;
  6789. if (this._attachedCanvas) {
  6790. return;
  6791. }
  6792. this._attachedCanvas = canvas;
  6793. if (this._onPointerDown === undefined) {
  6794. this._onPointerDown = function (evt) {
  6795. if (!noPreventDefault) {
  6796. evt.preventDefault();
  6797. }
  6798. _this._pointerPressed.push(evt.pointerId);
  6799. if (_this._pointerPressed.length !== 1) {
  6800. return;
  6801. }
  6802. previousPosition = {
  6803. x: evt.clientX,
  6804. y: evt.clientY
  6805. };
  6806. };
  6807. this._onPointerUp = function (evt) {
  6808. if (!noPreventDefault) {
  6809. evt.preventDefault();
  6810. }
  6811. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6812. if (index === -1) {
  6813. return;
  6814. }
  6815. _this._pointerPressed.splice(index, 1);
  6816. if (index != 0) {
  6817. return;
  6818. }
  6819. previousPosition = null;
  6820. _this._offsetX = null;
  6821. _this._offsetY = null;
  6822. };
  6823. this._onPointerMove = function (evt) {
  6824. if (!noPreventDefault) {
  6825. evt.preventDefault();
  6826. }
  6827. if (!previousPosition) {
  6828. return;
  6829. }
  6830. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6831. if (index != 0) {
  6832. return;
  6833. }
  6834. _this._offsetX = evt.clientX - previousPosition.x;
  6835. _this._offsetY = -(evt.clientY - previousPosition.y);
  6836. };
  6837. this._onLostFocus = function () {
  6838. _this._offsetX = null;
  6839. _this._offsetY = null;
  6840. };
  6841. }
  6842. canvas.addEventListener("pointerdown", this._onPointerDown);
  6843. canvas.addEventListener("pointerup", this._onPointerUp);
  6844. canvas.addEventListener("pointerout", this._onPointerUp);
  6845. canvas.addEventListener("pointermove", this._onPointerMove);
  6846. BABYLON.Tools.RegisterTopRootEvents([
  6847. { name: "blur", handler: this._onLostFocus }
  6848. ]);
  6849. };
  6850. TouchCamera.prototype.detachControl = function (canvas) {
  6851. if (this._attachedCanvas != canvas) {
  6852. return;
  6853. }
  6854. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6855. canvas.removeEventListener("pointerup", this._onPointerUp);
  6856. canvas.removeEventListener("pointerout", this._onPointerUp);
  6857. canvas.removeEventListener("pointermove", this._onPointerMove);
  6858. BABYLON.Tools.UnregisterTopRootEvents([
  6859. { name: "blur", handler: this._onLostFocus }
  6860. ]);
  6861. this._attachedCanvas = null;
  6862. };
  6863. TouchCamera.prototype._checkInputs = function () {
  6864. if (!this._offsetX) {
  6865. return;
  6866. }
  6867. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6868. if (this._pointerPressed.length > 1) {
  6869. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6870. }
  6871. else {
  6872. var speed = this._computeLocalCameraSpeed();
  6873. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6874. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6875. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6876. }
  6877. };
  6878. return TouchCamera;
  6879. })(BABYLON.FreeCamera);
  6880. BABYLON.TouchCamera = TouchCamera;
  6881. })(BABYLON || (BABYLON = {}));
  6882. //# sourceMappingURL=babylon.touchCamera.js.map
  6883. var BABYLON;
  6884. (function (BABYLON) {
  6885. // We're mainly based on the logic defined into the FreeCamera code
  6886. var DeviceOrientationCamera = (function (_super) {
  6887. __extends(DeviceOrientationCamera, _super);
  6888. function DeviceOrientationCamera(name, position, scene) {
  6889. var _this = this;
  6890. _super.call(this, name, position, scene);
  6891. this._offsetX = null;
  6892. this._offsetY = null;
  6893. this._orientationGamma = 0;
  6894. this._orientationBeta = 0;
  6895. this._initialOrientationGamma = 0;
  6896. this._initialOrientationBeta = 0;
  6897. this.angularSensibility = 10000.0;
  6898. this.moveSensibility = 50.0;
  6899. window.addEventListener("resize", function () {
  6900. _this._initialOrientationGamma = null;
  6901. }, false);
  6902. }
  6903. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6904. var _this = this;
  6905. if (this._attachedCanvas) {
  6906. return;
  6907. }
  6908. this._attachedCanvas = canvas;
  6909. if (!this._orientationChanged) {
  6910. this._orientationChanged = function (evt) {
  6911. if (!_this._initialOrientationGamma) {
  6912. _this._initialOrientationGamma = evt.gamma;
  6913. _this._initialOrientationBeta = evt.beta;
  6914. }
  6915. _this._orientationGamma = evt.gamma;
  6916. _this._orientationBeta = evt.beta;
  6917. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6918. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6919. };
  6920. }
  6921. window.addEventListener("deviceorientation", this._orientationChanged);
  6922. };
  6923. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6924. if (this._attachedCanvas != canvas) {
  6925. return;
  6926. }
  6927. window.removeEventListener("deviceorientation", this._orientationChanged);
  6928. this._attachedCanvas = null;
  6929. this._orientationGamma = 0;
  6930. this._orientationBeta = 0;
  6931. this._initialOrientationGamma = 0;
  6932. this._initialOrientationBeta = 0;
  6933. };
  6934. DeviceOrientationCamera.prototype._checkInputs = function () {
  6935. if (!this._offsetX) {
  6936. return;
  6937. }
  6938. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6939. var speed = this._computeLocalCameraSpeed();
  6940. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6941. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6942. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6943. };
  6944. return DeviceOrientationCamera;
  6945. })(BABYLON.FreeCamera);
  6946. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6947. })(BABYLON || (BABYLON = {}));
  6948. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  6949. var BABYLON;
  6950. (function (BABYLON) {
  6951. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6952. var ArcRotateCamera = (function (_super) {
  6953. __extends(ArcRotateCamera, _super);
  6954. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6955. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6956. this.alpha = alpha;
  6957. this.beta = beta;
  6958. this.radius = radius;
  6959. this.target = target;
  6960. this.inertialAlphaOffset = 0;
  6961. this.inertialBetaOffset = 0;
  6962. this.inertialRadiusOffset = 0;
  6963. this.lowerAlphaLimit = null;
  6964. this.upperAlphaLimit = null;
  6965. this.lowerBetaLimit = 0.01;
  6966. this.upperBetaLimit = Math.PI;
  6967. this.lowerRadiusLimit = null;
  6968. this.upperRadiusLimit = null;
  6969. this.angularSensibility = 1000.0;
  6970. this.wheelPrecision = 3.0;
  6971. this.keysUp = [38];
  6972. this.keysDown = [40];
  6973. this.keysLeft = [37];
  6974. this.keysRight = [39];
  6975. this.zoomOnFactor = 1;
  6976. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6977. this._keys = [];
  6978. this._viewMatrix = new BABYLON.Matrix();
  6979. this.checkCollisions = false;
  6980. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6981. this._collider = new BABYLON.Collider();
  6982. this._previousPosition = BABYLON.Vector3.Zero();
  6983. this._collisionVelocity = BABYLON.Vector3.Zero();
  6984. this._newPosition = BABYLON.Vector3.Zero();
  6985. // Pinch
  6986. // value for pinch step scaling
  6987. // set to 20 by default
  6988. this.pinchPrecision = 20;
  6989. this.getViewMatrix();
  6990. }
  6991. ArcRotateCamera.prototype._getTargetPosition = function () {
  6992. return this.target.position || this.target;
  6993. };
  6994. // Cache
  6995. ArcRotateCamera.prototype._initCache = function () {
  6996. _super.prototype._initCache.call(this);
  6997. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6998. this._cache.alpha = undefined;
  6999. this._cache.beta = undefined;
  7000. this._cache.radius = undefined;
  7001. this._cache.targetScreenOffset = undefined;
  7002. };
  7003. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7004. if (!ignoreParentClass) {
  7005. _super.prototype._updateCache.call(this);
  7006. }
  7007. this._cache.target.copyFrom(this._getTargetPosition());
  7008. this._cache.alpha = this.alpha;
  7009. this._cache.beta = this.beta;
  7010. this._cache.radius = this.radius;
  7011. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7012. };
  7013. // Synchronized
  7014. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7015. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7016. return false;
  7017. 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);
  7018. };
  7019. // Methods
  7020. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7021. var _this = this;
  7022. var previousPosition;
  7023. var pointerId;
  7024. // to know if pinch started
  7025. var pinchStarted = false;
  7026. // two pinch point on X
  7027. // that will use for find if user action is pinch open or pinch close
  7028. var pinchPointX1, pinchPointX2;
  7029. if (this._attachedElement) {
  7030. return;
  7031. }
  7032. this._attachedElement = element;
  7033. var engine = this.getEngine();
  7034. if (this._onPointerDown === undefined) {
  7035. this._onPointerDown = function (evt) {
  7036. if (pointerId) {
  7037. return;
  7038. }
  7039. pointerId = evt.pointerId;
  7040. previousPosition = {
  7041. x: evt.clientX,
  7042. y: evt.clientY
  7043. };
  7044. if (!noPreventDefault) {
  7045. evt.preventDefault();
  7046. }
  7047. };
  7048. this._onPointerUp = function (evt) {
  7049. previousPosition = null;
  7050. pointerId = null;
  7051. if (!noPreventDefault) {
  7052. evt.preventDefault();
  7053. }
  7054. };
  7055. this._onPointerMove = function (evt) {
  7056. if (!previousPosition) {
  7057. return;
  7058. }
  7059. if (pointerId !== evt.pointerId) {
  7060. return;
  7061. }
  7062. // return pinch is started
  7063. if (pinchStarted) {
  7064. return;
  7065. }
  7066. var offsetX = evt.clientX - previousPosition.x;
  7067. var offsetY = evt.clientY - previousPosition.y;
  7068. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7069. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7070. previousPosition = {
  7071. x: evt.clientX,
  7072. y: evt.clientY
  7073. };
  7074. if (!noPreventDefault) {
  7075. evt.preventDefault();
  7076. }
  7077. };
  7078. this._onMouseMove = function (evt) {
  7079. if (!engine.isPointerLock) {
  7080. return;
  7081. }
  7082. // return pinch is started
  7083. if (pinchStarted) {
  7084. return;
  7085. }
  7086. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7087. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7088. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7089. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7090. if (!noPreventDefault) {
  7091. evt.preventDefault();
  7092. }
  7093. };
  7094. this._wheel = function (event) {
  7095. var delta = 0;
  7096. if (event.wheelDelta) {
  7097. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7098. }
  7099. else if (event.detail) {
  7100. delta = -event.detail / _this.wheelPrecision;
  7101. }
  7102. if (delta)
  7103. _this.inertialRadiusOffset += delta;
  7104. if (event.preventDefault) {
  7105. if (!noPreventDefault) {
  7106. event.preventDefault();
  7107. }
  7108. }
  7109. };
  7110. this._onKeyDown = function (evt) {
  7111. 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) {
  7112. var index = _this._keys.indexOf(evt.keyCode);
  7113. if (index === -1) {
  7114. _this._keys.push(evt.keyCode);
  7115. }
  7116. if (evt.preventDefault) {
  7117. if (!noPreventDefault) {
  7118. evt.preventDefault();
  7119. }
  7120. }
  7121. }
  7122. };
  7123. this._onKeyUp = function (evt) {
  7124. 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) {
  7125. var index = _this._keys.indexOf(evt.keyCode);
  7126. if (index >= 0) {
  7127. _this._keys.splice(index, 1);
  7128. }
  7129. if (evt.preventDefault) {
  7130. if (!noPreventDefault) {
  7131. evt.preventDefault();
  7132. }
  7133. }
  7134. }
  7135. };
  7136. this._onLostFocus = function () {
  7137. _this._keys = [];
  7138. pointerId = null;
  7139. };
  7140. this._onGestureStart = function (e) {
  7141. if (window.MSGesture === undefined) {
  7142. return;
  7143. }
  7144. if (!_this._MSGestureHandler) {
  7145. _this._MSGestureHandler = new MSGesture();
  7146. _this._MSGestureHandler.target = element;
  7147. }
  7148. _this._MSGestureHandler.addPointer(e.pointerId);
  7149. };
  7150. this._onGesture = function (e) {
  7151. _this.radius *= e.scale;
  7152. if (e.preventDefault) {
  7153. if (!noPreventDefault) {
  7154. e.stopPropagation();
  7155. e.preventDefault();
  7156. }
  7157. }
  7158. };
  7159. this._reset = function () {
  7160. _this._keys = [];
  7161. _this.inertialAlphaOffset = 0;
  7162. _this.inertialBetaOffset = 0;
  7163. _this.inertialRadiusOffset = 0;
  7164. previousPosition = null;
  7165. pointerId = null;
  7166. };
  7167. this._touchStart = function (event) {
  7168. if (event.touches.length === 2) {
  7169. //-- start pinch if two fingers on the screen
  7170. pinchStarted = true;
  7171. _this._pinchStart(event);
  7172. }
  7173. };
  7174. this._touchMove = function (event) {
  7175. if (pinchStarted) {
  7176. //-- make scaling
  7177. _this._pinchMove(event);
  7178. }
  7179. };
  7180. this._touchEnd = function (event) {
  7181. if (pinchStarted) {
  7182. //-- end of pinch
  7183. _this._pinchEnd(event);
  7184. }
  7185. };
  7186. this._pinchStart = function (event) {
  7187. // save origin touch point
  7188. pinchPointX1 = event.touches[0].clientX;
  7189. pinchPointX2 = event.touches[1].clientX;
  7190. // block the camera
  7191. // if not it rotate around target during pinch
  7192. pinchStarted = true;
  7193. };
  7194. this._pinchMove = function (event) {
  7195. // variable for new camera's radius
  7196. var delta = 0;
  7197. // variables to know if pinch open or pinch close
  7198. var direction = 1;
  7199. var distanceXOrigine, distanceXNow;
  7200. if (event.touches.length !== 2)
  7201. return;
  7202. // calculate absolute distances of the two fingers
  7203. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7204. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7205. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7206. if (distanceXNow < distanceXOrigine) {
  7207. direction = -1;
  7208. }
  7209. // calculate new radius
  7210. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7211. // set new radius
  7212. _this.inertialRadiusOffset -= delta;
  7213. // save origin touch point
  7214. pinchPointX1 = event.touches[0].clientX;
  7215. pinchPointX2 = event.touches[1].clientX;
  7216. };
  7217. this._pinchEnd = function (event) {
  7218. // cancel pinch and deblock camera rotation
  7219. pinchStarted = false;
  7220. };
  7221. }
  7222. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7223. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7224. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7225. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7226. element.addEventListener("mousemove", this._onMouseMove, false);
  7227. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7228. element.addEventListener("MSGestureChange", this._onGesture, false);
  7229. element.addEventListener('mousewheel', this._wheel, false);
  7230. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7231. // pinch
  7232. element.addEventListener('touchstart', this._touchStart, false);
  7233. element.addEventListener('touchmove', this._touchMove, false);
  7234. element.addEventListener('touchend', this._touchEnd, false);
  7235. BABYLON.Tools.RegisterTopRootEvents([
  7236. { name: "keydown", handler: this._onKeyDown },
  7237. { name: "keyup", handler: this._onKeyUp },
  7238. { name: "blur", handler: this._onLostFocus }
  7239. ]);
  7240. };
  7241. ArcRotateCamera.prototype.detachControl = function (element) {
  7242. if (this._attachedElement != element) {
  7243. return;
  7244. }
  7245. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7246. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7247. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7248. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7249. element.removeEventListener("mousemove", this._onMouseMove);
  7250. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7251. element.removeEventListener("MSGestureChange", this._onGesture);
  7252. element.removeEventListener('mousewheel', this._wheel);
  7253. element.removeEventListener('DOMMouseScroll', this._wheel);
  7254. // pinch
  7255. element.removeEventListener('touchstart', this._touchStart);
  7256. element.removeEventListener('touchmove', this._touchMove);
  7257. element.removeEventListener('touchend', this._touchEnd);
  7258. BABYLON.Tools.UnregisterTopRootEvents([
  7259. { name: "keydown", handler: this._onKeyDown },
  7260. { name: "keyup", handler: this._onKeyUp },
  7261. { name: "blur", handler: this._onLostFocus }
  7262. ]);
  7263. this._MSGestureHandler = null;
  7264. this._attachedElement = null;
  7265. if (this._reset) {
  7266. this._reset();
  7267. }
  7268. };
  7269. ArcRotateCamera.prototype._update = function () {
  7270. for (var index = 0; index < this._keys.length; index++) {
  7271. var keyCode = this._keys[index];
  7272. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7273. this.inertialAlphaOffset -= 0.01;
  7274. }
  7275. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7276. this.inertialBetaOffset -= 0.01;
  7277. }
  7278. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7279. this.inertialAlphaOffset += 0.01;
  7280. }
  7281. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7282. this.inertialBetaOffset += 0.01;
  7283. }
  7284. }
  7285. // Inertia
  7286. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7287. this.alpha += this.inertialAlphaOffset;
  7288. this.beta += this.inertialBetaOffset;
  7289. this.radius -= this.inertialRadiusOffset;
  7290. this.inertialAlphaOffset *= this.inertia;
  7291. this.inertialBetaOffset *= this.inertia;
  7292. this.inertialRadiusOffset *= this.inertia;
  7293. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7294. this.inertialAlphaOffset = 0;
  7295. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7296. this.inertialBetaOffset = 0;
  7297. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7298. this.inertialRadiusOffset = 0;
  7299. }
  7300. // Limits
  7301. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7302. this.alpha = this.lowerAlphaLimit;
  7303. }
  7304. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7305. this.alpha = this.upperAlphaLimit;
  7306. }
  7307. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7308. this.beta = this.lowerBetaLimit;
  7309. }
  7310. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7311. this.beta = this.upperBetaLimit;
  7312. }
  7313. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7314. this.radius = this.lowerRadiusLimit;
  7315. }
  7316. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7317. this.radius = this.upperRadiusLimit;
  7318. }
  7319. };
  7320. ArcRotateCamera.prototype.setPosition = function (position) {
  7321. var radiusv3 = position.subtract(this._getTargetPosition());
  7322. this.radius = radiusv3.length();
  7323. // Alpha
  7324. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7325. if (radiusv3.z < 0) {
  7326. this.alpha = 2 * Math.PI - this.alpha;
  7327. }
  7328. // Beta
  7329. this.beta = Math.acos(radiusv3.y / this.radius);
  7330. };
  7331. ArcRotateCamera.prototype._getViewMatrix = function () {
  7332. // Compute
  7333. var cosa = Math.cos(this.alpha);
  7334. var sina = Math.sin(this.alpha);
  7335. var cosb = Math.cos(this.beta);
  7336. var sinb = Math.sin(this.beta);
  7337. var target = this._getTargetPosition();
  7338. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7339. if (this.checkCollisions) {
  7340. this._collider.radius = this.collisionRadius;
  7341. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7342. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7343. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7344. this.position.copyFrom(this._previousPosition);
  7345. this.alpha = this._previousAlpha;
  7346. this.beta = this._previousBeta;
  7347. this.radius = this._previousRadius;
  7348. if (this.onCollide) {
  7349. this.onCollide(this._collider.collidedMesh);
  7350. }
  7351. }
  7352. }
  7353. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7354. this._previousAlpha = this.alpha;
  7355. this._previousBeta = this.beta;
  7356. this._previousRadius = this.radius;
  7357. this._previousPosition.copyFrom(this.position);
  7358. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7359. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7360. return this._viewMatrix;
  7361. };
  7362. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7363. meshes = meshes || this.getScene().meshes;
  7364. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7365. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7366. this.radius = distance * this.zoomOnFactor;
  7367. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7368. };
  7369. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7370. var meshesOrMinMaxVector;
  7371. var distance;
  7372. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7373. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7374. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7375. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7376. }
  7377. else {
  7378. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7379. distance = meshesOrMinMaxVectorAndDistance.distance;
  7380. }
  7381. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7382. this.maxZ = distance * 2;
  7383. };
  7384. return ArcRotateCamera;
  7385. })(BABYLON.Camera);
  7386. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7387. })(BABYLON || (BABYLON = {}));
  7388. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7389. (function (BABYLON) {
  7390. /**
  7391. * Represents a scene to be rendered by the engine.
  7392. * @see http://doc.babylonjs.com/page.php?p=21911
  7393. */
  7394. var Scene = (function () {
  7395. /**
  7396. * @constructor
  7397. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7398. */
  7399. function Scene(engine) {
  7400. // Members
  7401. this.autoClear = true;
  7402. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7403. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7404. this.forceWireframe = false;
  7405. this.forcePointsCloud = false;
  7406. this.forceShowBoundingBoxes = false;
  7407. this.animationsEnabled = true;
  7408. 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
  7409. // Fog
  7410. /**
  7411. * is fog enabled on this scene.
  7412. * @type {boolean}
  7413. */
  7414. this.fogEnabled = true;
  7415. this.fogMode = Scene.FOGMODE_NONE;
  7416. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7417. this.fogDensity = 0.1;
  7418. this.fogStart = 0;
  7419. this.fogEnd = 1000.0;
  7420. // Lights
  7421. /**
  7422. * is shadow enabled on this scene.
  7423. * @type {boolean}
  7424. */
  7425. this.shadowsEnabled = true;
  7426. /**
  7427. * is light enabled on this scene.
  7428. * @type {boolean}
  7429. */
  7430. this.lightsEnabled = true;
  7431. /**
  7432. * All of the lights added to this scene.
  7433. * @see BABYLON.Light
  7434. * @type {BABYLON.Light[]}
  7435. */
  7436. this.lights = new Array();
  7437. // Cameras
  7438. /**
  7439. * All of the cameras added to this scene.
  7440. * @see BABYLON.Camera
  7441. * @type {BABYLON.Camera[]}
  7442. */
  7443. this.cameras = new Array();
  7444. this.activeCameras = new Array();
  7445. // Meshes
  7446. /**
  7447. * All of the (abstract) meshes added to this scene.
  7448. * @see BABYLON.AbstractMesh
  7449. * @type {BABYLON.AbstractMesh[]}
  7450. */
  7451. this.meshes = new Array();
  7452. // Geometries
  7453. this._geometries = new Array();
  7454. this.materials = new Array();
  7455. this.multiMaterials = new Array();
  7456. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7457. // Textures
  7458. this.texturesEnabled = true;
  7459. this.textures = new Array();
  7460. // Particles
  7461. this.particlesEnabled = true;
  7462. this.particleSystems = new Array();
  7463. // Sprites
  7464. this.spriteManagers = new Array();
  7465. // Layers
  7466. this.layers = new Array();
  7467. // Skeletons
  7468. this.skeletonsEnabled = true;
  7469. this.skeletons = new Array();
  7470. // Lens flares
  7471. this.lensFlaresEnabled = true;
  7472. this.lensFlareSystems = new Array();
  7473. // Collisions
  7474. this.collisionsEnabled = true;
  7475. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7476. // Postprocesses
  7477. this.postProcessesEnabled = true;
  7478. // Customs render targets
  7479. this.renderTargetsEnabled = true;
  7480. this.customRenderTargets = new Array();
  7481. // Imported meshes
  7482. this.importedMeshesFiles = new Array();
  7483. this._actionManagers = new Array();
  7484. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7485. // Procedural textures
  7486. this.proceduralTexturesEnabled = true;
  7487. this._proceduralTextures = new Array();
  7488. this.soundTracks = new Array();
  7489. this._totalVertices = 0;
  7490. this._activeVertices = 0;
  7491. this._activeParticles = 0;
  7492. this._lastFrameDuration = 0;
  7493. this._evaluateActiveMeshesDuration = 0;
  7494. this._renderTargetsDuration = 0;
  7495. this._particlesDuration = 0;
  7496. this._renderDuration = 0;
  7497. this._spritesDuration = 0;
  7498. this._animationRatio = 0;
  7499. this._renderId = 0;
  7500. this._executeWhenReadyTimeoutId = -1;
  7501. this._toBeDisposed = new BABYLON.SmartArray(256);
  7502. this._onReadyCallbacks = new Array();
  7503. this._pendingData = []; //ANY
  7504. this._onBeforeRenderCallbacks = new Array();
  7505. this._onAfterRenderCallbacks = new Array();
  7506. this._activeMeshes = new BABYLON.SmartArray(256);
  7507. this._processedMaterials = new BABYLON.SmartArray(256);
  7508. this._renderTargets = new BABYLON.SmartArray(256);
  7509. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7510. this._activeSkeletons = new BABYLON.SmartArray(32);
  7511. this._activeBones = 0;
  7512. this._activeAnimatables = new Array();
  7513. this._transformMatrix = BABYLON.Matrix.Zero();
  7514. this._scaledPosition = BABYLON.Vector3.Zero();
  7515. this._scaledVelocity = BABYLON.Vector3.Zero();
  7516. this._engine = engine;
  7517. engine.scenes.push(this);
  7518. this._renderingManager = new BABYLON.RenderingManager(this);
  7519. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7520. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7521. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7522. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7523. this.attachControl();
  7524. this._debugLayer = new BABYLON.DebugLayer(this);
  7525. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7526. }
  7527. Object.defineProperty(Scene.prototype, "debugLayer", {
  7528. // Properties
  7529. get: function () {
  7530. return this._debugLayer;
  7531. },
  7532. enumerable: true,
  7533. configurable: true
  7534. });
  7535. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7536. /**
  7537. * The mesh that is currently under the pointer.
  7538. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  7539. */
  7540. get: function () {
  7541. return this._meshUnderPointer;
  7542. },
  7543. enumerable: true,
  7544. configurable: true
  7545. });
  7546. Object.defineProperty(Scene.prototype, "pointerX", {
  7547. /**
  7548. * Current on-screen X position of the pointer
  7549. * @return {number} X position of the pointer
  7550. */
  7551. get: function () {
  7552. return this._pointerX;
  7553. },
  7554. enumerable: true,
  7555. configurable: true
  7556. });
  7557. Object.defineProperty(Scene.prototype, "pointerY", {
  7558. /**
  7559. * Current on-screen Y position of the pointer
  7560. * @return {number} Y position of the pointer
  7561. */
  7562. get: function () {
  7563. return this._pointerY;
  7564. },
  7565. enumerable: true,
  7566. configurable: true
  7567. });
  7568. Scene.prototype.getCachedMaterial = function () {
  7569. return this._cachedMaterial;
  7570. };
  7571. Scene.prototype.getBoundingBoxRenderer = function () {
  7572. return this._boundingBoxRenderer;
  7573. };
  7574. Scene.prototype.getOutlineRenderer = function () {
  7575. return this._outlineRenderer;
  7576. };
  7577. Scene.prototype.getEngine = function () {
  7578. return this._engine;
  7579. };
  7580. Scene.prototype.getTotalVertices = function () {
  7581. return this._totalVertices;
  7582. };
  7583. Scene.prototype.getActiveVertices = function () {
  7584. return this._activeVertices;
  7585. };
  7586. Scene.prototype.getActiveParticles = function () {
  7587. return this._activeParticles;
  7588. };
  7589. Scene.prototype.getActiveBones = function () {
  7590. return this._activeBones;
  7591. };
  7592. // Stats
  7593. Scene.prototype.getLastFrameDuration = function () {
  7594. return this._lastFrameDuration;
  7595. };
  7596. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7597. return this._evaluateActiveMeshesDuration;
  7598. };
  7599. Scene.prototype.getActiveMeshes = function () {
  7600. return this._activeMeshes;
  7601. };
  7602. Scene.prototype.getRenderTargetsDuration = function () {
  7603. return this._renderTargetsDuration;
  7604. };
  7605. Scene.prototype.getRenderDuration = function () {
  7606. return this._renderDuration;
  7607. };
  7608. Scene.prototype.getParticlesDuration = function () {
  7609. return this._particlesDuration;
  7610. };
  7611. Scene.prototype.getSpritesDuration = function () {
  7612. return this._spritesDuration;
  7613. };
  7614. Scene.prototype.getAnimationRatio = function () {
  7615. return this._animationRatio;
  7616. };
  7617. Scene.prototype.getRenderId = function () {
  7618. return this._renderId;
  7619. };
  7620. Scene.prototype._updatePointerPosition = function (evt) {
  7621. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7622. this._pointerX = evt.clientX - canvasRect.left;
  7623. this._pointerY = evt.clientY - canvasRect.top;
  7624. if (this.cameraToUseForPointers) {
  7625. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7626. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7627. }
  7628. };
  7629. // Pointers handling
  7630. Scene.prototype.attachControl = function () {
  7631. var _this = this;
  7632. this._onPointerMove = function (evt) {
  7633. var canvas = _this._engine.getRenderingCanvas();
  7634. _this._updatePointerPosition(evt);
  7635. 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);
  7636. if (pickResult.hit) {
  7637. _this._meshUnderPointer = pickResult.pickedMesh;
  7638. _this.setPointerOverMesh(pickResult.pickedMesh);
  7639. canvas.style.cursor = "pointer";
  7640. }
  7641. else {
  7642. _this.setPointerOverMesh(null);
  7643. canvas.style.cursor = "";
  7644. _this._meshUnderPointer = null;
  7645. }
  7646. };
  7647. this._onPointerDown = function (evt) {
  7648. var predicate = null;
  7649. if (!_this.onPointerDown) {
  7650. predicate = function (mesh) {
  7651. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7652. };
  7653. }
  7654. _this._updatePointerPosition(evt);
  7655. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7656. if (pickResult.hit) {
  7657. if (pickResult.pickedMesh.actionManager) {
  7658. switch (evt.button) {
  7659. case 0:
  7660. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7661. break;
  7662. case 1:
  7663. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7664. break;
  7665. case 2:
  7666. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7667. break;
  7668. }
  7669. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7670. }
  7671. }
  7672. if (_this.onPointerDown) {
  7673. _this.onPointerDown(evt, pickResult);
  7674. }
  7675. };
  7676. this._onKeyDown = function (evt) {
  7677. if (_this.actionManager) {
  7678. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7679. }
  7680. };
  7681. this._onKeyUp = function (evt) {
  7682. if (_this.actionManager) {
  7683. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7684. }
  7685. };
  7686. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7687. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7688. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7689. window.addEventListener("keydown", this._onKeyDown, false);
  7690. window.addEventListener("keyup", this._onKeyUp, false);
  7691. };
  7692. Scene.prototype.detachControl = function () {
  7693. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7694. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7695. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7696. window.removeEventListener("keydown", this._onKeyDown);
  7697. window.removeEventListener("keyup", this._onKeyUp);
  7698. };
  7699. // Ready
  7700. Scene.prototype.isReady = function () {
  7701. if (this._pendingData.length > 0) {
  7702. return false;
  7703. }
  7704. for (var index = 0; index < this._geometries.length; index++) {
  7705. var geometry = this._geometries[index];
  7706. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7707. return false;
  7708. }
  7709. }
  7710. for (index = 0; index < this.meshes.length; index++) {
  7711. var mesh = this.meshes[index];
  7712. if (!mesh.isReady()) {
  7713. return false;
  7714. }
  7715. var mat = mesh.material;
  7716. if (mat) {
  7717. if (!mat.isReady(mesh)) {
  7718. return false;
  7719. }
  7720. }
  7721. }
  7722. return true;
  7723. };
  7724. Scene.prototype.resetCachedMaterial = function () {
  7725. this._cachedMaterial = null;
  7726. };
  7727. Scene.prototype.registerBeforeRender = function (func) {
  7728. this._onBeforeRenderCallbacks.push(func);
  7729. };
  7730. Scene.prototype.unregisterBeforeRender = function (func) {
  7731. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7732. if (index > -1) {
  7733. this._onBeforeRenderCallbacks.splice(index, 1);
  7734. }
  7735. };
  7736. Scene.prototype.registerAfterRender = function (func) {
  7737. this._onAfterRenderCallbacks.push(func);
  7738. };
  7739. Scene.prototype.unregisterAfterRender = function (func) {
  7740. var index = this._onAfterRenderCallbacks.indexOf(func);
  7741. if (index > -1) {
  7742. this._onAfterRenderCallbacks.splice(index, 1);
  7743. }
  7744. };
  7745. Scene.prototype._addPendingData = function (data) {
  7746. this._pendingData.push(data);
  7747. };
  7748. Scene.prototype._removePendingData = function (data) {
  7749. var index = this._pendingData.indexOf(data);
  7750. if (index !== -1) {
  7751. this._pendingData.splice(index, 1);
  7752. }
  7753. };
  7754. Scene.prototype.getWaitingItemsCount = function () {
  7755. return this._pendingData.length;
  7756. };
  7757. /**
  7758. * Registers a function to be executed when the scene is ready.
  7759. * @param {Function} func - the function to be executed.
  7760. */
  7761. Scene.prototype.executeWhenReady = function (func) {
  7762. var _this = this;
  7763. this._onReadyCallbacks.push(func);
  7764. if (this._executeWhenReadyTimeoutId !== -1) {
  7765. return;
  7766. }
  7767. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7768. _this._checkIsReady();
  7769. }, 150);
  7770. };
  7771. Scene.prototype._checkIsReady = function () {
  7772. var _this = this;
  7773. if (this.isReady()) {
  7774. this._onReadyCallbacks.forEach(function (func) {
  7775. func();
  7776. });
  7777. this._onReadyCallbacks = [];
  7778. this._executeWhenReadyTimeoutId = -1;
  7779. return;
  7780. }
  7781. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7782. _this._checkIsReady();
  7783. }, 150);
  7784. };
  7785. // Animations
  7786. /**
  7787. * Will start the animation sequence of a given target
  7788. * @param target - the target
  7789. * @param {number} from - from which frame should animation start
  7790. * @param {number} to - till which frame should animation run.
  7791. * @param {boolean} [loop] - should the animation loop
  7792. * @param {number} [speedRatio] - the speed in which to run the animation
  7793. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  7794. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  7795. * @return {BABYLON.Animatable} the animatable object created for this animation
  7796. * @see BABYLON.Animatable
  7797. * @see http://doc.babylonjs.com/page.php?p=22081
  7798. */
  7799. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7800. if (speedRatio === undefined) {
  7801. speedRatio = 1.0;
  7802. }
  7803. this.stopAnimation(target);
  7804. if (!animatable) {
  7805. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7806. }
  7807. // Local animations
  7808. if (target.animations) {
  7809. animatable.appendAnimations(target, target.animations);
  7810. }
  7811. // Children animations
  7812. if (target.getAnimatables) {
  7813. var animatables = target.getAnimatables();
  7814. for (var index = 0; index < animatables.length; index++) {
  7815. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7816. }
  7817. }
  7818. return animatable;
  7819. };
  7820. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7821. if (speedRatio === undefined) {
  7822. speedRatio = 1.0;
  7823. }
  7824. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7825. return animatable;
  7826. };
  7827. Scene.prototype.getAnimatableByTarget = function (target) {
  7828. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7829. if (this._activeAnimatables[index].target === target) {
  7830. return this._activeAnimatables[index];
  7831. }
  7832. }
  7833. return null;
  7834. };
  7835. /**
  7836. * Will stop the animation of the given target
  7837. * @param target - the target
  7838. * @see beginAnimation
  7839. */
  7840. Scene.prototype.stopAnimation = function (target) {
  7841. var animatable = this.getAnimatableByTarget(target);
  7842. if (animatable) {
  7843. animatable.stop();
  7844. }
  7845. };
  7846. Scene.prototype._animate = function () {
  7847. if (!this.animationsEnabled) {
  7848. return;
  7849. }
  7850. if (!this._animationStartDate) {
  7851. this._animationStartDate = BABYLON.Tools.Now;
  7852. }
  7853. // Getting time
  7854. var now = BABYLON.Tools.Now;
  7855. var delay = now - this._animationStartDate;
  7856. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7857. if (!this._activeAnimatables[index]._animate(delay)) {
  7858. this._activeAnimatables.splice(index, 1);
  7859. index--;
  7860. }
  7861. }
  7862. };
  7863. // Matrix
  7864. Scene.prototype.getViewMatrix = function () {
  7865. return this._viewMatrix;
  7866. };
  7867. Scene.prototype.getProjectionMatrix = function () {
  7868. return this._projectionMatrix;
  7869. };
  7870. Scene.prototype.getTransformMatrix = function () {
  7871. return this._transformMatrix;
  7872. };
  7873. Scene.prototype.setTransformMatrix = function (view, projection) {
  7874. this._viewMatrix = view;
  7875. this._projectionMatrix = projection;
  7876. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  7877. };
  7878. // Methods
  7879. /**
  7880. * sets the active camera of the scene using its ID
  7881. * @param {string} id - the camera's ID
  7882. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  7883. * @see activeCamera
  7884. */
  7885. Scene.prototype.setActiveCameraByID = function (id) {
  7886. var camera = this.getCameraByID(id);
  7887. if (camera) {
  7888. this.activeCamera = camera;
  7889. return camera;
  7890. }
  7891. return null;
  7892. };
  7893. /**
  7894. * sets the active camera of the scene using its name
  7895. * @param {string} name - the camera's name
  7896. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  7897. * @see activeCamera
  7898. */
  7899. Scene.prototype.setActiveCameraByName = function (name) {
  7900. var camera = this.getCameraByName(name);
  7901. if (camera) {
  7902. this.activeCamera = camera;
  7903. return camera;
  7904. }
  7905. return null;
  7906. };
  7907. /**
  7908. * get a material using its id
  7909. * @param {string} the material's ID
  7910. * @return {BABYLON.Material|null} the material or null if none found.
  7911. */
  7912. Scene.prototype.getMaterialByID = function (id) {
  7913. for (var index = 0; index < this.materials.length; index++) {
  7914. if (this.materials[index].id === id) {
  7915. return this.materials[index];
  7916. }
  7917. }
  7918. return null;
  7919. };
  7920. /**
  7921. * get a material using its name
  7922. * @param {string} the material's name
  7923. * @return {BABYLON.Material|null} the material or null if none found.
  7924. */
  7925. Scene.prototype.getMaterialByName = function (name) {
  7926. for (var index = 0; index < this.materials.length; index++) {
  7927. if (this.materials[index].name === name) {
  7928. return this.materials[index];
  7929. }
  7930. }
  7931. return null;
  7932. };
  7933. Scene.prototype.getCameraByID = function (id) {
  7934. for (var index = 0; index < this.cameras.length; index++) {
  7935. if (this.cameras[index].id === id) {
  7936. return this.cameras[index];
  7937. }
  7938. }
  7939. return null;
  7940. };
  7941. /**
  7942. * get a camera using its name
  7943. * @param {string} the camera's name
  7944. * @return {BABYLON.Camera|null} the camera or null if none found.
  7945. */
  7946. Scene.prototype.getCameraByName = function (name) {
  7947. for (var index = 0; index < this.cameras.length; index++) {
  7948. if (this.cameras[index].name === name) {
  7949. return this.cameras[index];
  7950. }
  7951. }
  7952. return null;
  7953. };
  7954. /**
  7955. * get a light node using its name
  7956. * @param {string} the light's name
  7957. * @return {BABYLON.Light|null} the light or null if none found.
  7958. */
  7959. Scene.prototype.getLightByName = function (name) {
  7960. for (var index = 0; index < this.lights.length; index++) {
  7961. if (this.lights[index].name === name) {
  7962. return this.lights[index];
  7963. }
  7964. }
  7965. return null;
  7966. };
  7967. /**
  7968. * get a light node using its ID
  7969. * @param {string} the light's id
  7970. * @return {BABYLON.Light|null} the light or null if none found.
  7971. */
  7972. Scene.prototype.getLightByID = function (id) {
  7973. for (var index = 0; index < this.lights.length; index++) {
  7974. if (this.lights[index].id === id) {
  7975. return this.lights[index];
  7976. }
  7977. }
  7978. return null;
  7979. };
  7980. /**
  7981. * get a geometry using its ID
  7982. * @param {string} the geometry's id
  7983. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  7984. */
  7985. Scene.prototype.getGeometryByID = function (id) {
  7986. for (var index = 0; index < this._geometries.length; index++) {
  7987. if (this._geometries[index].id === id) {
  7988. return this._geometries[index];
  7989. }
  7990. }
  7991. return null;
  7992. };
  7993. /**
  7994. * add a new geometry to this scene.
  7995. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  7996. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  7997. * @return {boolean} was the geometry added or not
  7998. */
  7999. Scene.prototype.pushGeometry = function (geometry, force) {
  8000. if (!force && this.getGeometryByID(geometry.id)) {
  8001. return false;
  8002. }
  8003. this._geometries.push(geometry);
  8004. return true;
  8005. };
  8006. Scene.prototype.getGeometries = function () {
  8007. return this._geometries;
  8008. };
  8009. /**
  8010. * Get a the first added mesh found of a given ID
  8011. * @param {string} id - the id to search for
  8012. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8013. */
  8014. Scene.prototype.getMeshByID = function (id) {
  8015. for (var index = 0; index < this.meshes.length; index++) {
  8016. if (this.meshes[index].id === id) {
  8017. return this.meshes[index];
  8018. }
  8019. }
  8020. return null;
  8021. };
  8022. /**
  8023. * Get a the last added mesh found of a given ID
  8024. * @param {string} id - the id to search for
  8025. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8026. */
  8027. Scene.prototype.getLastMeshByID = function (id) {
  8028. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8029. if (this.meshes[index].id === id) {
  8030. return this.meshes[index];
  8031. }
  8032. }
  8033. return null;
  8034. };
  8035. /**
  8036. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8037. * @param {string} id - the id to search for
  8038. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8039. */
  8040. Scene.prototype.getLastEntryByID = function (id) {
  8041. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8042. if (this.meshes[index].id === id) {
  8043. return this.meshes[index];
  8044. }
  8045. }
  8046. for (index = this.cameras.length - 1; index >= 0; index--) {
  8047. if (this.cameras[index].id === id) {
  8048. return this.cameras[index];
  8049. }
  8050. }
  8051. for (index = this.lights.length - 1; index >= 0; index--) {
  8052. if (this.lights[index].id === id) {
  8053. return this.lights[index];
  8054. }
  8055. }
  8056. return null;
  8057. };
  8058. Scene.prototype.getNodeByName = function (name) {
  8059. var mesh = this.getMeshByName(name);
  8060. if (mesh) {
  8061. return mesh;
  8062. }
  8063. var light = this.getLightByName(name);
  8064. if (light) {
  8065. return light;
  8066. }
  8067. return this.getCameraByName(name);
  8068. };
  8069. Scene.prototype.getMeshByName = function (name) {
  8070. for (var index = 0; index < this.meshes.length; index++) {
  8071. if (this.meshes[index].name === name) {
  8072. return this.meshes[index];
  8073. }
  8074. }
  8075. return null;
  8076. };
  8077. Scene.prototype.getSoundByName = function (name) {
  8078. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8079. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8080. return this.mainSoundTrack.soundCollection[index];
  8081. }
  8082. }
  8083. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8084. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8085. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8086. return this.soundTracks[sdIndex].soundCollection[index];
  8087. }
  8088. }
  8089. }
  8090. return null;
  8091. };
  8092. Scene.prototype.getLastSkeletonByID = function (id) {
  8093. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8094. if (this.skeletons[index].id === id) {
  8095. return this.skeletons[index];
  8096. }
  8097. }
  8098. return null;
  8099. };
  8100. Scene.prototype.getSkeletonById = function (id) {
  8101. for (var index = 0; index < this.skeletons.length; index++) {
  8102. if (this.skeletons[index].id === id) {
  8103. return this.skeletons[index];
  8104. }
  8105. }
  8106. return null;
  8107. };
  8108. Scene.prototype.getSkeletonByName = function (name) {
  8109. for (var index = 0; index < this.skeletons.length; index++) {
  8110. if (this.skeletons[index].name === name) {
  8111. return this.skeletons[index];
  8112. }
  8113. }
  8114. return null;
  8115. };
  8116. Scene.prototype.isActiveMesh = function (mesh) {
  8117. return (this._activeMeshes.indexOf(mesh) !== -1);
  8118. };
  8119. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8120. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8121. var material = subMesh.getMaterial();
  8122. if (mesh.showSubMeshesBoundingBox) {
  8123. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8124. }
  8125. if (material) {
  8126. // Render targets
  8127. if (material.getRenderTargetTextures) {
  8128. if (this._processedMaterials.indexOf(material) === -1) {
  8129. this._processedMaterials.push(material);
  8130. this._renderTargets.concat(material.getRenderTargetTextures());
  8131. }
  8132. }
  8133. // Dispatch
  8134. this._activeVertices += subMesh.indexCount;
  8135. this._renderingManager.dispatch(subMesh);
  8136. }
  8137. }
  8138. };
  8139. Scene.prototype._evaluateActiveMeshes = function () {
  8140. this._activeMeshes.reset();
  8141. this._renderingManager.reset();
  8142. this._processedMaterials.reset();
  8143. this._activeParticleSystems.reset();
  8144. this._activeSkeletons.reset();
  8145. this._boundingBoxRenderer.reset();
  8146. if (!this._frustumPlanes) {
  8147. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8148. }
  8149. else {
  8150. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8151. }
  8152. // Meshes
  8153. var meshes;
  8154. var len;
  8155. if (this._selectionOctree) {
  8156. var selection = this._selectionOctree.select(this._frustumPlanes);
  8157. meshes = selection.data;
  8158. len = selection.length;
  8159. }
  8160. else {
  8161. len = this.meshes.length;
  8162. meshes = this.meshes;
  8163. }
  8164. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8165. var mesh = meshes[meshIndex];
  8166. if (mesh.isBlocked) {
  8167. continue;
  8168. }
  8169. this._totalVertices += mesh.getTotalVertices();
  8170. if (!mesh.isReady()) {
  8171. continue;
  8172. }
  8173. mesh.computeWorldMatrix();
  8174. // Intersections
  8175. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8176. this._meshesForIntersections.pushNoDuplicate(mesh);
  8177. }
  8178. // Switch to current LOD
  8179. var meshLOD = mesh.getLOD(this.activeCamera);
  8180. if (!meshLOD) {
  8181. continue;
  8182. }
  8183. mesh._preActivate();
  8184. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8185. this._activeMeshes.push(mesh);
  8186. mesh._activate(this._renderId);
  8187. this._activeMesh(meshLOD);
  8188. }
  8189. }
  8190. // Particle systems
  8191. var beforeParticlesDate = BABYLON.Tools.Now;
  8192. if (this.particlesEnabled) {
  8193. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8194. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8195. var particleSystem = this.particleSystems[particleIndex];
  8196. if (!particleSystem.isStarted()) {
  8197. continue;
  8198. }
  8199. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8200. this._activeParticleSystems.push(particleSystem);
  8201. particleSystem.animate();
  8202. }
  8203. }
  8204. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8205. }
  8206. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8207. };
  8208. Scene.prototype._activeMesh = function (mesh) {
  8209. if (mesh.skeleton && this.skeletonsEnabled) {
  8210. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8211. }
  8212. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8213. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8214. }
  8215. if (mesh && mesh.subMeshes) {
  8216. // Submeshes Octrees
  8217. var len;
  8218. var subMeshes;
  8219. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8220. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8221. len = intersections.length;
  8222. subMeshes = intersections.data;
  8223. }
  8224. else {
  8225. subMeshes = mesh.subMeshes;
  8226. len = subMeshes.length;
  8227. }
  8228. for (var subIndex = 0; subIndex < len; subIndex++) {
  8229. var subMesh = subMeshes[subIndex];
  8230. this._evaluateSubMesh(subMesh, mesh);
  8231. }
  8232. }
  8233. };
  8234. Scene.prototype.updateTransformMatrix = function (force) {
  8235. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8236. };
  8237. Scene.prototype._renderForCamera = function (camera) {
  8238. var engine = this._engine;
  8239. this.activeCamera = camera;
  8240. if (!this.activeCamera)
  8241. throw new Error("Active camera not set");
  8242. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8243. // Viewport
  8244. engine.setViewport(this.activeCamera.viewport);
  8245. // Camera
  8246. this._renderId++;
  8247. this.updateTransformMatrix();
  8248. if (this.beforeCameraRender) {
  8249. this.beforeCameraRender(this.activeCamera);
  8250. }
  8251. // Meshes
  8252. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8253. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8254. this._evaluateActiveMeshes();
  8255. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8256. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8257. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8258. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8259. skeleton.prepare();
  8260. this._activeBones += skeleton.bones.length;
  8261. }
  8262. // Render targets
  8263. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8264. if (this.renderTargetsEnabled) {
  8265. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8266. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8267. var renderTarget = this._renderTargets.data[renderIndex];
  8268. if (renderTarget._shouldRender()) {
  8269. this._renderId++;
  8270. renderTarget.render();
  8271. }
  8272. }
  8273. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8274. this._renderId++;
  8275. }
  8276. if (this._renderTargets.length > 0) {
  8277. engine.restoreDefaultFramebuffer();
  8278. }
  8279. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8280. // Prepare Frame
  8281. this.postProcessManager._prepareFrame();
  8282. var beforeRenderDate = BABYLON.Tools.Now;
  8283. // Backgrounds
  8284. if (this.layers.length) {
  8285. engine.setDepthBuffer(false);
  8286. var layerIndex;
  8287. var layer;
  8288. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8289. layer = this.layers[layerIndex];
  8290. if (layer.isBackground) {
  8291. layer.render();
  8292. }
  8293. }
  8294. engine.setDepthBuffer(true);
  8295. }
  8296. // Render
  8297. BABYLON.Tools.StartPerformanceCounter("Main render");
  8298. this._renderingManager.render(null, null, true, true);
  8299. BABYLON.Tools.EndPerformanceCounter("Main render");
  8300. // Bounding boxes
  8301. this._boundingBoxRenderer.render();
  8302. // Lens flares
  8303. if (this.lensFlaresEnabled) {
  8304. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8305. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8306. this.lensFlareSystems[lensFlareSystemIndex].render();
  8307. }
  8308. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8309. }
  8310. // Foregrounds
  8311. if (this.layers.length) {
  8312. engine.setDepthBuffer(false);
  8313. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8314. layer = this.layers[layerIndex];
  8315. if (!layer.isBackground) {
  8316. layer.render();
  8317. }
  8318. }
  8319. engine.setDepthBuffer(true);
  8320. }
  8321. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8322. // Finalize frame
  8323. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8324. // Update camera
  8325. this.activeCamera._updateFromScene();
  8326. // Reset some special arrays
  8327. this._renderTargets.reset();
  8328. if (this.afterCameraRender) {
  8329. this.afterCameraRender(this.activeCamera);
  8330. }
  8331. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8332. };
  8333. Scene.prototype._processSubCameras = function (camera) {
  8334. if (camera.subCameras.length === 0) {
  8335. this._renderForCamera(camera);
  8336. return;
  8337. }
  8338. for (var index = 0; index < camera.subCameras.length; index++) {
  8339. this._renderForCamera(camera.subCameras[index]);
  8340. }
  8341. this.activeCamera = camera;
  8342. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8343. // Update camera
  8344. this.activeCamera._updateFromScene();
  8345. };
  8346. Scene.prototype._checkIntersections = function () {
  8347. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8348. var sourceMesh = this._meshesForIntersections.data[index];
  8349. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8350. var action = sourceMesh.actionManager.actions[actionIndex];
  8351. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8352. var otherMesh = action.getTriggerParameter();
  8353. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  8354. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8355. if (areIntersecting && currentIntersectionInProgress === -1) {
  8356. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8357. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8358. sourceMesh._intersectionsInProgress.push(otherMesh);
  8359. }
  8360. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8361. sourceMesh._intersectionsInProgress.push(otherMesh);
  8362. }
  8363. }
  8364. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8365. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8366. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8367. if (indexOfOther > -1) {
  8368. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8369. }
  8370. }
  8371. }
  8372. }
  8373. }
  8374. };
  8375. Scene.prototype.render = function () {
  8376. var startDate = BABYLON.Tools.Now;
  8377. this._particlesDuration = 0;
  8378. this._spritesDuration = 0;
  8379. this._activeParticles = 0;
  8380. this._renderDuration = 0;
  8381. this._renderTargetsDuration = 0;
  8382. this._evaluateActiveMeshesDuration = 0;
  8383. this._totalVertices = 0;
  8384. this._activeVertices = 0;
  8385. this._activeBones = 0;
  8386. this.getEngine().resetDrawCalls();
  8387. this._meshesForIntersections.reset();
  8388. this.resetCachedMaterial();
  8389. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8390. // Actions
  8391. if (this.actionManager) {
  8392. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8393. }
  8394. // Before render
  8395. if (this.beforeRender) {
  8396. this.beforeRender();
  8397. }
  8398. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8399. this._onBeforeRenderCallbacks[callbackIndex]();
  8400. }
  8401. // Animations
  8402. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8403. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8404. this._animate();
  8405. // Physics
  8406. if (this._physicsEngine) {
  8407. BABYLON.Tools.StartPerformanceCounter("Physics");
  8408. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8409. BABYLON.Tools.EndPerformanceCounter("Physics");
  8410. }
  8411. // Customs render targets
  8412. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8413. var engine = this.getEngine();
  8414. if (this.renderTargetsEnabled) {
  8415. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8416. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8417. var renderTarget = this.customRenderTargets[customIndex];
  8418. if (renderTarget._shouldRender()) {
  8419. this._renderId++;
  8420. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8421. if (!this.activeCamera)
  8422. throw new Error("Active camera not set");
  8423. // Viewport
  8424. engine.setViewport(this.activeCamera.viewport);
  8425. // Camera
  8426. this.updateTransformMatrix();
  8427. renderTarget.render();
  8428. }
  8429. }
  8430. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8431. this._renderId++;
  8432. }
  8433. if (this.customRenderTargets.length > 0) {
  8434. engine.restoreDefaultFramebuffer();
  8435. }
  8436. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8437. // Procedural textures
  8438. if (this.proceduralTexturesEnabled) {
  8439. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8440. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8441. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8442. if (proceduralTexture._shouldRender()) {
  8443. proceduralTexture.render();
  8444. }
  8445. }
  8446. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8447. }
  8448. // Clear
  8449. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8450. // Shadows
  8451. if (this.shadowsEnabled) {
  8452. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8453. var light = this.lights[lightIndex];
  8454. var shadowGenerator = light.getShadowGenerator();
  8455. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8456. this._renderTargets.push(shadowGenerator.getShadowMap());
  8457. }
  8458. }
  8459. }
  8460. // Depth renderer
  8461. if (this._depthRenderer) {
  8462. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8463. }
  8464. // RenderPipeline
  8465. this.postProcessRenderPipelineManager.update();
  8466. // Multi-cameras?
  8467. if (this.activeCameras.length > 0) {
  8468. var currentRenderId = this._renderId;
  8469. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8470. this._renderId = currentRenderId;
  8471. this._processSubCameras(this.activeCameras[cameraIndex]);
  8472. }
  8473. }
  8474. else {
  8475. if (!this.activeCamera) {
  8476. throw new Error("No camera defined");
  8477. }
  8478. this._processSubCameras(this.activeCamera);
  8479. }
  8480. // Intersection checks
  8481. this._checkIntersections();
  8482. // Update the audio listener attached to the camera
  8483. this._updateAudioParameters();
  8484. // After render
  8485. if (this.afterRender) {
  8486. this.afterRender();
  8487. }
  8488. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8489. this._onAfterRenderCallbacks[callbackIndex]();
  8490. }
  8491. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8492. this._toBeDisposed.data[index].dispose();
  8493. this._toBeDisposed[index] = null;
  8494. }
  8495. this._toBeDisposed.reset();
  8496. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8497. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8498. };
  8499. Scene.prototype._updateAudioParameters = function () {
  8500. var listeningCamera;
  8501. var audioEngine = BABYLON.Engine.audioEngine;
  8502. if (this.activeCameras.length > 0) {
  8503. listeningCamera = this.activeCameras[0];
  8504. }
  8505. else {
  8506. listeningCamera = this.activeCamera;
  8507. }
  8508. if (listeningCamera && audioEngine.canUseWebAudio) {
  8509. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8510. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8511. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8512. cameraDirection.normalize();
  8513. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8514. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8515. var sound = this.mainSoundTrack.soundCollection[i];
  8516. if (sound.useCustomAttenuation) {
  8517. sound.updateDistanceFromListener();
  8518. }
  8519. }
  8520. for (i = 0; i < this.soundTracks.length; i++) {
  8521. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8522. sound = this.soundTracks[i].soundCollection[j];
  8523. if (sound.useCustomAttenuation) {
  8524. sound.updateDistanceFromListener();
  8525. }
  8526. }
  8527. }
  8528. }
  8529. };
  8530. Scene.prototype.enableDepthRenderer = function () {
  8531. if (this._depthRenderer) {
  8532. return this._depthRenderer;
  8533. }
  8534. this._depthRenderer = new BABYLON.DepthRenderer(this);
  8535. return this._depthRenderer;
  8536. };
  8537. Scene.prototype.disableDepthRenderer = function () {
  8538. if (!this._depthRenderer) {
  8539. return;
  8540. }
  8541. this._depthRenderer.dispose();
  8542. this._depthRenderer = null;
  8543. };
  8544. Scene.prototype.dispose = function () {
  8545. this.beforeRender = null;
  8546. this.afterRender = null;
  8547. this.skeletons = [];
  8548. this._boundingBoxRenderer.dispose();
  8549. if (this._depthRenderer) {
  8550. this._depthRenderer.dispose();
  8551. }
  8552. // Debug layer
  8553. this.debugLayer.hide();
  8554. // Events
  8555. if (this.onDispose) {
  8556. this.onDispose();
  8557. }
  8558. this._onBeforeRenderCallbacks = [];
  8559. this._onAfterRenderCallbacks = [];
  8560. this.detachControl();
  8561. // Release sounds & sounds tracks
  8562. this.mainSoundTrack.dispose();
  8563. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  8564. this.soundTracks[scIndex].dispose();
  8565. }
  8566. // Detach cameras
  8567. var canvas = this._engine.getRenderingCanvas();
  8568. var index;
  8569. for (index = 0; index < this.cameras.length; index++) {
  8570. this.cameras[index].detachControl(canvas);
  8571. }
  8572. while (this.lights.length) {
  8573. this.lights[0].dispose();
  8574. }
  8575. while (this.meshes.length) {
  8576. this.meshes[0].dispose(true);
  8577. }
  8578. while (this.cameras.length) {
  8579. this.cameras[0].dispose();
  8580. }
  8581. while (this.materials.length) {
  8582. this.materials[0].dispose();
  8583. }
  8584. while (this.particleSystems.length) {
  8585. this.particleSystems[0].dispose();
  8586. }
  8587. while (this.spriteManagers.length) {
  8588. this.spriteManagers[0].dispose();
  8589. }
  8590. while (this.layers.length) {
  8591. this.layers[0].dispose();
  8592. }
  8593. while (this.textures.length) {
  8594. this.textures[0].dispose();
  8595. }
  8596. // Post-processes
  8597. this.postProcessManager.dispose();
  8598. // Physics
  8599. if (this._physicsEngine) {
  8600. this.disablePhysicsEngine();
  8601. }
  8602. // Remove from engine
  8603. index = this._engine.scenes.indexOf(this);
  8604. if (index > -1) {
  8605. this._engine.scenes.splice(index, 1);
  8606. }
  8607. this._engine.wipeCaches();
  8608. };
  8609. // Collisions
  8610. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8611. if (excludedMesh === void 0) { excludedMesh = null; }
  8612. position.divideToRef(collider.radius, this._scaledPosition);
  8613. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8614. collider.retry = 0;
  8615. collider.initialVelocity = this._scaledVelocity;
  8616. collider.initialPosition = this._scaledPosition;
  8617. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8618. finalPosition.multiplyInPlace(collider.radius);
  8619. };
  8620. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8621. if (excludedMesh === void 0) { excludedMesh = null; }
  8622. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8623. if (collider.retry >= maximumRetry) {
  8624. finalPosition.copyFrom(position);
  8625. return;
  8626. }
  8627. collider._initialize(position, velocity, closeDistance);
  8628. for (var index = 0; index < this.meshes.length; index++) {
  8629. var mesh = this.meshes[index];
  8630. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8631. mesh._checkCollision(collider);
  8632. }
  8633. }
  8634. if (!collider.collisionFound) {
  8635. position.addToRef(velocity, finalPosition);
  8636. return;
  8637. }
  8638. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8639. collider._getResponse(position, velocity);
  8640. }
  8641. if (velocity.length() <= closeDistance) {
  8642. finalPosition.copyFrom(position);
  8643. return;
  8644. }
  8645. collider.retry++;
  8646. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8647. };
  8648. // Octrees
  8649. Scene.prototype.getWorldExtends = function () {
  8650. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8651. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8652. for (var index = 0; index < this.meshes.length; index++) {
  8653. var mesh = this.meshes[index];
  8654. mesh.computeWorldMatrix(true);
  8655. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8656. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8657. BABYLON.Tools.CheckExtends(minBox, min, max);
  8658. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8659. }
  8660. return {
  8661. min: min,
  8662. max: max
  8663. };
  8664. };
  8665. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8666. if (maxCapacity === void 0) { maxCapacity = 64; }
  8667. if (maxDepth === void 0) { maxDepth = 2; }
  8668. if (!this._selectionOctree) {
  8669. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8670. }
  8671. var worldExtends = this.getWorldExtends();
  8672. // Update octree
  8673. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  8674. return this._selectionOctree;
  8675. };
  8676. // Picking
  8677. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8678. var engine = this._engine;
  8679. if (!camera) {
  8680. if (!this.activeCamera)
  8681. throw new Error("Active camera not set");
  8682. camera = this.activeCamera;
  8683. }
  8684. var cameraViewport = camera.viewport;
  8685. var viewport = cameraViewport.toGlobal(engine);
  8686. // Moving coordinates to local viewport world
  8687. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8688. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8689. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8690. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8691. };
  8692. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8693. var pickingInfo = null;
  8694. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8695. var mesh = this.meshes[meshIndex];
  8696. if (predicate) {
  8697. if (!predicate(mesh)) {
  8698. continue;
  8699. }
  8700. }
  8701. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8702. continue;
  8703. }
  8704. var world = mesh.getWorldMatrix();
  8705. var ray = rayFunction(world);
  8706. var result = mesh.intersects(ray, fastCheck);
  8707. if (!result || !result.hit)
  8708. continue;
  8709. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8710. continue;
  8711. pickingInfo = result;
  8712. if (fastCheck) {
  8713. break;
  8714. }
  8715. }
  8716. return pickingInfo || new BABYLON.PickingInfo();
  8717. };
  8718. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8719. var _this = this;
  8720. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8721. /// <param name="x">X position on screen</param>
  8722. /// <param name="y">Y position on screen</param>
  8723. /// <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>
  8724. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8725. /// <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>
  8726. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  8727. };
  8728. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8729. var _this = this;
  8730. return this._internalPick(function (world) {
  8731. if (!_this._pickWithRayInverseMatrix) {
  8732. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8733. }
  8734. world.invertToRef(_this._pickWithRayInverseMatrix);
  8735. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8736. }, predicate, fastCheck);
  8737. };
  8738. Scene.prototype.setPointerOverMesh = function (mesh) {
  8739. if (this._pointerOverMesh === mesh) {
  8740. return;
  8741. }
  8742. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8743. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8744. }
  8745. this._pointerOverMesh = mesh;
  8746. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8747. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8748. }
  8749. };
  8750. Scene.prototype.getPointerOverMesh = function () {
  8751. return this._pointerOverMesh;
  8752. };
  8753. // Physics
  8754. Scene.prototype.getPhysicsEngine = function () {
  8755. return this._physicsEngine;
  8756. };
  8757. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8758. if (this._physicsEngine) {
  8759. return true;
  8760. }
  8761. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8762. if (!this._physicsEngine.isSupported()) {
  8763. this._physicsEngine = null;
  8764. return false;
  8765. }
  8766. this._physicsEngine._initialize(gravity);
  8767. return true;
  8768. };
  8769. Scene.prototype.disablePhysicsEngine = function () {
  8770. if (!this._physicsEngine) {
  8771. return;
  8772. }
  8773. this._physicsEngine.dispose();
  8774. this._physicsEngine = undefined;
  8775. };
  8776. Scene.prototype.isPhysicsEnabled = function () {
  8777. return this._physicsEngine !== undefined;
  8778. };
  8779. Scene.prototype.setGravity = function (gravity) {
  8780. if (!this._physicsEngine) {
  8781. return;
  8782. }
  8783. this._physicsEngine._setGravity(gravity);
  8784. };
  8785. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8786. if (parts.parts) {
  8787. options = parts;
  8788. parts = parts.parts;
  8789. }
  8790. if (!this._physicsEngine) {
  8791. return null;
  8792. }
  8793. for (var index = 0; index < parts.length; index++) {
  8794. var mesh = parts[index].mesh;
  8795. mesh._physicImpostor = parts[index].impostor;
  8796. mesh._physicsMass = options.mass / parts.length;
  8797. mesh._physicsFriction = options.friction;
  8798. mesh._physicRestitution = options.restitution;
  8799. }
  8800. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8801. };
  8802. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8803. for (var index = 0; index < compound.parts.length; index++) {
  8804. var mesh = compound.parts[index].mesh;
  8805. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8806. this._physicsEngine._unregisterMesh(mesh);
  8807. }
  8808. };
  8809. // Misc.
  8810. Scene.prototype.createDefaultCameraOrLight = function () {
  8811. // Light
  8812. if (this.lights.length === 0) {
  8813. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  8814. }
  8815. // Camera
  8816. if (!this.activeCamera) {
  8817. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  8818. // Compute position
  8819. var worldExtends = this.getWorldExtends();
  8820. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  8821. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  8822. camera.setTarget(worldCenter);
  8823. this.activeCamera = camera;
  8824. }
  8825. };
  8826. // Tags
  8827. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  8828. if (tagsQuery === undefined) {
  8829. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8830. return list;
  8831. }
  8832. var listByTags = [];
  8833. forEach = forEach || (function (item) {
  8834. return;
  8835. });
  8836. for (var i in list) {
  8837. var item = list[i];
  8838. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8839. listByTags.push(item);
  8840. forEach(item);
  8841. }
  8842. }
  8843. return listByTags;
  8844. };
  8845. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  8846. return this._getByTags(this.meshes, tagsQuery, forEach);
  8847. };
  8848. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  8849. return this._getByTags(this.cameras, tagsQuery, forEach);
  8850. };
  8851. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  8852. return this._getByTags(this.lights, tagsQuery, forEach);
  8853. };
  8854. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  8855. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  8856. };
  8857. // Statics
  8858. Scene.FOGMODE_NONE = 0;
  8859. Scene.FOGMODE_EXP = 1;
  8860. Scene.FOGMODE_EXP2 = 2;
  8861. Scene.FOGMODE_LINEAR = 3;
  8862. Scene.MinDeltaTime = 1.0;
  8863. Scene.MaxDeltaTime = 1000.0;
  8864. return Scene;
  8865. })();
  8866. BABYLON.Scene = Scene;
  8867. })(BABYLON || (BABYLON = {}));
  8868. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  8869. (function (BABYLON) {
  8870. var VertexBuffer = (function () {
  8871. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8872. if (engine instanceof BABYLON.Mesh) {
  8873. this._engine = engine.getScene().getEngine();
  8874. }
  8875. else {
  8876. this._engine = engine;
  8877. }
  8878. this._updatable = updatable;
  8879. this._data = data;
  8880. if (!postponeInternalCreation) {
  8881. this.create();
  8882. }
  8883. this._kind = kind;
  8884. if (stride) {
  8885. this._strideSize = stride;
  8886. return;
  8887. }
  8888. switch (kind) {
  8889. case VertexBuffer.PositionKind:
  8890. this._strideSize = 3;
  8891. break;
  8892. case VertexBuffer.NormalKind:
  8893. this._strideSize = 3;
  8894. break;
  8895. case VertexBuffer.UVKind:
  8896. this._strideSize = 2;
  8897. break;
  8898. case VertexBuffer.UV2Kind:
  8899. this._strideSize = 2;
  8900. break;
  8901. case VertexBuffer.ColorKind:
  8902. this._strideSize = 4;
  8903. break;
  8904. case VertexBuffer.MatricesIndicesKind:
  8905. this._strideSize = 4;
  8906. break;
  8907. case VertexBuffer.MatricesWeightsKind:
  8908. this._strideSize = 4;
  8909. break;
  8910. }
  8911. }
  8912. // Properties
  8913. VertexBuffer.prototype.isUpdatable = function () {
  8914. return this._updatable;
  8915. };
  8916. VertexBuffer.prototype.getData = function () {
  8917. return this._data;
  8918. };
  8919. VertexBuffer.prototype.getBuffer = function () {
  8920. return this._buffer;
  8921. };
  8922. VertexBuffer.prototype.getStrideSize = function () {
  8923. return this._strideSize;
  8924. };
  8925. // Methods
  8926. VertexBuffer.prototype.create = function (data) {
  8927. if (!data && this._buffer) {
  8928. return; // nothing to do
  8929. }
  8930. data = data || this._data;
  8931. if (!this._buffer) {
  8932. if (this._updatable) {
  8933. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8934. }
  8935. else {
  8936. this._buffer = this._engine.createVertexBuffer(data);
  8937. }
  8938. }
  8939. if (this._updatable) {
  8940. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  8941. this._data = data;
  8942. }
  8943. };
  8944. VertexBuffer.prototype.update = function (data) {
  8945. this.create(data);
  8946. };
  8947. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  8948. if (!this._buffer) {
  8949. return;
  8950. }
  8951. if (this._updatable) {
  8952. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  8953. this._data = null;
  8954. }
  8955. };
  8956. VertexBuffer.prototype.dispose = function () {
  8957. if (!this._buffer) {
  8958. return;
  8959. }
  8960. if (this._engine._releaseBuffer(this._buffer)) {
  8961. this._buffer = null;
  8962. }
  8963. };
  8964. Object.defineProperty(VertexBuffer, "PositionKind", {
  8965. get: function () {
  8966. return VertexBuffer._PositionKind;
  8967. },
  8968. enumerable: true,
  8969. configurable: true
  8970. });
  8971. Object.defineProperty(VertexBuffer, "NormalKind", {
  8972. get: function () {
  8973. return VertexBuffer._NormalKind;
  8974. },
  8975. enumerable: true,
  8976. configurable: true
  8977. });
  8978. Object.defineProperty(VertexBuffer, "UVKind", {
  8979. get: function () {
  8980. return VertexBuffer._UVKind;
  8981. },
  8982. enumerable: true,
  8983. configurable: true
  8984. });
  8985. Object.defineProperty(VertexBuffer, "UV2Kind", {
  8986. get: function () {
  8987. return VertexBuffer._UV2Kind;
  8988. },
  8989. enumerable: true,
  8990. configurable: true
  8991. });
  8992. Object.defineProperty(VertexBuffer, "ColorKind", {
  8993. get: function () {
  8994. return VertexBuffer._ColorKind;
  8995. },
  8996. enumerable: true,
  8997. configurable: true
  8998. });
  8999. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9000. get: function () {
  9001. return VertexBuffer._MatricesIndicesKind;
  9002. },
  9003. enumerable: true,
  9004. configurable: true
  9005. });
  9006. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9007. get: function () {
  9008. return VertexBuffer._MatricesWeightsKind;
  9009. },
  9010. enumerable: true,
  9011. configurable: true
  9012. });
  9013. // Enums
  9014. VertexBuffer._PositionKind = "position";
  9015. VertexBuffer._NormalKind = "normal";
  9016. VertexBuffer._UVKind = "uv";
  9017. VertexBuffer._UV2Kind = "uv2";
  9018. VertexBuffer._ColorKind = "color";
  9019. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9020. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9021. return VertexBuffer;
  9022. })();
  9023. BABYLON.VertexBuffer = VertexBuffer;
  9024. })(BABYLON || (BABYLON = {}));
  9025. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9026. var BABYLON;
  9027. (function (BABYLON) {
  9028. var AbstractMesh = (function (_super) {
  9029. __extends(AbstractMesh, _super);
  9030. function AbstractMesh(name, scene) {
  9031. _super.call(this, name, scene);
  9032. // Properties
  9033. this.definedFacingForward = true; // orientation for POV movement & rotation
  9034. this.position = new BABYLON.Vector3(0, 0, 0);
  9035. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9036. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9037. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9038. this.visibility = 1.0;
  9039. this.alphaIndex = Number.MAX_VALUE;
  9040. this.infiniteDistance = false;
  9041. this.isVisible = true;
  9042. this.isPickable = true;
  9043. this.showBoundingBox = false;
  9044. this.showSubMeshesBoundingBox = false;
  9045. this.onDispose = null;
  9046. this.checkCollisions = false;
  9047. this.isBlocker = false;
  9048. this.renderingGroupId = 0;
  9049. this.receiveShadows = false;
  9050. this.renderOutline = false;
  9051. this.outlineColor = BABYLON.Color3.Red();
  9052. this.outlineWidth = 0.02;
  9053. this.renderOverlay = false;
  9054. this.overlayColor = BABYLON.Color3.Red();
  9055. this.overlayAlpha = 0.5;
  9056. this.hasVertexAlpha = false;
  9057. this.useVertexColors = true;
  9058. this.applyFog = true;
  9059. this.useOctreeForRenderingSelection = true;
  9060. this.useOctreeForPicking = true;
  9061. this.useOctreeForCollisions = true;
  9062. this.layerMask = 0xFFFFFFFF;
  9063. // Physics
  9064. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9065. // Collisions
  9066. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9067. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9068. this._collider = new BABYLON.Collider();
  9069. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9070. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9071. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9072. // Cache
  9073. this._localScaling = BABYLON.Matrix.Zero();
  9074. this._localRotation = BABYLON.Matrix.Zero();
  9075. this._localTranslation = BABYLON.Matrix.Zero();
  9076. this._localBillboard = BABYLON.Matrix.Zero();
  9077. this._localPivotScaling = BABYLON.Matrix.Zero();
  9078. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9079. this._localWorld = BABYLON.Matrix.Zero();
  9080. this._worldMatrix = BABYLON.Matrix.Zero();
  9081. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9082. this._absolutePosition = BABYLON.Vector3.Zero();
  9083. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9084. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9085. this._isDirty = false;
  9086. this._pivotMatrix = BABYLON.Matrix.Identity();
  9087. this._isDisposed = false;
  9088. this._renderId = 0;
  9089. this._intersectionsInProgress = new Array();
  9090. this._onAfterWorldMatrixUpdate = new Array();
  9091. scene.meshes.push(this);
  9092. }
  9093. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9094. get: function () {
  9095. return AbstractMesh._BILLBOARDMODE_NONE;
  9096. },
  9097. enumerable: true,
  9098. configurable: true
  9099. });
  9100. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9101. get: function () {
  9102. return AbstractMesh._BILLBOARDMODE_X;
  9103. },
  9104. enumerable: true,
  9105. configurable: true
  9106. });
  9107. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9108. get: function () {
  9109. return AbstractMesh._BILLBOARDMODE_Y;
  9110. },
  9111. enumerable: true,
  9112. configurable: true
  9113. });
  9114. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9115. get: function () {
  9116. return AbstractMesh._BILLBOARDMODE_Z;
  9117. },
  9118. enumerable: true,
  9119. configurable: true
  9120. });
  9121. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9122. get: function () {
  9123. return AbstractMesh._BILLBOARDMODE_ALL;
  9124. },
  9125. enumerable: true,
  9126. configurable: true
  9127. });
  9128. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9129. // Methods
  9130. get: function () {
  9131. return false;
  9132. },
  9133. enumerable: true,
  9134. configurable: true
  9135. });
  9136. AbstractMesh.prototype.getLOD = function (camera) {
  9137. return this;
  9138. };
  9139. AbstractMesh.prototype.getTotalVertices = function () {
  9140. return 0;
  9141. };
  9142. AbstractMesh.prototype.getIndices = function () {
  9143. return null;
  9144. };
  9145. AbstractMesh.prototype.getVerticesData = function (kind) {
  9146. return null;
  9147. };
  9148. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9149. return false;
  9150. };
  9151. AbstractMesh.prototype.getBoundingInfo = function () {
  9152. if (this._masterMesh) {
  9153. return this._masterMesh.getBoundingInfo();
  9154. }
  9155. if (!this._boundingInfo) {
  9156. this._updateBoundingInfo();
  9157. }
  9158. return this._boundingInfo;
  9159. };
  9160. AbstractMesh.prototype._preActivate = function () {
  9161. };
  9162. AbstractMesh.prototype._activate = function (renderId) {
  9163. this._renderId = renderId;
  9164. };
  9165. AbstractMesh.prototype.getWorldMatrix = function () {
  9166. if (this._masterMesh) {
  9167. return this._masterMesh.getWorldMatrix();
  9168. }
  9169. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9170. this.computeWorldMatrix();
  9171. }
  9172. return this._worldMatrix;
  9173. };
  9174. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9175. get: function () {
  9176. return this._worldMatrix;
  9177. },
  9178. enumerable: true,
  9179. configurable: true
  9180. });
  9181. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9182. get: function () {
  9183. return this._absolutePosition;
  9184. },
  9185. enumerable: true,
  9186. configurable: true
  9187. });
  9188. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9189. if (!this.rotationQuaternion) {
  9190. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9191. this.rotation = BABYLON.Vector3.Zero();
  9192. }
  9193. if (!space || space == 0 /* LOCAL */) {
  9194. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9195. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9196. }
  9197. else {
  9198. if (this.parent) {
  9199. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9200. invertParentWorldMatrix.invert();
  9201. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9202. }
  9203. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9204. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9205. }
  9206. };
  9207. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9208. var displacementVector = axis.scale(distance);
  9209. if (!space || space == 0 /* LOCAL */) {
  9210. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9211. this.setPositionWithLocalVector(tempV3);
  9212. }
  9213. else {
  9214. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9215. }
  9216. };
  9217. AbstractMesh.prototype.getAbsolutePosition = function () {
  9218. this.computeWorldMatrix();
  9219. return this._absolutePosition;
  9220. };
  9221. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9222. if (!absolutePosition) {
  9223. return;
  9224. }
  9225. var absolutePositionX;
  9226. var absolutePositionY;
  9227. var absolutePositionZ;
  9228. if (absolutePosition.x === undefined) {
  9229. if (arguments.length < 3) {
  9230. return;
  9231. }
  9232. absolutePositionX = arguments[0];
  9233. absolutePositionY = arguments[1];
  9234. absolutePositionZ = arguments[2];
  9235. }
  9236. else {
  9237. absolutePositionX = absolutePosition.x;
  9238. absolutePositionY = absolutePosition.y;
  9239. absolutePositionZ = absolutePosition.z;
  9240. }
  9241. if (this.parent) {
  9242. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9243. invertParentWorldMatrix.invert();
  9244. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9245. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9246. }
  9247. else {
  9248. this.position.x = absolutePositionX;
  9249. this.position.y = absolutePositionY;
  9250. this.position.z = absolutePositionZ;
  9251. }
  9252. };
  9253. // ================================== Point of View Movement =================================
  9254. /**
  9255. * Perform relative position change from the point of view of behind the front of the mesh.
  9256. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9257. * Supports definition of mesh facing forward or backward.
  9258. * @param {number} amountRight
  9259. * @param {number} amountUp
  9260. * @param {number} amountForward
  9261. */
  9262. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9263. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9264. };
  9265. /**
  9266. * Calculate relative position change from the point of view of behind the front of the mesh.
  9267. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9268. * Supports definition of mesh facing forward or backward.
  9269. * @param {number} amountRight
  9270. * @param {number} amountUp
  9271. * @param {number} amountForward
  9272. */
  9273. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9274. var rotMatrix = new BABYLON.Matrix();
  9275. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9276. rotQuaternion.toRotationMatrix(rotMatrix);
  9277. var translationDelta = BABYLON.Vector3.Zero();
  9278. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9279. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9280. return translationDelta;
  9281. };
  9282. // ================================== Point of View Rotation =================================
  9283. /**
  9284. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9285. * Supports definition of mesh facing forward or backward.
  9286. * @param {number} flipBack
  9287. * @param {number} twirlClockwise
  9288. * @param {number} tiltRight
  9289. */
  9290. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9291. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9292. };
  9293. /**
  9294. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9295. * Supports definition of mesh facing forward or backward.
  9296. * @param {number} flipBack
  9297. * @param {number} twirlClockwise
  9298. * @param {number} tiltRight
  9299. */
  9300. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9301. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9302. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9303. };
  9304. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9305. this._pivotMatrix = matrix;
  9306. this._cache.pivotMatrixUpdated = true;
  9307. };
  9308. AbstractMesh.prototype.getPivotMatrix = function () {
  9309. return this._pivotMatrix;
  9310. };
  9311. AbstractMesh.prototype._isSynchronized = function () {
  9312. if (this._isDirty) {
  9313. return false;
  9314. }
  9315. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9316. return false;
  9317. if (this._cache.pivotMatrixUpdated) {
  9318. return false;
  9319. }
  9320. if (this.infiniteDistance) {
  9321. return false;
  9322. }
  9323. if (!this._cache.position.equals(this.position))
  9324. return false;
  9325. if (this.rotationQuaternion) {
  9326. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9327. return false;
  9328. }
  9329. else {
  9330. if (!this._cache.rotation.equals(this.rotation))
  9331. return false;
  9332. }
  9333. if (!this._cache.scaling.equals(this.scaling))
  9334. return false;
  9335. return true;
  9336. };
  9337. AbstractMesh.prototype._initCache = function () {
  9338. _super.prototype._initCache.call(this);
  9339. this._cache.localMatrixUpdated = false;
  9340. this._cache.position = BABYLON.Vector3.Zero();
  9341. this._cache.scaling = BABYLON.Vector3.Zero();
  9342. this._cache.rotation = BABYLON.Vector3.Zero();
  9343. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9344. };
  9345. AbstractMesh.prototype.markAsDirty = function (property) {
  9346. if (property === "rotation") {
  9347. this.rotationQuaternion = null;
  9348. }
  9349. this._currentRenderId = Number.MAX_VALUE;
  9350. this._isDirty = true;
  9351. };
  9352. AbstractMesh.prototype._updateBoundingInfo = function () {
  9353. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9354. this._boundingInfo._update(this.worldMatrixFromCache);
  9355. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9356. };
  9357. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9358. if (!this.subMeshes) {
  9359. return;
  9360. }
  9361. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9362. var subMesh = this.subMeshes[subIndex];
  9363. subMesh.updateBoundingInfo(matrix);
  9364. }
  9365. };
  9366. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9367. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9368. return this._worldMatrix;
  9369. }
  9370. this._cache.position.copyFrom(this.position);
  9371. this._cache.scaling.copyFrom(this.scaling);
  9372. this._cache.pivotMatrixUpdated = false;
  9373. this._currentRenderId = this.getScene().getRenderId();
  9374. this._isDirty = false;
  9375. // Scaling
  9376. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9377. // Rotation
  9378. if (this.rotationQuaternion) {
  9379. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9380. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9381. }
  9382. else {
  9383. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9384. this._cache.rotation.copyFrom(this.rotation);
  9385. }
  9386. // Translation
  9387. if (this.infiniteDistance && !this.parent) {
  9388. var camera = this.getScene().activeCamera;
  9389. var cameraWorldMatrix = camera.getWorldMatrix();
  9390. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9391. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9392. }
  9393. else {
  9394. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9395. }
  9396. // Composing transformations
  9397. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9398. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9399. // Billboarding
  9400. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9401. var localPosition = this.position.clone();
  9402. var zero = this.getScene().activeCamera.position.clone();
  9403. if (this.parent && this.parent.position) {
  9404. localPosition.addInPlace(this.parent.position);
  9405. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9406. }
  9407. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9408. zero = this.getScene().activeCamera.position;
  9409. }
  9410. else {
  9411. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9412. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9413. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9414. zero.y = localPosition.y + 0.001;
  9415. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9416. zero.z = localPosition.z + 0.001;
  9417. }
  9418. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9419. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9420. this._localBillboard.invert();
  9421. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9422. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9423. }
  9424. // Local world
  9425. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9426. // Parent
  9427. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9428. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9429. }
  9430. else {
  9431. this._worldMatrix.copyFrom(this._localWorld);
  9432. }
  9433. // Bounding info
  9434. this._updateBoundingInfo();
  9435. // Absolute position
  9436. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9437. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9438. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9439. }
  9440. return this._worldMatrix;
  9441. };
  9442. /**
  9443. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9444. * @param func: callback function to add
  9445. */
  9446. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9447. this._onAfterWorldMatrixUpdate.push(func);
  9448. };
  9449. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9450. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  9451. if (index > -1) {
  9452. this._onAfterWorldMatrixUpdate.splice(index, 1);
  9453. }
  9454. };
  9455. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9456. this.computeWorldMatrix();
  9457. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9458. };
  9459. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9460. this.computeWorldMatrix();
  9461. var invLocalWorldMatrix = this._localWorld.clone();
  9462. invLocalWorldMatrix.invert();
  9463. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9464. };
  9465. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9466. this.computeWorldMatrix();
  9467. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9468. };
  9469. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9470. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9471. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9472. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9473. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9474. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9475. /// <returns>Mesh oriented towards targetMesh</returns>
  9476. yawCor = yawCor || 0; // default to zero if undefined
  9477. pitchCor = pitchCor || 0;
  9478. rollCor = rollCor || 0;
  9479. var dv = targetPoint.subtract(this.position);
  9480. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9481. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9482. var pitch = Math.atan2(dv.y, len);
  9483. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9484. };
  9485. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9486. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9487. return false;
  9488. }
  9489. return true;
  9490. };
  9491. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9492. if (!camera) {
  9493. camera = this.getScene().activeCamera;
  9494. }
  9495. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9496. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9497. return false;
  9498. }
  9499. return true;
  9500. };
  9501. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9502. if (!this._boundingInfo || !mesh._boundingInfo) {
  9503. return false;
  9504. }
  9505. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9506. };
  9507. AbstractMesh.prototype.intersectsPoint = function (point) {
  9508. if (!this._boundingInfo) {
  9509. return false;
  9510. }
  9511. return this._boundingInfo.intersectsPoint(point);
  9512. };
  9513. // Physics
  9514. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9515. var physicsEngine = this.getScene().getPhysicsEngine();
  9516. if (!physicsEngine) {
  9517. return;
  9518. }
  9519. if (impostor.impostor) {
  9520. // Old API
  9521. options = impostor;
  9522. impostor = impostor.impostor;
  9523. }
  9524. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9525. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9526. physicsEngine._unregisterMesh(this);
  9527. return;
  9528. }
  9529. options.mass = options.mass || 0;
  9530. options.friction = options.friction || 0.2;
  9531. options.restitution = options.restitution || 0.2;
  9532. this._physicImpostor = impostor;
  9533. this._physicsMass = options.mass;
  9534. this._physicsFriction = options.friction;
  9535. this._physicRestitution = options.restitution;
  9536. return physicsEngine._registerMesh(this, impostor, options);
  9537. };
  9538. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9539. if (!this._physicImpostor) {
  9540. return BABYLON.PhysicsEngine.NoImpostor;
  9541. }
  9542. return this._physicImpostor;
  9543. };
  9544. AbstractMesh.prototype.getPhysicsMass = function () {
  9545. if (!this._physicsMass) {
  9546. return 0;
  9547. }
  9548. return this._physicsMass;
  9549. };
  9550. AbstractMesh.prototype.getPhysicsFriction = function () {
  9551. if (!this._physicsFriction) {
  9552. return 0;
  9553. }
  9554. return this._physicsFriction;
  9555. };
  9556. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9557. if (!this._physicRestitution) {
  9558. return 0;
  9559. }
  9560. return this._physicRestitution;
  9561. };
  9562. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9563. if (!camera) {
  9564. camera = this.getScene().activeCamera;
  9565. }
  9566. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9567. };
  9568. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9569. if (!camera) {
  9570. camera = this.getScene().activeCamera;
  9571. }
  9572. return this.absolutePosition.subtract(camera.position).length();
  9573. };
  9574. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9575. if (!this._physicImpostor) {
  9576. return;
  9577. }
  9578. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9579. };
  9580. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9581. if (!this._physicImpostor) {
  9582. return;
  9583. }
  9584. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9585. };
  9586. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9587. if (!this._physicImpostor) {
  9588. return;
  9589. }
  9590. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9591. };
  9592. // Collisions
  9593. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9594. var globalPosition = this.getAbsolutePosition();
  9595. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9596. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9597. this._collider.radius = this.ellipsoid;
  9598. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  9599. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  9600. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9601. this.position.addInPlace(this._diffPositionForCollisions);
  9602. }
  9603. };
  9604. // Submeshes octree
  9605. /**
  9606. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9607. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9608. */
  9609. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9610. if (maxCapacity === void 0) { maxCapacity = 64; }
  9611. if (maxDepth === void 0) { maxDepth = 2; }
  9612. if (!this._submeshesOctree) {
  9613. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9614. }
  9615. this.computeWorldMatrix(true);
  9616. // Update octree
  9617. var bbox = this.getBoundingInfo().boundingBox;
  9618. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9619. return this._submeshesOctree;
  9620. };
  9621. // Collisions
  9622. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9623. this._generatePointsArray();
  9624. // Transformation
  9625. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9626. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9627. subMesh._lastColliderWorldVertices = [];
  9628. subMesh._trianglePlanes = [];
  9629. var start = subMesh.verticesStart;
  9630. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9631. for (var i = start; i < end; i++) {
  9632. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9633. }
  9634. }
  9635. // Collide
  9636. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  9637. };
  9638. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9639. var subMeshes;
  9640. var len;
  9641. // Octrees
  9642. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9643. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9644. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9645. len = intersections.length;
  9646. subMeshes = intersections.data;
  9647. }
  9648. else {
  9649. subMeshes = this.subMeshes;
  9650. len = subMeshes.length;
  9651. }
  9652. for (var index = 0; index < len; index++) {
  9653. var subMesh = subMeshes[index];
  9654. // Bounding test
  9655. if (len > 1 && !subMesh._checkCollision(collider))
  9656. continue;
  9657. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9658. }
  9659. };
  9660. AbstractMesh.prototype._checkCollision = function (collider) {
  9661. // Bounding box test
  9662. if (!this._boundingInfo._checkCollision(collider))
  9663. return;
  9664. // Transformation matrix
  9665. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9666. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9667. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9668. };
  9669. // Picking
  9670. AbstractMesh.prototype._generatePointsArray = function () {
  9671. return false;
  9672. };
  9673. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9674. var pickingInfo = new BABYLON.PickingInfo();
  9675. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9676. return pickingInfo;
  9677. }
  9678. if (!this._generatePointsArray()) {
  9679. return pickingInfo;
  9680. }
  9681. var intersectInfo = null;
  9682. // Octrees
  9683. var subMeshes;
  9684. var len;
  9685. if (this._submeshesOctree && this.useOctreeForPicking) {
  9686. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9687. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9688. len = intersections.length;
  9689. subMeshes = intersections.data;
  9690. }
  9691. else {
  9692. subMeshes = this.subMeshes;
  9693. len = subMeshes.length;
  9694. }
  9695. for (var index = 0; index < len; index++) {
  9696. var subMesh = subMeshes[index];
  9697. // Bounding test
  9698. if (len > 1 && !subMesh.canIntersects(ray))
  9699. continue;
  9700. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9701. if (currentIntersectInfo) {
  9702. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9703. intersectInfo = currentIntersectInfo;
  9704. if (fastCheck) {
  9705. break;
  9706. }
  9707. }
  9708. }
  9709. }
  9710. if (intersectInfo) {
  9711. // Get picked point
  9712. var world = this.getWorldMatrix();
  9713. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9714. var direction = ray.direction.clone();
  9715. direction = direction.scale(intersectInfo.distance);
  9716. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9717. var pickedPoint = worldOrigin.add(worldDirection);
  9718. // Return result
  9719. pickingInfo.hit = true;
  9720. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9721. pickingInfo.pickedPoint = pickedPoint;
  9722. pickingInfo.pickedMesh = this;
  9723. pickingInfo.bu = intersectInfo.bu;
  9724. pickingInfo.bv = intersectInfo.bv;
  9725. pickingInfo.faceId = intersectInfo.faceId;
  9726. return pickingInfo;
  9727. }
  9728. return pickingInfo;
  9729. };
  9730. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9731. return null;
  9732. };
  9733. AbstractMesh.prototype.releaseSubMeshes = function () {
  9734. if (this.subMeshes) {
  9735. while (this.subMeshes.length) {
  9736. this.subMeshes[0].dispose();
  9737. }
  9738. }
  9739. else {
  9740. this.subMeshes = new Array();
  9741. }
  9742. };
  9743. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9744. // Physics
  9745. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9746. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9747. }
  9748. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9749. var other = this._intersectionsInProgress[index];
  9750. var pos = other._intersectionsInProgress.indexOf(this);
  9751. other._intersectionsInProgress.splice(pos, 1);
  9752. }
  9753. this._intersectionsInProgress = [];
  9754. // SubMeshes
  9755. this.releaseSubMeshes();
  9756. // Remove from scene
  9757. var index = this.getScene().meshes.indexOf(this);
  9758. if (index != -1) {
  9759. // Remove from the scene if mesh found
  9760. this.getScene().meshes.splice(index, 1);
  9761. }
  9762. if (!doNotRecurse) {
  9763. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9764. if (this.getScene().particleSystems[index].emitter == this) {
  9765. this.getScene().particleSystems[index].dispose();
  9766. index--;
  9767. }
  9768. }
  9769. // Children
  9770. var objects = this.getScene().meshes.slice(0);
  9771. for (index = 0; index < objects.length; index++) {
  9772. if (objects[index].parent == this) {
  9773. objects[index].dispose();
  9774. }
  9775. }
  9776. }
  9777. else {
  9778. for (index = 0; index < this.getScene().meshes.length; index++) {
  9779. var obj = this.getScene().meshes[index];
  9780. if (obj.parent === this) {
  9781. obj.parent = null;
  9782. obj.computeWorldMatrix(true);
  9783. }
  9784. }
  9785. }
  9786. this._onAfterWorldMatrixUpdate = [];
  9787. this._isDisposed = true;
  9788. // Callback
  9789. if (this.onDispose) {
  9790. this.onDispose();
  9791. }
  9792. };
  9793. // Statics
  9794. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9795. AbstractMesh._BILLBOARDMODE_X = 1;
  9796. AbstractMesh._BILLBOARDMODE_Y = 2;
  9797. AbstractMesh._BILLBOARDMODE_Z = 4;
  9798. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9799. return AbstractMesh;
  9800. })(BABYLON.Node);
  9801. BABYLON.AbstractMesh = AbstractMesh;
  9802. })(BABYLON || (BABYLON = {}));
  9803. //# sourceMappingURL=babylon.abstractMesh.js.map
  9804. var BABYLON;
  9805. (function (BABYLON) {
  9806. var _InstancesBatch = (function () {
  9807. function _InstancesBatch() {
  9808. this.mustReturn = false;
  9809. this.visibleInstances = new Array();
  9810. this.renderSelf = new Array();
  9811. }
  9812. return _InstancesBatch;
  9813. })();
  9814. BABYLON._InstancesBatch = _InstancesBatch;
  9815. var Mesh = (function (_super) {
  9816. __extends(Mesh, _super);
  9817. /**
  9818. * @constructor
  9819. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9820. * @param {Scene} scene - The scene to add this mesh to.
  9821. * @param {Node} parent - The parent of this mesh, if it has one
  9822. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9823. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9824. * When false, achieved by calling a clone(), also passing False.
  9825. * This will make creation of children, recursive.
  9826. */
  9827. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9828. if (parent === void 0) { parent = null; }
  9829. _super.call(this, name, scene);
  9830. // Members
  9831. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9832. this.instances = new Array();
  9833. this._LODLevels = new Array();
  9834. this._onBeforeRenderCallbacks = new Array();
  9835. this._onAfterRenderCallbacks = new Array();
  9836. this._visibleInstances = {};
  9837. this._renderIdForInstances = new Array();
  9838. this._batchCache = new _InstancesBatch();
  9839. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  9840. if (source) {
  9841. // Geometry
  9842. if (source._geometry) {
  9843. source._geometry.applyToMesh(this);
  9844. }
  9845. // Deep copy
  9846. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9847. // Material
  9848. this.material = source.material;
  9849. if (!doNotCloneChildren) {
  9850. for (var index = 0; index < scene.meshes.length; index++) {
  9851. var mesh = scene.meshes[index];
  9852. if (mesh.parent === source) {
  9853. // doNotCloneChildren is always going to be False
  9854. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  9855. }
  9856. }
  9857. }
  9858. for (index = 0; index < scene.particleSystems.length; index++) {
  9859. var system = scene.particleSystems[index];
  9860. if (system.emitter === source) {
  9861. system.clone(system.name, this);
  9862. }
  9863. }
  9864. this.computeWorldMatrix(true);
  9865. }
  9866. // Parent
  9867. if (parent !== null) {
  9868. this.parent = parent;
  9869. }
  9870. }
  9871. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  9872. // Methods
  9873. get: function () {
  9874. return this._LODLevels.length > 0;
  9875. },
  9876. enumerable: true,
  9877. configurable: true
  9878. });
  9879. Mesh.prototype._sortLODLevels = function () {
  9880. this._LODLevels.sort(function (a, b) {
  9881. if (a.distance < b.distance) {
  9882. return 1;
  9883. }
  9884. if (a.distance > b.distance) {
  9885. return -1;
  9886. }
  9887. return 0;
  9888. });
  9889. };
  9890. /**
  9891. * Add a mesh as LOD level triggered at the given distance.
  9892. * @param {number} distance - the distance from the center of the object to show this level
  9893. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  9894. * @return {BABYLON.Mesh} this mesh (for chaining)
  9895. */
  9896. Mesh.prototype.addLODLevel = function (distance, mesh) {
  9897. if (mesh && mesh._masterMesh) {
  9898. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  9899. return this;
  9900. }
  9901. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  9902. this._LODLevels.push(level);
  9903. if (mesh) {
  9904. mesh._masterMesh = this;
  9905. }
  9906. this._sortLODLevels();
  9907. return this;
  9908. };
  9909. /**
  9910. * Remove a mesh from the LOD array
  9911. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  9912. * @return {BABYLON.Mesh} this mesh (for chaining)
  9913. */
  9914. Mesh.prototype.removeLODLevel = function (mesh) {
  9915. for (var index = 0; index < this._LODLevels.length; index++) {
  9916. if (this._LODLevels[index].mesh === mesh) {
  9917. this._LODLevels.splice(index, 1);
  9918. if (mesh) {
  9919. mesh._masterMesh = null;
  9920. }
  9921. }
  9922. }
  9923. this._sortLODLevels();
  9924. return this;
  9925. };
  9926. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9927. if (!this._LODLevels || this._LODLevels.length === 0) {
  9928. return this;
  9929. }
  9930. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  9931. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  9932. return this;
  9933. }
  9934. for (var index = 0; index < this._LODLevels.length; index++) {
  9935. var level = this._LODLevels[index];
  9936. if (level.distance < distanceToCamera) {
  9937. if (level.mesh) {
  9938. level.mesh._preActivate();
  9939. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9940. }
  9941. return level.mesh;
  9942. }
  9943. }
  9944. return this;
  9945. };
  9946. Object.defineProperty(Mesh.prototype, "geometry", {
  9947. get: function () {
  9948. return this._geometry;
  9949. },
  9950. enumerable: true,
  9951. configurable: true
  9952. });
  9953. Mesh.prototype.getTotalVertices = function () {
  9954. if (!this._geometry) {
  9955. return 0;
  9956. }
  9957. return this._geometry.getTotalVertices();
  9958. };
  9959. Mesh.prototype.getVerticesData = function (kind) {
  9960. if (!this._geometry) {
  9961. return null;
  9962. }
  9963. return this._geometry.getVerticesData(kind);
  9964. };
  9965. Mesh.prototype.getVertexBuffer = function (kind) {
  9966. if (!this._geometry) {
  9967. return undefined;
  9968. }
  9969. return this._geometry.getVertexBuffer(kind);
  9970. };
  9971. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9972. if (!this._geometry) {
  9973. if (this._delayInfo) {
  9974. return this._delayInfo.indexOf(kind) !== -1;
  9975. }
  9976. return false;
  9977. }
  9978. return this._geometry.isVerticesDataPresent(kind);
  9979. };
  9980. Mesh.prototype.getVerticesDataKinds = function () {
  9981. if (!this._geometry) {
  9982. var result = [];
  9983. if (this._delayInfo) {
  9984. for (var kind in this._delayInfo) {
  9985. result.push(kind);
  9986. }
  9987. }
  9988. return result;
  9989. }
  9990. return this._geometry.getVerticesDataKinds();
  9991. };
  9992. Mesh.prototype.getTotalIndices = function () {
  9993. if (!this._geometry) {
  9994. return 0;
  9995. }
  9996. return this._geometry.getTotalIndices();
  9997. };
  9998. Mesh.prototype.getIndices = function () {
  9999. if (!this._geometry) {
  10000. return [];
  10001. }
  10002. return this._geometry.getIndices();
  10003. };
  10004. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10005. get: function () {
  10006. return this._masterMesh !== null && this._masterMesh !== undefined;
  10007. },
  10008. enumerable: true,
  10009. configurable: true
  10010. });
  10011. Mesh.prototype.isReady = function () {
  10012. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10013. return false;
  10014. }
  10015. return _super.prototype.isReady.call(this);
  10016. };
  10017. Mesh.prototype.isDisposed = function () {
  10018. return this._isDisposed;
  10019. };
  10020. // Methods
  10021. Mesh.prototype._preActivate = function () {
  10022. var sceneRenderId = this.getScene().getRenderId();
  10023. if (this._preActivateId == sceneRenderId) {
  10024. return;
  10025. }
  10026. this._preActivateId = sceneRenderId;
  10027. this._visibleInstances = null;
  10028. };
  10029. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10030. if (!this._visibleInstances) {
  10031. this._visibleInstances = {};
  10032. this._visibleInstances.defaultRenderId = renderId;
  10033. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10034. }
  10035. if (!this._visibleInstances[renderId]) {
  10036. this._visibleInstances[renderId] = new Array();
  10037. }
  10038. this._visibleInstances[renderId].push(instance);
  10039. };
  10040. Mesh.prototype.refreshBoundingInfo = function () {
  10041. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10042. if (data) {
  10043. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10044. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10045. }
  10046. if (this.subMeshes) {
  10047. for (var index = 0; index < this.subMeshes.length; index++) {
  10048. this.subMeshes[index].refreshBoundingInfo();
  10049. }
  10050. }
  10051. this._updateBoundingInfo();
  10052. };
  10053. Mesh.prototype._createGlobalSubMesh = function () {
  10054. var totalVertices = this.getTotalVertices();
  10055. if (!totalVertices || !this.getIndices()) {
  10056. return null;
  10057. }
  10058. this.releaseSubMeshes();
  10059. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10060. };
  10061. Mesh.prototype.subdivide = function (count) {
  10062. if (count < 1) {
  10063. return;
  10064. }
  10065. var totalIndices = this.getTotalIndices();
  10066. var subdivisionSize = (totalIndices / count) | 0;
  10067. var offset = 0;
  10068. while (subdivisionSize % 3 != 0) {
  10069. subdivisionSize++;
  10070. }
  10071. this.releaseSubMeshes();
  10072. for (var index = 0; index < count; index++) {
  10073. if (offset >= totalIndices) {
  10074. break;
  10075. }
  10076. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10077. offset += subdivisionSize;
  10078. }
  10079. this.synchronizeInstances();
  10080. };
  10081. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10082. if (kind instanceof Array) {
  10083. var temp = data;
  10084. data = kind;
  10085. kind = temp;
  10086. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10087. }
  10088. if (!this._geometry) {
  10089. var vertexData = new BABYLON.VertexData();
  10090. vertexData.set(data, kind);
  10091. var scene = this.getScene();
  10092. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10093. }
  10094. else {
  10095. this._geometry.setVerticesData(kind, data, updatable, stride);
  10096. }
  10097. };
  10098. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10099. if (!this._geometry) {
  10100. return;
  10101. }
  10102. if (!makeItUnique) {
  10103. this._geometry.updateVerticesData(kind, data, updateExtends);
  10104. }
  10105. else {
  10106. this.makeGeometryUnique();
  10107. this.updateVerticesData(kind, data, updateExtends, false);
  10108. }
  10109. };
  10110. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10111. if (!this._geometry) {
  10112. return;
  10113. }
  10114. if (!makeItUnique) {
  10115. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10116. }
  10117. else {
  10118. this.makeGeometryUnique();
  10119. this.updateVerticesDataDirectly(kind, data, offset, false);
  10120. }
  10121. };
  10122. Mesh.prototype.makeGeometryUnique = function () {
  10123. if (!this._geometry) {
  10124. return;
  10125. }
  10126. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10127. geometry.applyToMesh(this);
  10128. };
  10129. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10130. if (!this._geometry) {
  10131. var vertexData = new BABYLON.VertexData();
  10132. vertexData.indices = indices;
  10133. var scene = this.getScene();
  10134. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10135. }
  10136. else {
  10137. this._geometry.setIndices(indices, totalVertices);
  10138. }
  10139. };
  10140. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10141. var engine = this.getScene().getEngine();
  10142. // Wireframe
  10143. var indexToBind;
  10144. switch (fillMode) {
  10145. case BABYLON.Material.PointFillMode:
  10146. indexToBind = null;
  10147. break;
  10148. case BABYLON.Material.WireFrameFillMode:
  10149. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10150. break;
  10151. default:
  10152. case BABYLON.Material.TriangleFillMode:
  10153. indexToBind = this._geometry.getIndexBuffer();
  10154. break;
  10155. }
  10156. // VBOs
  10157. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10158. };
  10159. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10160. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10161. return;
  10162. }
  10163. var engine = this.getScene().getEngine();
  10164. switch (fillMode) {
  10165. case BABYLON.Material.PointFillMode:
  10166. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10167. break;
  10168. case BABYLON.Material.WireFrameFillMode:
  10169. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10170. break;
  10171. default:
  10172. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10173. }
  10174. };
  10175. Mesh.prototype.registerBeforeRender = function (func) {
  10176. this._onBeforeRenderCallbacks.push(func);
  10177. };
  10178. Mesh.prototype.unregisterBeforeRender = function (func) {
  10179. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10180. if (index > -1) {
  10181. this._onBeforeRenderCallbacks.splice(index, 1);
  10182. }
  10183. };
  10184. Mesh.prototype.registerAfterRender = function (func) {
  10185. this._onAfterRenderCallbacks.push(func);
  10186. };
  10187. Mesh.prototype.unregisterAfterRender = function (func) {
  10188. var index = this._onAfterRenderCallbacks.indexOf(func);
  10189. if (index > -1) {
  10190. this._onAfterRenderCallbacks.splice(index, 1);
  10191. }
  10192. };
  10193. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10194. var scene = this.getScene();
  10195. this._batchCache.mustReturn = false;
  10196. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10197. this._batchCache.visibleInstances[subMeshId] = null;
  10198. if (this._visibleInstances) {
  10199. var currentRenderId = scene.getRenderId();
  10200. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10201. var selfRenderId = this._renderId;
  10202. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10203. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10204. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10205. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10206. }
  10207. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10208. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10209. this._batchCache.mustReturn = true;
  10210. return this._batchCache;
  10211. }
  10212. if (currentRenderId !== selfRenderId) {
  10213. this._batchCache.renderSelf[subMeshId] = false;
  10214. }
  10215. }
  10216. this._renderIdForInstances[subMeshId] = currentRenderId;
  10217. }
  10218. return this._batchCache;
  10219. };
  10220. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10221. var visibleInstances = batch.visibleInstances[subMesh._id];
  10222. var matricesCount = visibleInstances.length + 1;
  10223. var bufferSize = matricesCount * 16 * 4;
  10224. while (this._instancesBufferSize < bufferSize) {
  10225. this._instancesBufferSize *= 2;
  10226. }
  10227. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10228. if (this._worldMatricesInstancesBuffer) {
  10229. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10230. }
  10231. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10232. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10233. }
  10234. var offset = 0;
  10235. var instancesCount = 0;
  10236. var world = this.getWorldMatrix();
  10237. if (batch.renderSelf[subMesh._id]) {
  10238. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10239. offset += 16;
  10240. instancesCount++;
  10241. }
  10242. if (visibleInstances) {
  10243. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10244. var instance = visibleInstances[instanceIndex];
  10245. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10246. offset += 16;
  10247. instancesCount++;
  10248. }
  10249. }
  10250. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10251. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10252. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10253. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10254. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10255. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10256. this._draw(subMesh, fillMode, instancesCount);
  10257. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10258. };
  10259. Mesh.prototype.render = function (subMesh) {
  10260. var scene = this.getScene();
  10261. // Managing instances
  10262. var batch = this._getInstancesRenderList(subMesh._id);
  10263. if (batch.mustReturn) {
  10264. return;
  10265. }
  10266. // Checking geometry state
  10267. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10268. return;
  10269. }
  10270. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10271. this._onBeforeRenderCallbacks[callbackIndex]();
  10272. }
  10273. var engine = scene.getEngine();
  10274. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10275. // Material
  10276. var effectiveMaterial = subMesh.getMaterial();
  10277. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10278. return;
  10279. }
  10280. // Outline - step 1
  10281. var savedDepthWrite = engine.getDepthWrite();
  10282. if (this.renderOutline) {
  10283. engine.setDepthWrite(false);
  10284. scene.getOutlineRenderer().render(subMesh, batch);
  10285. engine.setDepthWrite(savedDepthWrite);
  10286. }
  10287. effectiveMaterial._preBind();
  10288. var effect = effectiveMaterial.getEffect();
  10289. // Bind
  10290. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10291. this._bind(subMesh, effect, fillMode);
  10292. var world = this.getWorldMatrix();
  10293. effectiveMaterial.bind(world, this);
  10294. // Instances rendering
  10295. if (hardwareInstancedRendering) {
  10296. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10297. }
  10298. else {
  10299. if (batch.renderSelf[subMesh._id]) {
  10300. // Draw
  10301. this._draw(subMesh, fillMode);
  10302. }
  10303. if (batch.visibleInstances[subMesh._id]) {
  10304. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10305. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10306. // World
  10307. world = instance.getWorldMatrix();
  10308. effectiveMaterial.bindOnlyWorldMatrix(world);
  10309. // Draw
  10310. this._draw(subMesh, fillMode);
  10311. }
  10312. }
  10313. }
  10314. // Unbind
  10315. effectiveMaterial.unbind();
  10316. // Outline - step 2
  10317. if (this.renderOutline && savedDepthWrite) {
  10318. engine.setDepthWrite(true);
  10319. engine.setColorWrite(false);
  10320. scene.getOutlineRenderer().render(subMesh, batch);
  10321. engine.setColorWrite(true);
  10322. }
  10323. // Overlay
  10324. if (this.renderOverlay) {
  10325. var currentMode = engine.getAlphaMode();
  10326. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10327. scene.getOutlineRenderer().render(subMesh, batch, true);
  10328. engine.setAlphaMode(currentMode);
  10329. }
  10330. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10331. this._onAfterRenderCallbacks[callbackIndex]();
  10332. }
  10333. };
  10334. Mesh.prototype.getEmittedParticleSystems = function () {
  10335. var results = new Array();
  10336. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10337. var particleSystem = this.getScene().particleSystems[index];
  10338. if (particleSystem.emitter === this) {
  10339. results.push(particleSystem);
  10340. }
  10341. }
  10342. return results;
  10343. };
  10344. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10345. var results = new Array();
  10346. var descendants = this.getDescendants();
  10347. descendants.push(this);
  10348. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10349. var particleSystem = this.getScene().particleSystems[index];
  10350. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10351. results.push(particleSystem);
  10352. }
  10353. }
  10354. return results;
  10355. };
  10356. Mesh.prototype.getChildren = function () {
  10357. var results = [];
  10358. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10359. var mesh = this.getScene().meshes[index];
  10360. if (mesh.parent == this) {
  10361. results.push(mesh);
  10362. }
  10363. }
  10364. return results;
  10365. };
  10366. Mesh.prototype._checkDelayState = function () {
  10367. var _this = this;
  10368. var that = this;
  10369. var scene = this.getScene();
  10370. if (this._geometry) {
  10371. this._geometry.load(scene);
  10372. }
  10373. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10374. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10375. scene._addPendingData(that);
  10376. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  10377. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  10378. if (data instanceof ArrayBuffer) {
  10379. _this._delayLoadingFunction(data, _this);
  10380. }
  10381. else {
  10382. _this._delayLoadingFunction(JSON.parse(data), _this);
  10383. }
  10384. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10385. scene._removePendingData(_this);
  10386. }, function () {
  10387. }, scene.database, getBinaryData);
  10388. }
  10389. };
  10390. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  10391. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10392. return false;
  10393. }
  10394. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  10395. return false;
  10396. }
  10397. this._checkDelayState();
  10398. return true;
  10399. };
  10400. Mesh.prototype.setMaterialByID = function (id) {
  10401. var materials = this.getScene().materials;
  10402. for (var index = 0; index < materials.length; index++) {
  10403. if (materials[index].id == id) {
  10404. this.material = materials[index];
  10405. return;
  10406. }
  10407. }
  10408. // Multi
  10409. var multiMaterials = this.getScene().multiMaterials;
  10410. for (index = 0; index < multiMaterials.length; index++) {
  10411. if (multiMaterials[index].id == id) {
  10412. this.material = multiMaterials[index];
  10413. return;
  10414. }
  10415. }
  10416. };
  10417. Mesh.prototype.getAnimatables = function () {
  10418. var results = [];
  10419. if (this.material) {
  10420. results.push(this.material);
  10421. }
  10422. if (this.skeleton) {
  10423. results.push(this.skeleton);
  10424. }
  10425. return results;
  10426. };
  10427. // Geometry
  10428. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  10429. // Position
  10430. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  10431. return;
  10432. }
  10433. this._resetPointsArrayCache();
  10434. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10435. var temp = [];
  10436. for (var index = 0; index < data.length; index += 3) {
  10437. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10438. }
  10439. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  10440. // Normals
  10441. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  10442. return;
  10443. }
  10444. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10445. for (index = 0; index < data.length; index += 3) {
  10446. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10447. }
  10448. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  10449. };
  10450. // Cache
  10451. Mesh.prototype._resetPointsArrayCache = function () {
  10452. this._positions = null;
  10453. };
  10454. Mesh.prototype._generatePointsArray = function () {
  10455. if (this._positions)
  10456. return true;
  10457. this._positions = [];
  10458. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10459. if (!data) {
  10460. return false;
  10461. }
  10462. for (var index = 0; index < data.length; index += 3) {
  10463. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  10464. }
  10465. return true;
  10466. };
  10467. // Clone
  10468. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10469. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  10470. };
  10471. // Dispose
  10472. Mesh.prototype.dispose = function (doNotRecurse) {
  10473. if (this._geometry) {
  10474. this._geometry.releaseForMesh(this, true);
  10475. }
  10476. // Instances
  10477. if (this._worldMatricesInstancesBuffer) {
  10478. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10479. this._worldMatricesInstancesBuffer = null;
  10480. }
  10481. while (this.instances.length) {
  10482. this.instances[0].dispose();
  10483. }
  10484. _super.prototype.dispose.call(this, doNotRecurse);
  10485. };
  10486. // Geometric tools
  10487. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  10488. var _this = this;
  10489. var scene = this.getScene();
  10490. var onload = function (img) {
  10491. // Getting height map data
  10492. var canvas = document.createElement("canvas");
  10493. var context = canvas.getContext("2d");
  10494. var heightMapWidth = img.width;
  10495. var heightMapHeight = img.height;
  10496. canvas.width = heightMapWidth;
  10497. canvas.height = heightMapHeight;
  10498. context.drawImage(img, 0, 0);
  10499. // Create VertexData from map data
  10500. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10501. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  10502. //execute success callback, if set
  10503. if (onSuccess) {
  10504. onSuccess(_this);
  10505. }
  10506. };
  10507. BABYLON.Tools.LoadImage(url, onload, function () {
  10508. }, scene.database);
  10509. };
  10510. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  10511. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10512. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  10513. return;
  10514. }
  10515. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10516. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10517. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  10518. var position = BABYLON.Vector3.Zero();
  10519. var normal = BABYLON.Vector3.Zero();
  10520. var uv = BABYLON.Vector2.Zero();
  10521. for (var index = 0; index < positions.length; index += 3) {
  10522. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  10523. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  10524. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  10525. // Compute height
  10526. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  10527. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  10528. var pos = (u + v * heightMapWidth) * 4;
  10529. var r = buffer[pos] / 255.0;
  10530. var g = buffer[pos + 1] / 255.0;
  10531. var b = buffer[pos + 2] / 255.0;
  10532. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  10533. normal.normalize();
  10534. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  10535. position = position.add(normal);
  10536. position.toArray(positions, index);
  10537. }
  10538. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  10539. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  10540. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  10541. };
  10542. Mesh.prototype.convertToFlatShadedMesh = function () {
  10543. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  10544. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  10545. var kinds = this.getVerticesDataKinds();
  10546. var vbs = [];
  10547. var data = [];
  10548. var newdata = [];
  10549. var updatableNormals = false;
  10550. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10551. var kind = kinds[kindIndex];
  10552. var vertexBuffer = this.getVertexBuffer(kind);
  10553. if (kind === BABYLON.VertexBuffer.NormalKind) {
  10554. updatableNormals = vertexBuffer.isUpdatable();
  10555. kinds.splice(kindIndex, 1);
  10556. kindIndex--;
  10557. continue;
  10558. }
  10559. vbs[kind] = vertexBuffer;
  10560. data[kind] = vbs[kind].getData();
  10561. newdata[kind] = [];
  10562. }
  10563. // Save previous submeshes
  10564. var previousSubmeshes = this.subMeshes.slice(0);
  10565. var indices = this.getIndices();
  10566. var totalIndices = this.getTotalIndices();
  10567. for (var index = 0; index < totalIndices; index++) {
  10568. var vertexIndex = indices[index];
  10569. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10570. kind = kinds[kindIndex];
  10571. var stride = vbs[kind].getStrideSize();
  10572. for (var offset = 0; offset < stride; offset++) {
  10573. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  10574. }
  10575. }
  10576. }
  10577. // Updating faces & normal
  10578. var normals = [];
  10579. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  10580. for (index = 0; index < totalIndices; index += 3) {
  10581. indices[index] = index;
  10582. indices[index + 1] = index + 1;
  10583. indices[index + 2] = index + 2;
  10584. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  10585. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  10586. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  10587. var p1p2 = p1.subtract(p2);
  10588. var p3p2 = p3.subtract(p2);
  10589. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  10590. for (var localIndex = 0; localIndex < 3; localIndex++) {
  10591. normals.push(normal.x);
  10592. normals.push(normal.y);
  10593. normals.push(normal.z);
  10594. }
  10595. }
  10596. this.setIndices(indices);
  10597. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  10598. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10599. kind = kinds[kindIndex];
  10600. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  10601. }
  10602. // Updating submeshes
  10603. this.releaseSubMeshes();
  10604. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  10605. var previousOne = previousSubmeshes[submeshIndex];
  10606. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  10607. }
  10608. this.synchronizeInstances();
  10609. };
  10610. // Instances
  10611. Mesh.prototype.createInstance = function (name) {
  10612. return new BABYLON.InstancedMesh(name, this);
  10613. };
  10614. Mesh.prototype.synchronizeInstances = function () {
  10615. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  10616. var instance = this.instances[instanceIndex];
  10617. instance._syncSubMeshes();
  10618. }
  10619. };
  10620. /**
  10621. * Simplify the mesh according to the given array of settings.
  10622. * Function will return immediately and will simplify async.
  10623. * @param settings a collection of simplification settings.
  10624. * @param parallelProcessing should all levels calculate parallel or one after the other.
  10625. * @param type the type of simplification to run.
  10626. * successCallback optional success callback to be called after the simplification finished processing all settings.
  10627. */
  10628. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  10629. var _this = this;
  10630. if (parallelProcessing === void 0) { parallelProcessing = true; }
  10631. if (type === void 0) { type = 0 /* QUADRATIC */; }
  10632. var getSimplifier = function () {
  10633. switch (type) {
  10634. case 0 /* QUADRATIC */:
  10635. default:
  10636. return new BABYLON.QuadraticErrorSimplification(_this);
  10637. }
  10638. };
  10639. if (parallelProcessing) {
  10640. //parallel simplifier
  10641. settings.forEach(function (setting) {
  10642. var simplifier = getSimplifier();
  10643. simplifier.simplify(setting, function (newMesh) {
  10644. _this.addLODLevel(setting.distance, newMesh);
  10645. //check if it is the last
  10646. if (setting.quality == settings[settings.length - 1].quality && successCallback) {
  10647. //all done, run the success callback.
  10648. successCallback();
  10649. }
  10650. });
  10651. });
  10652. }
  10653. else {
  10654. //single simplifier.
  10655. var simplifier = getSimplifier();
  10656. var runDecimation = function (setting, callback) {
  10657. simplifier.simplify(setting, function (newMesh) {
  10658. _this.addLODLevel(setting.distance, newMesh);
  10659. //run the next quality level
  10660. callback();
  10661. });
  10662. };
  10663. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  10664. runDecimation(settings[loop.index], function () {
  10665. loop.executeNext();
  10666. });
  10667. }, function () {
  10668. //execution ended, run the success callback.
  10669. if (successCallback) {
  10670. successCallback();
  10671. }
  10672. });
  10673. }
  10674. };
  10675. // Statics
  10676. Mesh.CreateBox = function (name, size, scene, updatable) {
  10677. var box = new Mesh(name, scene);
  10678. var vertexData = BABYLON.VertexData.CreateBox(size);
  10679. vertexData.applyToMesh(box, updatable);
  10680. return box;
  10681. };
  10682. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  10683. var sphere = new Mesh(name, scene);
  10684. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  10685. vertexData.applyToMesh(sphere, updatable);
  10686. return sphere;
  10687. };
  10688. // Cylinder and cone (Code inspired by SharpDX.org)
  10689. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  10690. // subdivisions is a new parameter, we need to support old signature
  10691. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  10692. if (scene !== undefined) {
  10693. updatable = scene;
  10694. }
  10695. scene = subdivisions;
  10696. subdivisions = 1;
  10697. }
  10698. var cylinder = new Mesh(name, scene);
  10699. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  10700. vertexData.applyToMesh(cylinder, updatable);
  10701. return cylinder;
  10702. };
  10703. // Torus (Code from SharpDX.org)
  10704. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  10705. var torus = new Mesh(name, scene);
  10706. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  10707. vertexData.applyToMesh(torus, updatable);
  10708. return torus;
  10709. };
  10710. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  10711. var torusKnot = new Mesh(name, scene);
  10712. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  10713. vertexData.applyToMesh(torusKnot, updatable);
  10714. return torusKnot;
  10715. };
  10716. // Lines
  10717. Mesh.CreateLines = function (name, points, scene, updatable) {
  10718. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  10719. var vertexData = BABYLON.VertexData.CreateLines(points);
  10720. vertexData.applyToMesh(lines, updatable);
  10721. return lines;
  10722. };
  10723. // Plane & ground
  10724. Mesh.CreatePlane = function (name, size, scene, updatable) {
  10725. var plane = new Mesh(name, scene);
  10726. var vertexData = BABYLON.VertexData.CreatePlane(size);
  10727. vertexData.applyToMesh(plane, updatable);
  10728. return plane;
  10729. };
  10730. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10731. var ground = new BABYLON.GroundMesh(name, scene);
  10732. ground._setReady(false);
  10733. ground._subdivisions = subdivisions;
  10734. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10735. vertexData.applyToMesh(ground, updatable);
  10736. ground._setReady(true);
  10737. return ground;
  10738. };
  10739. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10740. var tiledGround = new Mesh(name, scene);
  10741. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10742. vertexData.applyToMesh(tiledGround, updatable);
  10743. return tiledGround;
  10744. };
  10745. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  10746. var ground = new BABYLON.GroundMesh(name, scene);
  10747. ground._subdivisions = subdivisions;
  10748. ground._setReady(false);
  10749. var onload = function (img) {
  10750. // Getting height map data
  10751. var canvas = document.createElement("canvas");
  10752. var context = canvas.getContext("2d");
  10753. var heightMapWidth = img.width;
  10754. var heightMapHeight = img.height;
  10755. canvas.width = heightMapWidth;
  10756. canvas.height = heightMapHeight;
  10757. context.drawImage(img, 0, 0);
  10758. // Create VertexData from map data
  10759. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10760. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10761. vertexData.applyToMesh(ground, updatable);
  10762. ground._setReady(true);
  10763. //execute ready callback, if set
  10764. if (onReady) {
  10765. onReady(ground);
  10766. }
  10767. };
  10768. BABYLON.Tools.LoadImage(url, onload, function () {
  10769. }, scene.database);
  10770. return ground;
  10771. };
  10772. // Tools
  10773. Mesh.MinMax = function (meshes) {
  10774. var minVector = null;
  10775. var maxVector = null;
  10776. for (var i in meshes) {
  10777. var mesh = meshes[i];
  10778. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10779. if (!minVector) {
  10780. minVector = boundingBox.minimumWorld;
  10781. maxVector = boundingBox.maximumWorld;
  10782. continue;
  10783. }
  10784. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10785. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10786. }
  10787. return {
  10788. min: minVector,
  10789. max: maxVector
  10790. };
  10791. };
  10792. Mesh.Center = function (meshesOrMinMaxVector) {
  10793. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  10794. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10795. };
  10796. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10797. if (disposeSource === void 0) { disposeSource = true; }
  10798. var source = meshes[0];
  10799. var material = source.material;
  10800. var scene = source.getScene();
  10801. if (!allow32BitsIndices) {
  10802. var totalVertices = 0;
  10803. for (var index = 0; index < meshes.length; index++) {
  10804. totalVertices += meshes[index].getTotalVertices();
  10805. if (totalVertices > 65536) {
  10806. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  10807. return null;
  10808. }
  10809. }
  10810. }
  10811. // Merge
  10812. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  10813. vertexData.transform(source.getWorldMatrix());
  10814. for (index = 1; index < meshes.length; index++) {
  10815. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  10816. otherVertexData.transform(meshes[index].getWorldMatrix());
  10817. vertexData.merge(otherVertexData);
  10818. }
  10819. var newMesh = new Mesh(source.name + "_merged", scene);
  10820. vertexData.applyToMesh(newMesh);
  10821. // Setting properties
  10822. newMesh.material = material;
  10823. newMesh.checkCollisions = source.checkCollisions;
  10824. // Cleaning
  10825. if (disposeSource) {
  10826. for (index = 0; index < meshes.length; index++) {
  10827. meshes[index].dispose();
  10828. }
  10829. }
  10830. return newMesh;
  10831. };
  10832. return Mesh;
  10833. })(BABYLON.AbstractMesh);
  10834. BABYLON.Mesh = Mesh;
  10835. })(BABYLON || (BABYLON = {}));
  10836. //# sourceMappingURL=babylon.mesh.js.map
  10837. var BABYLON;
  10838. (function (BABYLON) {
  10839. var GroundMesh = (function (_super) {
  10840. __extends(GroundMesh, _super);
  10841. function GroundMesh(name, scene) {
  10842. _super.call(this, name, scene);
  10843. this.generateOctree = false;
  10844. this._worldInverse = new BABYLON.Matrix();
  10845. }
  10846. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  10847. get: function () {
  10848. return this._subdivisions;
  10849. },
  10850. enumerable: true,
  10851. configurable: true
  10852. });
  10853. GroundMesh.prototype.optimize = function (chunksCount) {
  10854. this.subdivide(this._subdivisions);
  10855. this.createOrUpdateSubmeshesOctree(32);
  10856. };
  10857. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  10858. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  10859. this.getWorldMatrix().invertToRef(this._worldInverse);
  10860. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  10861. var pickInfo = this.intersects(ray);
  10862. if (pickInfo.hit) {
  10863. return pickInfo.pickedPoint.y;
  10864. }
  10865. return 0;
  10866. };
  10867. return GroundMesh;
  10868. })(BABYLON.Mesh);
  10869. BABYLON.GroundMesh = GroundMesh;
  10870. })(BABYLON || (BABYLON = {}));
  10871. //# sourceMappingURL=babylon.groundMesh.js.map
  10872. var BABYLON;
  10873. (function (BABYLON) {
  10874. /**
  10875. * Creates an instance based on a source mesh.
  10876. */
  10877. var InstancedMesh = (function (_super) {
  10878. __extends(InstancedMesh, _super);
  10879. function InstancedMesh(name, source) {
  10880. _super.call(this, name, source.getScene());
  10881. source.instances.push(this);
  10882. this._sourceMesh = source;
  10883. this.position.copyFrom(source.position);
  10884. this.rotation.copyFrom(source.rotation);
  10885. this.scaling.copyFrom(source.scaling);
  10886. if (source.rotationQuaternion) {
  10887. this.rotationQuaternion = source.rotationQuaternion.clone();
  10888. }
  10889. this.infiniteDistance = source.infiniteDistance;
  10890. this.setPivotMatrix(source.getPivotMatrix());
  10891. this.refreshBoundingInfo();
  10892. this._syncSubMeshes();
  10893. }
  10894. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  10895. // Methods
  10896. get: function () {
  10897. return this._sourceMesh.receiveShadows;
  10898. },
  10899. enumerable: true,
  10900. configurable: true
  10901. });
  10902. Object.defineProperty(InstancedMesh.prototype, "material", {
  10903. get: function () {
  10904. return this._sourceMesh.material;
  10905. },
  10906. enumerable: true,
  10907. configurable: true
  10908. });
  10909. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  10910. get: function () {
  10911. return this._sourceMesh.visibility;
  10912. },
  10913. enumerable: true,
  10914. configurable: true
  10915. });
  10916. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  10917. get: function () {
  10918. return this._sourceMesh.skeleton;
  10919. },
  10920. enumerable: true,
  10921. configurable: true
  10922. });
  10923. InstancedMesh.prototype.getTotalVertices = function () {
  10924. return this._sourceMesh.getTotalVertices();
  10925. };
  10926. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  10927. get: function () {
  10928. return this._sourceMesh;
  10929. },
  10930. enumerable: true,
  10931. configurable: true
  10932. });
  10933. InstancedMesh.prototype.getVerticesData = function (kind) {
  10934. return this._sourceMesh.getVerticesData(kind);
  10935. };
  10936. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  10937. return this._sourceMesh.isVerticesDataPresent(kind);
  10938. };
  10939. InstancedMesh.prototype.getIndices = function () {
  10940. return this._sourceMesh.getIndices();
  10941. };
  10942. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  10943. get: function () {
  10944. return this._sourceMesh._positions;
  10945. },
  10946. enumerable: true,
  10947. configurable: true
  10948. });
  10949. InstancedMesh.prototype.refreshBoundingInfo = function () {
  10950. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10951. if (data) {
  10952. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  10953. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10954. }
  10955. this._updateBoundingInfo();
  10956. };
  10957. InstancedMesh.prototype._preActivate = function () {
  10958. if (this._currentLOD) {
  10959. this._currentLOD._preActivate();
  10960. }
  10961. };
  10962. InstancedMesh.prototype._activate = function (renderId) {
  10963. if (this._currentLOD) {
  10964. this._currentLOD._registerInstanceForRenderId(this, renderId);
  10965. }
  10966. };
  10967. InstancedMesh.prototype.getLOD = function (camera) {
  10968. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  10969. if (this._currentLOD === this.sourceMesh) {
  10970. return this;
  10971. }
  10972. return this._currentLOD;
  10973. };
  10974. InstancedMesh.prototype._syncSubMeshes = function () {
  10975. this.releaseSubMeshes();
  10976. if (this._sourceMesh.subMeshes) {
  10977. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  10978. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  10979. }
  10980. }
  10981. };
  10982. InstancedMesh.prototype._generatePointsArray = function () {
  10983. return this._sourceMesh._generatePointsArray();
  10984. };
  10985. // Clone
  10986. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10987. var result = this._sourceMesh.createInstance(name);
  10988. // Deep copy
  10989. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  10990. // Bounding info
  10991. this.refreshBoundingInfo();
  10992. // Parent
  10993. if (newParent) {
  10994. result.parent = newParent;
  10995. }
  10996. if (!doNotCloneChildren) {
  10997. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10998. var mesh = this.getScene().meshes[index];
  10999. if (mesh.parent === this) {
  11000. mesh.clone(mesh.name, result);
  11001. }
  11002. }
  11003. }
  11004. result.computeWorldMatrix(true);
  11005. return result;
  11006. };
  11007. // Dispoe
  11008. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11009. // Remove from mesh
  11010. var index = this._sourceMesh.instances.indexOf(this);
  11011. this._sourceMesh.instances.splice(index, 1);
  11012. _super.prototype.dispose.call(this, doNotRecurse);
  11013. };
  11014. return InstancedMesh;
  11015. })(BABYLON.AbstractMesh);
  11016. BABYLON.InstancedMesh = InstancedMesh;
  11017. })(BABYLON || (BABYLON = {}));
  11018. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  11019. (function (BABYLON) {
  11020. var SubMesh = (function () {
  11021. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  11022. if (createBoundingBox === void 0) { createBoundingBox = true; }
  11023. this.materialIndex = materialIndex;
  11024. this.verticesStart = verticesStart;
  11025. this.verticesCount = verticesCount;
  11026. this.indexStart = indexStart;
  11027. this.indexCount = indexCount;
  11028. this._renderId = 0;
  11029. this._mesh = mesh;
  11030. this._renderingMesh = renderingMesh || mesh;
  11031. mesh.subMeshes.push(this);
  11032. this._id = mesh.subMeshes.length - 1;
  11033. if (createBoundingBox) {
  11034. this.refreshBoundingInfo();
  11035. }
  11036. }
  11037. SubMesh.prototype.getBoundingInfo = function () {
  11038. return this._boundingInfo;
  11039. };
  11040. SubMesh.prototype.getMesh = function () {
  11041. return this._mesh;
  11042. };
  11043. SubMesh.prototype.getRenderingMesh = function () {
  11044. return this._renderingMesh;
  11045. };
  11046. SubMesh.prototype.getMaterial = function () {
  11047. var rootMaterial = this._renderingMesh.material;
  11048. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11049. var multiMaterial = rootMaterial;
  11050. return multiMaterial.getSubMaterial(this.materialIndex);
  11051. }
  11052. if (!rootMaterial) {
  11053. return this._mesh.getScene().defaultMaterial;
  11054. }
  11055. return rootMaterial;
  11056. };
  11057. // Methods
  11058. SubMesh.prototype.refreshBoundingInfo = function () {
  11059. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11060. if (!data) {
  11061. this._boundingInfo = this._mesh._boundingInfo;
  11062. return;
  11063. }
  11064. var indices = this._renderingMesh.getIndices();
  11065. var extend;
  11066. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11067. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11068. }
  11069. else {
  11070. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11071. }
  11072. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11073. };
  11074. SubMesh.prototype._checkCollision = function (collider) {
  11075. return this._boundingInfo._checkCollision(collider);
  11076. };
  11077. SubMesh.prototype.updateBoundingInfo = function (world) {
  11078. if (!this._boundingInfo) {
  11079. this.refreshBoundingInfo();
  11080. }
  11081. this._boundingInfo._update(world);
  11082. };
  11083. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11084. return this._boundingInfo.isInFrustum(frustumPlanes);
  11085. };
  11086. SubMesh.prototype.render = function () {
  11087. this._renderingMesh.render(this);
  11088. };
  11089. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11090. if (!this._linesIndexBuffer) {
  11091. var linesIndices = [];
  11092. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11093. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11094. }
  11095. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11096. this.linesIndexCount = linesIndices.length;
  11097. }
  11098. return this._linesIndexBuffer;
  11099. };
  11100. SubMesh.prototype.canIntersects = function (ray) {
  11101. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11102. };
  11103. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11104. var intersectInfo = null;
  11105. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11106. var p0 = positions[indices[index]];
  11107. var p1 = positions[indices[index + 1]];
  11108. var p2 = positions[indices[index + 2]];
  11109. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11110. if (currentIntersectInfo) {
  11111. if (currentIntersectInfo.distance < 0) {
  11112. continue;
  11113. }
  11114. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11115. intersectInfo = currentIntersectInfo;
  11116. intersectInfo.faceId = index / 3;
  11117. if (fastCheck) {
  11118. break;
  11119. }
  11120. }
  11121. }
  11122. }
  11123. return intersectInfo;
  11124. };
  11125. // Clone
  11126. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11127. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11128. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11129. return result;
  11130. };
  11131. // Dispose
  11132. SubMesh.prototype.dispose = function () {
  11133. if (this._linesIndexBuffer) {
  11134. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11135. this._linesIndexBuffer = null;
  11136. }
  11137. // Remove from mesh
  11138. var index = this._mesh.subMeshes.indexOf(this);
  11139. this._mesh.subMeshes.splice(index, 1);
  11140. };
  11141. // Statics
  11142. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11143. var minVertexIndex = Number.MAX_VALUE;
  11144. var maxVertexIndex = -Number.MAX_VALUE;
  11145. renderingMesh = renderingMesh || mesh;
  11146. var indices = renderingMesh.getIndices();
  11147. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11148. var vertexIndex = indices[index];
  11149. if (vertexIndex < minVertexIndex)
  11150. minVertexIndex = vertexIndex;
  11151. if (vertexIndex > maxVertexIndex)
  11152. maxVertexIndex = vertexIndex;
  11153. }
  11154. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11155. };
  11156. return SubMesh;
  11157. })();
  11158. BABYLON.SubMesh = SubMesh;
  11159. })(BABYLON || (BABYLON = {}));
  11160. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11161. (function (BABYLON) {
  11162. var BaseTexture = (function () {
  11163. function BaseTexture(scene) {
  11164. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11165. this.hasAlpha = false;
  11166. this.getAlphaFromRGB = false;
  11167. this.level = 1;
  11168. this.isCube = false;
  11169. this.isRenderTarget = false;
  11170. this.animations = new Array();
  11171. this.coordinatesIndex = 0;
  11172. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11173. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11174. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11175. this.anisotropicFilteringLevel = 4;
  11176. this._scene = scene;
  11177. this._scene.textures.push(this);
  11178. }
  11179. BaseTexture.prototype.getScene = function () {
  11180. return this._scene;
  11181. };
  11182. BaseTexture.prototype.getTextureMatrix = function () {
  11183. return null;
  11184. };
  11185. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11186. return null;
  11187. };
  11188. BaseTexture.prototype.getInternalTexture = function () {
  11189. return this._texture;
  11190. };
  11191. BaseTexture.prototype.isReady = function () {
  11192. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11193. return true;
  11194. }
  11195. if (this._texture) {
  11196. return this._texture.isReady;
  11197. }
  11198. return false;
  11199. };
  11200. BaseTexture.prototype.getSize = function () {
  11201. if (this._texture._width) {
  11202. return { width: this._texture._width, height: this._texture._height };
  11203. }
  11204. if (this._texture._size) {
  11205. return { width: this._texture._size, height: this._texture._size };
  11206. }
  11207. return { width: 0, height: 0 };
  11208. };
  11209. BaseTexture.prototype.getBaseSize = function () {
  11210. if (!this.isReady())
  11211. return { width: 0, height: 0 };
  11212. if (this._texture._size) {
  11213. return { width: this._texture._size, height: this._texture._size };
  11214. }
  11215. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11216. };
  11217. BaseTexture.prototype.scale = function (ratio) {
  11218. };
  11219. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11220. get: function () {
  11221. return false;
  11222. },
  11223. enumerable: true,
  11224. configurable: true
  11225. });
  11226. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11227. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11228. for (var index = 0; index < texturesCache.length; index++) {
  11229. var texturesCacheEntry = texturesCache[index];
  11230. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11231. texturesCache.splice(index, 1);
  11232. return;
  11233. }
  11234. }
  11235. };
  11236. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11237. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11238. for (var index = 0; index < texturesCache.length; index++) {
  11239. var texturesCacheEntry = texturesCache[index];
  11240. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11241. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11242. texturesCacheEntry.references++;
  11243. return texturesCacheEntry;
  11244. }
  11245. }
  11246. }
  11247. return null;
  11248. };
  11249. BaseTexture.prototype.delayLoad = function () {
  11250. };
  11251. BaseTexture.prototype.releaseInternalTexture = function () {
  11252. if (!this._texture) {
  11253. return;
  11254. }
  11255. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11256. this._texture.references--;
  11257. // Final reference ?
  11258. if (this._texture.references === 0) {
  11259. var index = texturesCache.indexOf(this._texture);
  11260. texturesCache.splice(index, 1);
  11261. this._scene.getEngine()._releaseTexture(this._texture);
  11262. delete this._texture;
  11263. }
  11264. };
  11265. BaseTexture.prototype.clone = function () {
  11266. return null;
  11267. };
  11268. BaseTexture.prototype.dispose = function () {
  11269. // Remove from scene
  11270. var index = this._scene.textures.indexOf(this);
  11271. if (index >= 0) {
  11272. this._scene.textures.splice(index, 1);
  11273. }
  11274. if (this._texture === undefined) {
  11275. return;
  11276. }
  11277. this.releaseInternalTexture();
  11278. // Callback
  11279. if (this.onDispose) {
  11280. this.onDispose();
  11281. }
  11282. };
  11283. return BaseTexture;
  11284. })();
  11285. BABYLON.BaseTexture = BaseTexture;
  11286. })(BABYLON || (BABYLON = {}));
  11287. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  11288. (function (BABYLON) {
  11289. var RenderingGroup = (function () {
  11290. function RenderingGroup(index, scene) {
  11291. this.index = index;
  11292. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11293. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11294. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11295. this._scene = scene;
  11296. }
  11297. RenderingGroup.prototype.render = function (customRenderFunction) {
  11298. if (customRenderFunction) {
  11299. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11300. return true;
  11301. }
  11302. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11303. return false;
  11304. }
  11305. var engine = this._scene.getEngine();
  11306. // Opaque
  11307. var subIndex;
  11308. var submesh;
  11309. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11310. submesh = this._opaqueSubMeshes.data[subIndex];
  11311. submesh.render();
  11312. }
  11313. // Alpha test
  11314. engine.setAlphaTesting(true);
  11315. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11316. submesh = this._alphaTestSubMeshes.data[subIndex];
  11317. submesh.render();
  11318. }
  11319. engine.setAlphaTesting(false);
  11320. // Transparent
  11321. if (this._transparentSubMeshes.length) {
  11322. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11323. submesh = this._transparentSubMeshes.data[subIndex];
  11324. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11325. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11326. }
  11327. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11328. sortedArray.sort(function (a, b) {
  11329. // Alpha index first
  11330. if (a._alphaIndex > b._alphaIndex) {
  11331. return 1;
  11332. }
  11333. if (a._alphaIndex < b._alphaIndex) {
  11334. return -1;
  11335. }
  11336. // Then distance to camera
  11337. if (a._distanceToCamera < b._distanceToCamera) {
  11338. return 1;
  11339. }
  11340. if (a._distanceToCamera > b._distanceToCamera) {
  11341. return -1;
  11342. }
  11343. return 0;
  11344. });
  11345. // Rendering
  11346. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11347. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11348. submesh = sortedArray[subIndex];
  11349. submesh.render();
  11350. }
  11351. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11352. }
  11353. return true;
  11354. };
  11355. RenderingGroup.prototype.prepare = function () {
  11356. this._opaqueSubMeshes.reset();
  11357. this._transparentSubMeshes.reset();
  11358. this._alphaTestSubMeshes.reset();
  11359. };
  11360. RenderingGroup.prototype.dispatch = function (subMesh) {
  11361. var material = subMesh.getMaterial();
  11362. var mesh = subMesh.getMesh();
  11363. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11364. this._transparentSubMeshes.push(subMesh);
  11365. }
  11366. else if (material.needAlphaTesting()) {
  11367. this._alphaTestSubMeshes.push(subMesh);
  11368. }
  11369. else {
  11370. this._opaqueSubMeshes.push(subMesh); // Opaque
  11371. }
  11372. };
  11373. return RenderingGroup;
  11374. })();
  11375. BABYLON.RenderingGroup = RenderingGroup;
  11376. })(BABYLON || (BABYLON = {}));
  11377. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  11378. (function (BABYLON) {
  11379. var RenderingManager = (function () {
  11380. function RenderingManager(scene) {
  11381. this._renderingGroups = new Array();
  11382. this._scene = scene;
  11383. }
  11384. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11385. if (this._scene._activeParticleSystems.length === 0) {
  11386. return;
  11387. }
  11388. // Particles
  11389. var beforeParticlesDate = BABYLON.Tools.Now;
  11390. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11391. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11392. if (particleSystem.renderingGroupId !== index) {
  11393. continue;
  11394. }
  11395. this._clearDepthBuffer();
  11396. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11397. this._scene._activeParticles += particleSystem.render();
  11398. }
  11399. }
  11400. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11401. };
  11402. RenderingManager.prototype._renderSprites = function (index) {
  11403. if (this._scene.spriteManagers.length === 0) {
  11404. return;
  11405. }
  11406. // Sprites
  11407. var beforeSpritessDate = BABYLON.Tools.Now;
  11408. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11409. var spriteManager = this._scene.spriteManagers[id];
  11410. if (spriteManager.renderingGroupId === index) {
  11411. this._clearDepthBuffer();
  11412. spriteManager.render();
  11413. }
  11414. }
  11415. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11416. };
  11417. RenderingManager.prototype._clearDepthBuffer = function () {
  11418. if (this._depthBufferAlreadyCleaned) {
  11419. return;
  11420. }
  11421. this._scene.getEngine().clear(0, false, true);
  11422. this._depthBufferAlreadyCleaned = true;
  11423. };
  11424. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11425. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11426. this._depthBufferAlreadyCleaned = false;
  11427. var renderingGroup = this._renderingGroups[index];
  11428. if (renderingGroup) {
  11429. this._clearDepthBuffer();
  11430. if (!renderingGroup.render(customRenderFunction)) {
  11431. this._renderingGroups.splice(index, 1);
  11432. }
  11433. }
  11434. if (renderSprites) {
  11435. this._renderSprites(index);
  11436. }
  11437. if (renderParticles) {
  11438. this._renderParticles(index, activeMeshes);
  11439. }
  11440. }
  11441. };
  11442. RenderingManager.prototype.reset = function () {
  11443. for (var index in this._renderingGroups) {
  11444. var renderingGroup = this._renderingGroups[index];
  11445. renderingGroup.prepare();
  11446. }
  11447. };
  11448. RenderingManager.prototype.dispatch = function (subMesh) {
  11449. var mesh = subMesh.getMesh();
  11450. var renderingGroupId = mesh.renderingGroupId || 0;
  11451. if (!this._renderingGroups[renderingGroupId]) {
  11452. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11453. }
  11454. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11455. };
  11456. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11457. return RenderingManager;
  11458. })();
  11459. BABYLON.RenderingManager = RenderingManager;
  11460. })(BABYLON || (BABYLON = {}));
  11461. //# sourceMappingURL=babylon.renderingManager.js.map
  11462. var BABYLON;
  11463. (function (BABYLON) {
  11464. var Texture = (function (_super) {
  11465. __extends(Texture, _super);
  11466. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  11467. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11468. if (onLoad === void 0) { onLoad = null; }
  11469. if (onError === void 0) { onError = null; }
  11470. if (buffer === void 0) { buffer = null; }
  11471. if (deleteBuffer === void 0) { deleteBuffer = false; }
  11472. _super.call(this, scene);
  11473. this.uOffset = 0;
  11474. this.vOffset = 0;
  11475. this.uScale = 1.0;
  11476. this.vScale = 1.0;
  11477. this.uAng = 0;
  11478. this.vAng = 0;
  11479. this.wAng = 0;
  11480. this.name = url;
  11481. this.url = url;
  11482. this._noMipmap = noMipmap;
  11483. this._invertY = invertY;
  11484. this._samplingMode = samplingMode;
  11485. this._buffer = buffer;
  11486. this._deleteBuffer = deleteBuffer;
  11487. if (!url) {
  11488. return;
  11489. }
  11490. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  11491. if (!this._texture) {
  11492. if (!scene.useDelayedTextureLoading) {
  11493. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  11494. if (deleteBuffer) {
  11495. delete this._buffer;
  11496. }
  11497. }
  11498. else {
  11499. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11500. }
  11501. }
  11502. }
  11503. Texture.prototype.delayLoad = function () {
  11504. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11505. return;
  11506. }
  11507. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11508. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  11509. if (!this._texture) {
  11510. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  11511. if (this._deleteBuffer) {
  11512. delete this._buffer;
  11513. }
  11514. }
  11515. };
  11516. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  11517. x -= this.uOffset + 0.5;
  11518. y -= this.vOffset + 0.5;
  11519. z -= 0.5;
  11520. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  11521. t.x *= this.uScale;
  11522. t.y *= this.vScale;
  11523. t.x += 0.5;
  11524. t.y += 0.5;
  11525. t.z += 0.5;
  11526. };
  11527. Texture.prototype.getTextureMatrix = function () {
  11528. 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) {
  11529. return this._cachedTextureMatrix;
  11530. }
  11531. this._cachedUOffset = this.uOffset;
  11532. this._cachedVOffset = this.vOffset;
  11533. this._cachedUScale = this.uScale;
  11534. this._cachedVScale = this.vScale;
  11535. this._cachedUAng = this.uAng;
  11536. this._cachedVAng = this.vAng;
  11537. this._cachedWAng = this.wAng;
  11538. if (!this._cachedTextureMatrix) {
  11539. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11540. this._rowGenerationMatrix = new BABYLON.Matrix();
  11541. this._t0 = BABYLON.Vector3.Zero();
  11542. this._t1 = BABYLON.Vector3.Zero();
  11543. this._t2 = BABYLON.Vector3.Zero();
  11544. }
  11545. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  11546. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  11547. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  11548. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  11549. this._t1.subtractInPlace(this._t0);
  11550. this._t2.subtractInPlace(this._t0);
  11551. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11552. this._cachedTextureMatrix.m[0] = this._t1.x;
  11553. this._cachedTextureMatrix.m[1] = this._t1.y;
  11554. this._cachedTextureMatrix.m[2] = this._t1.z;
  11555. this._cachedTextureMatrix.m[4] = this._t2.x;
  11556. this._cachedTextureMatrix.m[5] = this._t2.y;
  11557. this._cachedTextureMatrix.m[6] = this._t2.z;
  11558. this._cachedTextureMatrix.m[8] = this._t0.x;
  11559. this._cachedTextureMatrix.m[9] = this._t0.y;
  11560. this._cachedTextureMatrix.m[10] = this._t0.z;
  11561. return this._cachedTextureMatrix;
  11562. };
  11563. Texture.prototype.getReflectionTextureMatrix = function () {
  11564. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  11565. return this._cachedTextureMatrix;
  11566. }
  11567. if (!this._cachedTextureMatrix) {
  11568. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11569. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  11570. }
  11571. this._cachedCoordinatesMode = this.coordinatesMode;
  11572. switch (this.coordinatesMode) {
  11573. case BABYLON.Texture.SPHERICAL_MODE:
  11574. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11575. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  11576. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  11577. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  11578. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  11579. break;
  11580. case BABYLON.Texture.PLANAR_MODE:
  11581. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11582. this._cachedTextureMatrix[0] = this.uScale;
  11583. this._cachedTextureMatrix[5] = this.vScale;
  11584. this._cachedTextureMatrix[12] = this.uOffset;
  11585. this._cachedTextureMatrix[13] = this.vOffset;
  11586. break;
  11587. case BABYLON.Texture.PROJECTION_MODE:
  11588. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  11589. this._projectionModeMatrix.m[0] = 0.5;
  11590. this._projectionModeMatrix.m[5] = -0.5;
  11591. this._projectionModeMatrix.m[10] = 0.0;
  11592. this._projectionModeMatrix.m[12] = 0.5;
  11593. this._projectionModeMatrix.m[13] = 0.5;
  11594. this._projectionModeMatrix.m[14] = 1.0;
  11595. this._projectionModeMatrix.m[15] = 1.0;
  11596. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  11597. break;
  11598. default:
  11599. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11600. break;
  11601. }
  11602. return this._cachedTextureMatrix;
  11603. };
  11604. Texture.prototype.clone = function () {
  11605. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  11606. // Base texture
  11607. newTexture.hasAlpha = this.hasAlpha;
  11608. newTexture.level = this.level;
  11609. newTexture.wrapU = this.wrapU;
  11610. newTexture.wrapV = this.wrapV;
  11611. newTexture.coordinatesIndex = this.coordinatesIndex;
  11612. newTexture.coordinatesMode = this.coordinatesMode;
  11613. // Texture
  11614. newTexture.uOffset = this.uOffset;
  11615. newTexture.vOffset = this.vOffset;
  11616. newTexture.uScale = this.uScale;
  11617. newTexture.vScale = this.vScale;
  11618. newTexture.uAng = this.uAng;
  11619. newTexture.vAng = this.vAng;
  11620. newTexture.wAng = this.wAng;
  11621. return newTexture;
  11622. };
  11623. // Statics
  11624. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  11625. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11626. if (onLoad === void 0) { onLoad = null; }
  11627. if (onError === void 0) { onError = null; }
  11628. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  11629. };
  11630. // Constants
  11631. Texture.NEAREST_SAMPLINGMODE = 1;
  11632. Texture.BILINEAR_SAMPLINGMODE = 2;
  11633. Texture.TRILINEAR_SAMPLINGMODE = 3;
  11634. Texture.EXPLICIT_MODE = 0;
  11635. Texture.SPHERICAL_MODE = 1;
  11636. Texture.PLANAR_MODE = 2;
  11637. Texture.CUBIC_MODE = 3;
  11638. Texture.PROJECTION_MODE = 4;
  11639. Texture.SKYBOX_MODE = 5;
  11640. Texture.CLAMP_ADDRESSMODE = 0;
  11641. Texture.WRAP_ADDRESSMODE = 1;
  11642. Texture.MIRROR_ADDRESSMODE = 2;
  11643. return Texture;
  11644. })(BABYLON.BaseTexture);
  11645. BABYLON.Texture = Texture;
  11646. })(BABYLON || (BABYLON = {}));
  11647. //# sourceMappingURL=babylon.texture.js.map
  11648. var BABYLON;
  11649. (function (BABYLON) {
  11650. var CubeTexture = (function (_super) {
  11651. __extends(CubeTexture, _super);
  11652. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  11653. _super.call(this, scene);
  11654. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  11655. this.name = rootUrl;
  11656. this.url = rootUrl;
  11657. this._noMipmap = noMipmap;
  11658. this.hasAlpha = false;
  11659. this._texture = this._getFromCache(rootUrl, noMipmap);
  11660. if (!extensions) {
  11661. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  11662. }
  11663. this._extensions = extensions;
  11664. if (!this._texture) {
  11665. if (!scene.useDelayedTextureLoading) {
  11666. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  11667. }
  11668. else {
  11669. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11670. }
  11671. }
  11672. this.isCube = true;
  11673. this._textureMatrix = BABYLON.Matrix.Identity();
  11674. }
  11675. CubeTexture.prototype.clone = function () {
  11676. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  11677. // Base texture
  11678. newTexture.level = this.level;
  11679. newTexture.wrapU = this.wrapU;
  11680. newTexture.wrapV = this.wrapV;
  11681. newTexture.coordinatesIndex = this.coordinatesIndex;
  11682. newTexture.coordinatesMode = this.coordinatesMode;
  11683. return newTexture;
  11684. };
  11685. // Methods
  11686. CubeTexture.prototype.delayLoad = function () {
  11687. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11688. return;
  11689. }
  11690. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11691. this._texture = this._getFromCache(this.url, this._noMipmap);
  11692. if (!this._texture) {
  11693. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  11694. }
  11695. };
  11696. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  11697. return this._textureMatrix;
  11698. };
  11699. return CubeTexture;
  11700. })(BABYLON.BaseTexture);
  11701. BABYLON.CubeTexture = CubeTexture;
  11702. })(BABYLON || (BABYLON = {}));
  11703. //# sourceMappingURL=babylon.cubeTexture.js.map
  11704. var BABYLON;
  11705. (function (BABYLON) {
  11706. var RenderTargetTexture = (function (_super) {
  11707. __extends(RenderTargetTexture, _super);
  11708. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  11709. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  11710. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  11711. _super.call(this, null, scene, !generateMipMaps);
  11712. this.renderList = new Array();
  11713. this.renderParticles = true;
  11714. this.renderSprites = false;
  11715. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  11716. this._currentRefreshId = -1;
  11717. this._refreshRate = 1;
  11718. this.name = name;
  11719. this.isRenderTarget = true;
  11720. this._size = size;
  11721. this._generateMipMaps = generateMipMaps;
  11722. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  11723. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  11724. // Rendering groups
  11725. this._renderingManager = new BABYLON.RenderingManager(scene);
  11726. }
  11727. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  11728. this._currentRefreshId = -1;
  11729. };
  11730. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  11731. get: function () {
  11732. return this._refreshRate;
  11733. },
  11734. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11735. set: function (value) {
  11736. this._refreshRate = value;
  11737. this.resetRefreshCounter();
  11738. },
  11739. enumerable: true,
  11740. configurable: true
  11741. });
  11742. RenderTargetTexture.prototype._shouldRender = function () {
  11743. if (this._currentRefreshId === -1) {
  11744. this._currentRefreshId = 1;
  11745. return true;
  11746. }
  11747. if (this.refreshRate === this._currentRefreshId) {
  11748. this._currentRefreshId = 1;
  11749. return true;
  11750. }
  11751. this._currentRefreshId++;
  11752. return false;
  11753. };
  11754. RenderTargetTexture.prototype.isReady = function () {
  11755. if (!this.getScene().renderTargetsEnabled) {
  11756. return false;
  11757. }
  11758. return _super.prototype.isReady.call(this);
  11759. };
  11760. RenderTargetTexture.prototype.getRenderSize = function () {
  11761. return this._size;
  11762. };
  11763. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11764. get: function () {
  11765. return true;
  11766. },
  11767. enumerable: true,
  11768. configurable: true
  11769. });
  11770. RenderTargetTexture.prototype.scale = function (ratio) {
  11771. var newSize = this._size * ratio;
  11772. this.resize(newSize, this._generateMipMaps);
  11773. };
  11774. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11775. this.releaseInternalTexture();
  11776. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11777. };
  11778. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11779. var scene = this.getScene();
  11780. var engine = scene.getEngine();
  11781. if (this._waitingRenderList) {
  11782. this.renderList = [];
  11783. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11784. var id = this._waitingRenderList[index];
  11785. this.renderList.push(scene.getMeshByID(id));
  11786. }
  11787. delete this._waitingRenderList;
  11788. }
  11789. if (this.renderList && this.renderList.length === 0) {
  11790. return;
  11791. }
  11792. // Bind
  11793. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11794. engine.bindFramebuffer(this._texture);
  11795. }
  11796. // Clear
  11797. engine.clear(scene.clearColor, true, true);
  11798. this._renderingManager.reset();
  11799. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  11800. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  11801. var mesh = currentRenderList[meshIndex];
  11802. if (mesh) {
  11803. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  11804. // Reset _currentRefreshId
  11805. this.resetRefreshCounter();
  11806. continue;
  11807. }
  11808. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  11809. mesh._activate(scene.getRenderId());
  11810. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  11811. var subMesh = mesh.subMeshes[subIndex];
  11812. scene._activeVertices += subMesh.indexCount;
  11813. this._renderingManager.dispatch(subMesh);
  11814. }
  11815. }
  11816. }
  11817. }
  11818. if (!this._doNotChangeAspectRatio) {
  11819. scene.updateTransformMatrix(true);
  11820. }
  11821. if (this.onBeforeRender) {
  11822. this.onBeforeRender();
  11823. }
  11824. // Render
  11825. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  11826. if (useCameraPostProcess) {
  11827. scene.postProcessManager._finalizeFrame(false, this._texture);
  11828. }
  11829. if (this.onAfterRender) {
  11830. this.onAfterRender();
  11831. }
  11832. // Unbind
  11833. engine.unBindFramebuffer(this._texture);
  11834. if (!this._doNotChangeAspectRatio) {
  11835. scene.updateTransformMatrix(true);
  11836. }
  11837. };
  11838. RenderTargetTexture.prototype.clone = function () {
  11839. var textureSize = this.getSize();
  11840. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11841. // Base texture
  11842. newTexture.hasAlpha = this.hasAlpha;
  11843. newTexture.level = this.level;
  11844. // RenderTarget Texture
  11845. newTexture.coordinatesMode = this.coordinatesMode;
  11846. newTexture.renderList = this.renderList.slice(0);
  11847. return newTexture;
  11848. };
  11849. return RenderTargetTexture;
  11850. })(BABYLON.Texture);
  11851. BABYLON.RenderTargetTexture = RenderTargetTexture;
  11852. })(BABYLON || (BABYLON = {}));
  11853. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  11854. var BABYLON;
  11855. (function (BABYLON) {
  11856. var ProceduralTexture = (function (_super) {
  11857. __extends(ProceduralTexture, _super);
  11858. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  11859. if (generateMipMaps === void 0) { generateMipMaps = true; }
  11860. _super.call(this, null, scene, !generateMipMaps);
  11861. this._currentRefreshId = -1;
  11862. this._refreshRate = 1;
  11863. this._vertexDeclaration = [2];
  11864. this._vertexStrideSize = 2 * 4;
  11865. this._uniforms = new Array();
  11866. this._samplers = new Array();
  11867. this._textures = new Array();
  11868. this._floats = new Array();
  11869. this._floatsArrays = {};
  11870. this._colors3 = new Array();
  11871. this._colors4 = new Array();
  11872. this._vectors2 = new Array();
  11873. this._vectors3 = new Array();
  11874. this._matrices = new Array();
  11875. this._fallbackTextureUsed = false;
  11876. scene._proceduralTextures.push(this);
  11877. this.name = name;
  11878. this.isRenderTarget = true;
  11879. this._size = size;
  11880. this._generateMipMaps = generateMipMaps;
  11881. this.setFragment(fragment);
  11882. this._fallbackTexture = fallbackTexture;
  11883. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11884. // VBO
  11885. var vertices = [];
  11886. vertices.push(1, 1);
  11887. vertices.push(-1, 1);
  11888. vertices.push(-1, -1);
  11889. vertices.push(1, -1);
  11890. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11891. // Indices
  11892. var indices = [];
  11893. indices.push(0);
  11894. indices.push(1);
  11895. indices.push(2);
  11896. indices.push(0);
  11897. indices.push(2);
  11898. indices.push(3);
  11899. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11900. }
  11901. ProceduralTexture.prototype.reset = function () {
  11902. if (this._effect === undefined) {
  11903. return;
  11904. }
  11905. var engine = this.getScene().getEngine();
  11906. engine._releaseEffect(this._effect);
  11907. };
  11908. ProceduralTexture.prototype.isReady = function () {
  11909. var _this = this;
  11910. var engine = this.getScene().getEngine();
  11911. var shaders;
  11912. if (!this._fragment) {
  11913. return false;
  11914. }
  11915. if (this._fallbackTextureUsed) {
  11916. return true;
  11917. }
  11918. if (this._fragment.fragmentElement !== undefined) {
  11919. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  11920. }
  11921. else {
  11922. shaders = { vertex: "procedural", fragment: this._fragment };
  11923. }
  11924. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  11925. _this.releaseInternalTexture();
  11926. if (_this._fallbackTexture) {
  11927. _this._texture = _this._fallbackTexture._texture;
  11928. _this._texture.references++;
  11929. }
  11930. _this._fallbackTextureUsed = true;
  11931. });
  11932. return this._effect.isReady();
  11933. };
  11934. ProceduralTexture.prototype.resetRefreshCounter = function () {
  11935. this._currentRefreshId = -1;
  11936. };
  11937. ProceduralTexture.prototype.setFragment = function (fragment) {
  11938. this._fragment = fragment;
  11939. };
  11940. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  11941. get: function () {
  11942. return this._refreshRate;
  11943. },
  11944. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11945. set: function (value) {
  11946. this._refreshRate = value;
  11947. this.resetRefreshCounter();
  11948. },
  11949. enumerable: true,
  11950. configurable: true
  11951. });
  11952. ProceduralTexture.prototype._shouldRender = function () {
  11953. if (!this.isReady() || !this._texture) {
  11954. return false;
  11955. }
  11956. if (this._fallbackTextureUsed) {
  11957. return false;
  11958. }
  11959. if (this._currentRefreshId === -1) {
  11960. this._currentRefreshId = 1;
  11961. return true;
  11962. }
  11963. if (this.refreshRate === this._currentRefreshId) {
  11964. this._currentRefreshId = 1;
  11965. return true;
  11966. }
  11967. this._currentRefreshId++;
  11968. return false;
  11969. };
  11970. ProceduralTexture.prototype.getRenderSize = function () {
  11971. return this._size;
  11972. };
  11973. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  11974. if (this._fallbackTextureUsed) {
  11975. return;
  11976. }
  11977. this.releaseInternalTexture();
  11978. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11979. };
  11980. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  11981. if (this._uniforms.indexOf(uniformName) === -1) {
  11982. this._uniforms.push(uniformName);
  11983. }
  11984. };
  11985. ProceduralTexture.prototype.setTexture = function (name, texture) {
  11986. if (this._samplers.indexOf(name) === -1) {
  11987. this._samplers.push(name);
  11988. }
  11989. this._textures[name] = texture;
  11990. return this;
  11991. };
  11992. ProceduralTexture.prototype.setFloat = function (name, value) {
  11993. this._checkUniform(name);
  11994. this._floats[name] = value;
  11995. return this;
  11996. };
  11997. ProceduralTexture.prototype.setFloats = function (name, value) {
  11998. this._checkUniform(name);
  11999. this._floatsArrays[name] = value;
  12000. return this;
  12001. };
  12002. ProceduralTexture.prototype.setColor3 = function (name, value) {
  12003. this._checkUniform(name);
  12004. this._colors3[name] = value;
  12005. return this;
  12006. };
  12007. ProceduralTexture.prototype.setColor4 = function (name, value) {
  12008. this._checkUniform(name);
  12009. this._colors4[name] = value;
  12010. return this;
  12011. };
  12012. ProceduralTexture.prototype.setVector2 = function (name, value) {
  12013. this._checkUniform(name);
  12014. this._vectors2[name] = value;
  12015. return this;
  12016. };
  12017. ProceduralTexture.prototype.setVector3 = function (name, value) {
  12018. this._checkUniform(name);
  12019. this._vectors3[name] = value;
  12020. return this;
  12021. };
  12022. ProceduralTexture.prototype.setMatrix = function (name, value) {
  12023. this._checkUniform(name);
  12024. this._matrices[name] = value;
  12025. return this;
  12026. };
  12027. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12028. var scene = this.getScene();
  12029. var engine = scene.getEngine();
  12030. engine.bindFramebuffer(this._texture);
  12031. // Clear
  12032. engine.clear(scene.clearColor, true, true);
  12033. // Render
  12034. engine.enableEffect(this._effect);
  12035. engine.setState(false);
  12036. for (var name in this._textures) {
  12037. this._effect.setTexture(name, this._textures[name]);
  12038. }
  12039. for (name in this._floats) {
  12040. this._effect.setFloat(name, this._floats[name]);
  12041. }
  12042. for (name in this._floatsArrays) {
  12043. this._effect.setArray(name, this._floatsArrays[name]);
  12044. }
  12045. for (name in this._colors3) {
  12046. this._effect.setColor3(name, this._colors3[name]);
  12047. }
  12048. for (name in this._colors4) {
  12049. var color = this._colors4[name];
  12050. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12051. }
  12052. for (name in this._vectors2) {
  12053. this._effect.setVector2(name, this._vectors2[name]);
  12054. }
  12055. for (name in this._vectors3) {
  12056. this._effect.setVector3(name, this._vectors3[name]);
  12057. }
  12058. for (name in this._matrices) {
  12059. this._effect.setMatrix(name, this._matrices[name]);
  12060. }
  12061. // VBOs
  12062. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12063. // Draw order
  12064. engine.draw(true, 0, 6);
  12065. // Unbind
  12066. engine.unBindFramebuffer(this._texture);
  12067. };
  12068. ProceduralTexture.prototype.clone = function () {
  12069. var textureSize = this.getSize();
  12070. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12071. // Base texture
  12072. newTexture.hasAlpha = this.hasAlpha;
  12073. newTexture.level = this.level;
  12074. // RenderTarget Texture
  12075. newTexture.coordinatesMode = this.coordinatesMode;
  12076. return newTexture;
  12077. };
  12078. ProceduralTexture.prototype.dispose = function () {
  12079. var index = this.getScene()._proceduralTextures.indexOf(this);
  12080. if (index >= 0) {
  12081. this.getScene()._proceduralTextures.splice(index, 1);
  12082. }
  12083. _super.prototype.dispose.call(this);
  12084. };
  12085. return ProceduralTexture;
  12086. })(BABYLON.Texture);
  12087. BABYLON.ProceduralTexture = ProceduralTexture;
  12088. })(BABYLON || (BABYLON = {}));
  12089. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12090. var BABYLON;
  12091. (function (BABYLON) {
  12092. var WoodProceduralTexture = (function (_super) {
  12093. __extends(WoodProceduralTexture, _super);
  12094. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12095. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12096. this._ampScale = 100.0;
  12097. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12098. this.updateShaderUniforms();
  12099. this.refreshRate = 0;
  12100. }
  12101. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12102. this.setFloat("ampScale", this._ampScale);
  12103. this.setColor3("woodColor", this._woodColor);
  12104. };
  12105. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12106. get: function () {
  12107. return this._ampScale;
  12108. },
  12109. set: function (value) {
  12110. this._ampScale = value;
  12111. this.updateShaderUniforms();
  12112. },
  12113. enumerable: true,
  12114. configurable: true
  12115. });
  12116. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12117. get: function () {
  12118. return this._woodColor;
  12119. },
  12120. set: function (value) {
  12121. this._woodColor = value;
  12122. this.updateShaderUniforms();
  12123. },
  12124. enumerable: true,
  12125. configurable: true
  12126. });
  12127. return WoodProceduralTexture;
  12128. })(BABYLON.ProceduralTexture);
  12129. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12130. var FireProceduralTexture = (function (_super) {
  12131. __extends(FireProceduralTexture, _super);
  12132. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12133. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12134. this._time = 0.0;
  12135. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12136. this._shift = 1.6;
  12137. this._autoGenerateTime = true;
  12138. this._alphaThreshold = 0.5;
  12139. this._fireColors = FireProceduralTexture.RedFireColors;
  12140. this.updateShaderUniforms();
  12141. this.refreshRate = 1;
  12142. }
  12143. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12144. this.setFloat("time", this._time);
  12145. this.setVector2("speed", this._speed);
  12146. this.setFloat("shift", this._shift);
  12147. this.setColor3("c1", this._fireColors[0]);
  12148. this.setColor3("c2", this._fireColors[1]);
  12149. this.setColor3("c3", this._fireColors[2]);
  12150. this.setColor3("c4", this._fireColors[3]);
  12151. this.setColor3("c5", this._fireColors[4]);
  12152. this.setColor3("c6", this._fireColors[5]);
  12153. this.setFloat("alphaThreshold", this._alphaThreshold);
  12154. };
  12155. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12156. if (this._autoGenerateTime) {
  12157. this._time += this.getScene().getAnimationRatio() * 0.03;
  12158. this.updateShaderUniforms();
  12159. }
  12160. _super.prototype.render.call(this, useCameraPostProcess);
  12161. };
  12162. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12163. get: function () {
  12164. return [
  12165. new BABYLON.Color3(0.5, 0.0, 1.0),
  12166. new BABYLON.Color3(0.9, 0.0, 1.0),
  12167. new BABYLON.Color3(0.2, 0.0, 1.0),
  12168. new BABYLON.Color3(1.0, 0.9, 1.0),
  12169. new BABYLON.Color3(0.1, 0.1, 1.0),
  12170. new BABYLON.Color3(0.9, 0.9, 1.0)
  12171. ];
  12172. },
  12173. enumerable: true,
  12174. configurable: true
  12175. });
  12176. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12177. get: function () {
  12178. return [
  12179. new BABYLON.Color3(0.5, 1.0, 0.0),
  12180. new BABYLON.Color3(0.5, 1.0, 0.0),
  12181. new BABYLON.Color3(0.3, 0.4, 0.0),
  12182. new BABYLON.Color3(0.5, 1.0, 0.0),
  12183. new BABYLON.Color3(0.2, 0.0, 0.0),
  12184. new BABYLON.Color3(0.5, 1.0, 0.0)
  12185. ];
  12186. },
  12187. enumerable: true,
  12188. configurable: true
  12189. });
  12190. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12191. get: function () {
  12192. return [
  12193. new BABYLON.Color3(0.5, 0.0, 0.1),
  12194. new BABYLON.Color3(0.9, 0.0, 0.0),
  12195. new BABYLON.Color3(0.2, 0.0, 0.0),
  12196. new BABYLON.Color3(1.0, 0.9, 0.0),
  12197. new BABYLON.Color3(0.1, 0.1, 0.1),
  12198. new BABYLON.Color3(0.9, 0.9, 0.9)
  12199. ];
  12200. },
  12201. enumerable: true,
  12202. configurable: true
  12203. });
  12204. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12205. get: function () {
  12206. return [
  12207. new BABYLON.Color3(0.1, 0.0, 0.5),
  12208. new BABYLON.Color3(0.0, 0.0, 0.5),
  12209. new BABYLON.Color3(0.1, 0.0, 0.2),
  12210. new BABYLON.Color3(0.0, 0.0, 1.0),
  12211. new BABYLON.Color3(0.1, 0.2, 0.3),
  12212. new BABYLON.Color3(0.0, 0.2, 0.9)
  12213. ];
  12214. },
  12215. enumerable: true,
  12216. configurable: true
  12217. });
  12218. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12219. get: function () {
  12220. return this._fireColors;
  12221. },
  12222. set: function (value) {
  12223. this._fireColors = value;
  12224. this.updateShaderUniforms();
  12225. },
  12226. enumerable: true,
  12227. configurable: true
  12228. });
  12229. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12230. get: function () {
  12231. return this._time;
  12232. },
  12233. set: function (value) {
  12234. this._time = value;
  12235. this.updateShaderUniforms();
  12236. },
  12237. enumerable: true,
  12238. configurable: true
  12239. });
  12240. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12241. get: function () {
  12242. return this._speed;
  12243. },
  12244. set: function (value) {
  12245. this._speed = value;
  12246. this.updateShaderUniforms();
  12247. },
  12248. enumerable: true,
  12249. configurable: true
  12250. });
  12251. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12252. get: function () {
  12253. return this._shift;
  12254. },
  12255. set: function (value) {
  12256. this._shift = value;
  12257. this.updateShaderUniforms();
  12258. },
  12259. enumerable: true,
  12260. configurable: true
  12261. });
  12262. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12263. get: function () {
  12264. return this._alphaThreshold;
  12265. },
  12266. set: function (value) {
  12267. this._alphaThreshold = value;
  12268. this.updateShaderUniforms();
  12269. },
  12270. enumerable: true,
  12271. configurable: true
  12272. });
  12273. return FireProceduralTexture;
  12274. })(BABYLON.ProceduralTexture);
  12275. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12276. var CloudProceduralTexture = (function (_super) {
  12277. __extends(CloudProceduralTexture, _super);
  12278. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12279. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12280. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12281. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12282. this.updateShaderUniforms();
  12283. this.refreshRate = 0;
  12284. }
  12285. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12286. this.setColor3("skyColor", this._skyColor);
  12287. this.setColor3("cloudColor", this._cloudColor);
  12288. };
  12289. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12290. get: function () {
  12291. return this._skyColor;
  12292. },
  12293. set: function (value) {
  12294. this._skyColor = value;
  12295. this.updateShaderUniforms();
  12296. },
  12297. enumerable: true,
  12298. configurable: true
  12299. });
  12300. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  12301. get: function () {
  12302. return this._cloudColor;
  12303. },
  12304. set: function (value) {
  12305. this._cloudColor = value;
  12306. this.updateShaderUniforms();
  12307. },
  12308. enumerable: true,
  12309. configurable: true
  12310. });
  12311. return CloudProceduralTexture;
  12312. })(BABYLON.ProceduralTexture);
  12313. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12314. var GrassProceduralTexture = (function (_super) {
  12315. __extends(GrassProceduralTexture, _super);
  12316. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12317. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12318. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12319. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12320. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12321. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12322. this._grassColors = [
  12323. new BABYLON.Color3(0.29, 0.38, 0.02),
  12324. new BABYLON.Color3(0.36, 0.49, 0.09),
  12325. new BABYLON.Color3(0.51, 0.6, 0.28)
  12326. ];
  12327. this.updateShaderUniforms();
  12328. this.refreshRate = 0;
  12329. }
  12330. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  12331. this.setColor3("herb1Color", this._grassColors[0]);
  12332. this.setColor3("herb2Color", this._grassColors[1]);
  12333. this.setColor3("herb3Color", this._grassColors[2]);
  12334. this.setColor3("groundColor", this._groundColor);
  12335. };
  12336. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  12337. get: function () {
  12338. return this._grassColors;
  12339. },
  12340. set: function (value) {
  12341. this._grassColors = value;
  12342. this.updateShaderUniforms();
  12343. },
  12344. enumerable: true,
  12345. configurable: true
  12346. });
  12347. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  12348. get: function () {
  12349. return this._groundColor;
  12350. },
  12351. set: function (value) {
  12352. this.groundColor = value;
  12353. this.updateShaderUniforms();
  12354. },
  12355. enumerable: true,
  12356. configurable: true
  12357. });
  12358. return GrassProceduralTexture;
  12359. })(BABYLON.ProceduralTexture);
  12360. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  12361. var RoadProceduralTexture = (function (_super) {
  12362. __extends(RoadProceduralTexture, _super);
  12363. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12364. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  12365. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  12366. this.updateShaderUniforms();
  12367. this.refreshRate = 0;
  12368. }
  12369. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  12370. this.setColor3("roadColor", this._roadColor);
  12371. };
  12372. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  12373. get: function () {
  12374. return this._roadColor;
  12375. },
  12376. set: function (value) {
  12377. this._roadColor = value;
  12378. this.updateShaderUniforms();
  12379. },
  12380. enumerable: true,
  12381. configurable: true
  12382. });
  12383. return RoadProceduralTexture;
  12384. })(BABYLON.ProceduralTexture);
  12385. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  12386. var BrickProceduralTexture = (function (_super) {
  12387. __extends(BrickProceduralTexture, _super);
  12388. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12389. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  12390. this._numberOfBricksHeight = 15;
  12391. this._numberOfBricksWidth = 5;
  12392. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12393. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12394. this.updateShaderUniforms();
  12395. this.refreshRate = 0;
  12396. }
  12397. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  12398. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  12399. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  12400. this.setColor3("brickColor", this._brickColor);
  12401. this.setColor3("jointColor", this._jointColor);
  12402. };
  12403. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  12404. get: function () {
  12405. return this._numberOfBricksHeight;
  12406. },
  12407. enumerable: true,
  12408. configurable: true
  12409. });
  12410. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  12411. set: function (value) {
  12412. this._numberOfBricksHeight = value;
  12413. this.updateShaderUniforms();
  12414. },
  12415. enumerable: true,
  12416. configurable: true
  12417. });
  12418. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  12419. get: function () {
  12420. return this._numberOfBricksWidth;
  12421. },
  12422. set: function (value) {
  12423. this._numberOfBricksHeight = value;
  12424. this.updateShaderUniforms();
  12425. },
  12426. enumerable: true,
  12427. configurable: true
  12428. });
  12429. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  12430. get: function () {
  12431. return this._jointColor;
  12432. },
  12433. set: function (value) {
  12434. this._jointColor = value;
  12435. this.updateShaderUniforms();
  12436. },
  12437. enumerable: true,
  12438. configurable: true
  12439. });
  12440. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  12441. get: function () {
  12442. return this._brickColor;
  12443. },
  12444. set: function (value) {
  12445. this._brickColor = value;
  12446. this.updateShaderUniforms();
  12447. },
  12448. enumerable: true,
  12449. configurable: true
  12450. });
  12451. return BrickProceduralTexture;
  12452. })(BABYLON.ProceduralTexture);
  12453. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  12454. var MarbleProceduralTexture = (function (_super) {
  12455. __extends(MarbleProceduralTexture, _super);
  12456. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12457. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  12458. this._numberOfTilesHeight = 3;
  12459. this._numberOfTilesWidth = 3;
  12460. this._amplitude = 9.0;
  12461. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12462. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12463. this.updateShaderUniforms();
  12464. this.refreshRate = 0;
  12465. }
  12466. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  12467. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  12468. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  12469. this.setFloat("amplitude", this._amplitude);
  12470. this.setColor3("marbleColor", this._marbleColor);
  12471. this.setColor3("jointColor", this._jointColor);
  12472. };
  12473. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  12474. get: function () {
  12475. return this._numberOfTilesHeight;
  12476. },
  12477. set: function (value) {
  12478. this._numberOfTilesHeight = value;
  12479. this.updateShaderUniforms();
  12480. },
  12481. enumerable: true,
  12482. configurable: true
  12483. });
  12484. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  12485. get: function () {
  12486. return this._numberOfTilesWidth;
  12487. },
  12488. set: function (value) {
  12489. this._numberOfTilesWidth = value;
  12490. this.updateShaderUniforms();
  12491. },
  12492. enumerable: true,
  12493. configurable: true
  12494. });
  12495. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  12496. get: function () {
  12497. return this._jointColor;
  12498. },
  12499. set: function (value) {
  12500. this._jointColor = value;
  12501. this.updateShaderUniforms();
  12502. },
  12503. enumerable: true,
  12504. configurable: true
  12505. });
  12506. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  12507. get: function () {
  12508. return this._marbleColor;
  12509. },
  12510. set: function (value) {
  12511. this._marbleColor = value;
  12512. this.updateShaderUniforms();
  12513. },
  12514. enumerable: true,
  12515. configurable: true
  12516. });
  12517. return MarbleProceduralTexture;
  12518. })(BABYLON.ProceduralTexture);
  12519. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  12520. })(BABYLON || (BABYLON = {}));
  12521. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  12522. var BABYLON;
  12523. (function (BABYLON) {
  12524. var CustomProceduralTexture = (function (_super) {
  12525. __extends(CustomProceduralTexture, _super);
  12526. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  12527. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  12528. this._animate = true;
  12529. this._time = 0;
  12530. this._texturePath = texturePath;
  12531. //Try to load json
  12532. this.loadJson(texturePath);
  12533. this.refreshRate = 1;
  12534. }
  12535. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  12536. var _this = this;
  12537. var that = this;
  12538. function noConfigFile() {
  12539. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  12540. try {
  12541. that.setFragment(that._texturePath);
  12542. }
  12543. catch (ex) {
  12544. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  12545. }
  12546. }
  12547. var configFileUrl = jsonUrl + "/config.json";
  12548. var xhr = new XMLHttpRequest();
  12549. xhr.open("GET", configFileUrl, true);
  12550. xhr.addEventListener("load", function () {
  12551. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12552. try {
  12553. _this._config = JSON.parse(xhr.response);
  12554. _this.updateShaderUniforms();
  12555. _this.updateTextures();
  12556. _this.setFragment(_this._texturePath + "/custom");
  12557. _this._animate = _this._config.animate;
  12558. _this.refreshRate = _this._config.refreshrate;
  12559. }
  12560. catch (ex) {
  12561. noConfigFile();
  12562. }
  12563. }
  12564. else {
  12565. noConfigFile();
  12566. }
  12567. }, false);
  12568. xhr.addEventListener("error", function (event) {
  12569. noConfigFile();
  12570. }, false);
  12571. try {
  12572. xhr.send();
  12573. }
  12574. catch (ex) {
  12575. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  12576. }
  12577. };
  12578. CustomProceduralTexture.prototype.isReady = function () {
  12579. if (!_super.prototype.isReady.call(this)) {
  12580. return false;
  12581. }
  12582. for (var name in this._textures) {
  12583. var texture = this._textures[name];
  12584. if (!texture.isReady()) {
  12585. return false;
  12586. }
  12587. }
  12588. return true;
  12589. };
  12590. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12591. if (this._animate) {
  12592. this._time += this.getScene().getAnimationRatio() * 0.03;
  12593. this.updateShaderUniforms();
  12594. }
  12595. _super.prototype.render.call(this, useCameraPostProcess);
  12596. };
  12597. CustomProceduralTexture.prototype.updateTextures = function () {
  12598. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  12599. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  12600. }
  12601. };
  12602. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  12603. if (this._config) {
  12604. for (var j = 0; j < this._config.uniforms.length; j++) {
  12605. var uniform = this._config.uniforms[j];
  12606. switch (uniform.type) {
  12607. case "float":
  12608. this.setFloat(uniform.name, uniform.value);
  12609. break;
  12610. case "color3":
  12611. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  12612. break;
  12613. case "color4":
  12614. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  12615. break;
  12616. case "vector2":
  12617. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  12618. break;
  12619. case "vector3":
  12620. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  12621. break;
  12622. }
  12623. }
  12624. }
  12625. this.setFloat("time", this._time);
  12626. };
  12627. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  12628. get: function () {
  12629. return this._animate;
  12630. },
  12631. set: function (value) {
  12632. this._animate = value;
  12633. },
  12634. enumerable: true,
  12635. configurable: true
  12636. });
  12637. return CustomProceduralTexture;
  12638. })(BABYLON.ProceduralTexture);
  12639. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  12640. })(BABYLON || (BABYLON = {}));
  12641. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  12642. var BABYLON;
  12643. (function (BABYLON) {
  12644. var MirrorTexture = (function (_super) {
  12645. __extends(MirrorTexture, _super);
  12646. function MirrorTexture(name, size, scene, generateMipMaps) {
  12647. var _this = this;
  12648. _super.call(this, name, size, scene, generateMipMaps, true);
  12649. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  12650. this._transformMatrix = BABYLON.Matrix.Zero();
  12651. this._mirrorMatrix = BABYLON.Matrix.Zero();
  12652. this.onBeforeRender = function () {
  12653. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  12654. _this._savedViewMatrix = scene.getViewMatrix();
  12655. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  12656. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  12657. scene.clipPlane = _this.mirrorPlane;
  12658. scene.getEngine().cullBackFaces = false;
  12659. };
  12660. this.onAfterRender = function () {
  12661. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  12662. scene.getEngine().cullBackFaces = true;
  12663. delete scene.clipPlane;
  12664. };
  12665. }
  12666. MirrorTexture.prototype.clone = function () {
  12667. var textureSize = this.getSize();
  12668. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12669. // Base texture
  12670. newTexture.hasAlpha = this.hasAlpha;
  12671. newTexture.level = this.level;
  12672. // Mirror Texture
  12673. newTexture.mirrorPlane = this.mirrorPlane.clone();
  12674. newTexture.renderList = this.renderList.slice(0);
  12675. return newTexture;
  12676. };
  12677. return MirrorTexture;
  12678. })(BABYLON.RenderTargetTexture);
  12679. BABYLON.MirrorTexture = MirrorTexture;
  12680. })(BABYLON || (BABYLON = {}));
  12681. //# sourceMappingURL=babylon.mirrorTexture.js.map
  12682. var BABYLON;
  12683. (function (BABYLON) {
  12684. var DynamicTexture = (function (_super) {
  12685. __extends(DynamicTexture, _super);
  12686. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  12687. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12688. _super.call(this, null, scene, !generateMipMaps);
  12689. this.name = name;
  12690. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12691. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12692. this._generateMipMaps = generateMipMaps;
  12693. if (options.getContext) {
  12694. this._canvas = options;
  12695. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12696. }
  12697. else {
  12698. this._canvas = document.createElement("canvas");
  12699. if (options.width) {
  12700. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12701. }
  12702. else {
  12703. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  12704. }
  12705. }
  12706. var textureSize = this.getSize();
  12707. this._canvas.width = textureSize.width;
  12708. this._canvas.height = textureSize.height;
  12709. this._context = this._canvas.getContext("2d");
  12710. }
  12711. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  12712. get: function () {
  12713. return true;
  12714. },
  12715. enumerable: true,
  12716. configurable: true
  12717. });
  12718. DynamicTexture.prototype.scale = function (ratio) {
  12719. var textureSize = this.getSize();
  12720. textureSize.width *= ratio;
  12721. textureSize.height *= ratio;
  12722. this._canvas.width = textureSize.width;
  12723. this._canvas.height = textureSize.height;
  12724. this.releaseInternalTexture();
  12725. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  12726. };
  12727. DynamicTexture.prototype.getContext = function () {
  12728. return this._context;
  12729. };
  12730. DynamicTexture.prototype.clear = function () {
  12731. var size = this.getSize();
  12732. this._context.fillRect(0, 0, size.width, size.height);
  12733. };
  12734. DynamicTexture.prototype.update = function (invertY) {
  12735. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  12736. };
  12737. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  12738. if (update === void 0) { update = true; }
  12739. var size = this.getSize();
  12740. if (clearColor) {
  12741. this._context.fillStyle = clearColor;
  12742. this._context.fillRect(0, 0, size.width, size.height);
  12743. }
  12744. this._context.font = font;
  12745. if (x === null) {
  12746. var textSize = this._context.measureText(text);
  12747. x = (size.width - textSize.width) / 2;
  12748. }
  12749. this._context.fillStyle = color;
  12750. this._context.fillText(text, x, y);
  12751. if (update) {
  12752. this.update(invertY);
  12753. }
  12754. };
  12755. DynamicTexture.prototype.clone = function () {
  12756. var textureSize = this.getSize();
  12757. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12758. // Base texture
  12759. newTexture.hasAlpha = this.hasAlpha;
  12760. newTexture.level = this.level;
  12761. // Dynamic Texture
  12762. newTexture.wrapU = this.wrapU;
  12763. newTexture.wrapV = this.wrapV;
  12764. return newTexture;
  12765. };
  12766. return DynamicTexture;
  12767. })(BABYLON.Texture);
  12768. BABYLON.DynamicTexture = DynamicTexture;
  12769. })(BABYLON || (BABYLON = {}));
  12770. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12771. var BABYLON;
  12772. (function (BABYLON) {
  12773. var VideoTexture = (function (_super) {
  12774. __extends(VideoTexture, _super);
  12775. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12776. var _this = this;
  12777. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12778. _super.call(this, null, scene, !generateMipMaps, invertY);
  12779. this._autoLaunch = true;
  12780. this.name = name;
  12781. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12782. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12783. var requiredWidth = size.width || size;
  12784. var requiredHeight = size.height || size;
  12785. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12786. var textureSize = this.getSize();
  12787. this.video = document.createElement("video");
  12788. this.video.width = textureSize.width;
  12789. this.video.height = textureSize.height;
  12790. this.video.autoplay = false;
  12791. this.video.loop = true;
  12792. this.video.addEventListener("canplaythrough", function () {
  12793. if (_this._texture) {
  12794. _this._texture.isReady = true;
  12795. }
  12796. });
  12797. urls.forEach(function (url) {
  12798. var source = document.createElement("source");
  12799. source.src = url;
  12800. _this.video.appendChild(source);
  12801. });
  12802. this._lastUpdate = BABYLON.Tools.Now;
  12803. }
  12804. VideoTexture.prototype.update = function () {
  12805. if (this._autoLaunch) {
  12806. this._autoLaunch = false;
  12807. this.video.play();
  12808. }
  12809. var now = BABYLON.Tools.Now;
  12810. if (now - this._lastUpdate < 15) {
  12811. return false;
  12812. }
  12813. this._lastUpdate = now;
  12814. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  12815. return true;
  12816. };
  12817. return VideoTexture;
  12818. })(BABYLON.Texture);
  12819. BABYLON.VideoTexture = VideoTexture;
  12820. })(BABYLON || (BABYLON = {}));
  12821. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  12822. (function (BABYLON) {
  12823. var EffectFallbacks = (function () {
  12824. function EffectFallbacks() {
  12825. this._defines = {};
  12826. this._currentRank = 32;
  12827. this._maxRank = -1;
  12828. }
  12829. EffectFallbacks.prototype.addFallback = function (rank, define) {
  12830. if (!this._defines[rank]) {
  12831. if (rank < this._currentRank) {
  12832. this._currentRank = rank;
  12833. }
  12834. if (rank > this._maxRank) {
  12835. this._maxRank = rank;
  12836. }
  12837. this._defines[rank] = new Array();
  12838. }
  12839. this._defines[rank].push(define);
  12840. };
  12841. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  12842. get: function () {
  12843. return this._currentRank <= this._maxRank;
  12844. },
  12845. enumerable: true,
  12846. configurable: true
  12847. });
  12848. EffectFallbacks.prototype.reduce = function (currentDefines) {
  12849. var currentFallbacks = this._defines[this._currentRank];
  12850. for (var index = 0; index < currentFallbacks.length; index++) {
  12851. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  12852. }
  12853. this._currentRank++;
  12854. return currentDefines;
  12855. };
  12856. return EffectFallbacks;
  12857. })();
  12858. BABYLON.EffectFallbacks = EffectFallbacks;
  12859. var Effect = (function () {
  12860. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  12861. var _this = this;
  12862. this._isReady = false;
  12863. this._compilationError = "";
  12864. this._valueCache = [];
  12865. this._engine = engine;
  12866. this.name = baseName;
  12867. this.defines = defines;
  12868. this._uniformsNames = uniformsNames.concat(samplers);
  12869. this._samplers = samplers;
  12870. this._attributesNames = attributesNames;
  12871. this.onError = onError;
  12872. this.onCompiled = onCompiled;
  12873. var vertexSource;
  12874. var fragmentSource;
  12875. if (baseName.vertexElement) {
  12876. vertexSource = document.getElementById(baseName.vertexElement);
  12877. if (!vertexSource) {
  12878. vertexSource = baseName.vertexElement;
  12879. }
  12880. }
  12881. else {
  12882. vertexSource = baseName.vertex || baseName;
  12883. }
  12884. if (baseName.fragmentElement) {
  12885. fragmentSource = document.getElementById(baseName.fragmentElement);
  12886. if (!fragmentSource) {
  12887. fragmentSource = baseName.fragmentElement;
  12888. }
  12889. }
  12890. else {
  12891. fragmentSource = baseName.fragment || baseName;
  12892. }
  12893. this._loadVertexShader(vertexSource, function (vertexCode) {
  12894. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  12895. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  12896. });
  12897. });
  12898. }
  12899. // Properties
  12900. Effect.prototype.isReady = function () {
  12901. return this._isReady;
  12902. };
  12903. Effect.prototype.getProgram = function () {
  12904. return this._program;
  12905. };
  12906. Effect.prototype.getAttributesNames = function () {
  12907. return this._attributesNames;
  12908. };
  12909. Effect.prototype.getAttributeLocation = function (index) {
  12910. return this._attributes[index];
  12911. };
  12912. Effect.prototype.getAttributeLocationByName = function (name) {
  12913. var index = this._attributesNames.indexOf(name);
  12914. return this._attributes[index];
  12915. };
  12916. Effect.prototype.getAttributesCount = function () {
  12917. return this._attributes.length;
  12918. };
  12919. Effect.prototype.getUniformIndex = function (uniformName) {
  12920. return this._uniformsNames.indexOf(uniformName);
  12921. };
  12922. Effect.prototype.getUniform = function (uniformName) {
  12923. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  12924. };
  12925. Effect.prototype.getSamplers = function () {
  12926. return this._samplers;
  12927. };
  12928. Effect.prototype.getCompilationError = function () {
  12929. return this._compilationError;
  12930. };
  12931. // Methods
  12932. Effect.prototype._loadVertexShader = function (vertex, callback) {
  12933. // DOM element ?
  12934. if (vertex instanceof HTMLElement) {
  12935. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  12936. callback(vertexCode);
  12937. return;
  12938. }
  12939. // Is in local store ?
  12940. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  12941. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  12942. return;
  12943. }
  12944. var vertexShaderUrl;
  12945. if (vertex[0] === ".") {
  12946. vertexShaderUrl = vertex;
  12947. }
  12948. else {
  12949. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  12950. }
  12951. // Vertex shader
  12952. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  12953. };
  12954. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  12955. // DOM element ?
  12956. if (fragment instanceof HTMLElement) {
  12957. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  12958. callback(fragmentCode);
  12959. return;
  12960. }
  12961. // Is in local store ?
  12962. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  12963. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  12964. return;
  12965. }
  12966. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  12967. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  12968. return;
  12969. }
  12970. var fragmentShaderUrl;
  12971. if (fragment[0] === ".") {
  12972. fragmentShaderUrl = fragment;
  12973. }
  12974. else {
  12975. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  12976. }
  12977. // Fragment shader
  12978. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  12979. };
  12980. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  12981. try {
  12982. var engine = this._engine;
  12983. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  12984. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  12985. this._attributes = engine.getAttributes(this._program, attributesNames);
  12986. for (var index = 0; index < this._samplers.length; index++) {
  12987. var sampler = this.getUniform(this._samplers[index]);
  12988. if (sampler == null) {
  12989. this._samplers.splice(index, 1);
  12990. index--;
  12991. }
  12992. }
  12993. engine.bindSamplers(this);
  12994. this._isReady = true;
  12995. if (this.onCompiled) {
  12996. this.onCompiled(this);
  12997. }
  12998. }
  12999. catch (e) {
  13000. // Is it a problem with precision?
  13001. if (e.message.indexOf("highp") !== -1) {
  13002. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  13003. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  13004. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13005. return;
  13006. }
  13007. // Let's go through fallbacks then
  13008. if (fallbacks && fallbacks.isMoreFallbacks) {
  13009. defines = fallbacks.reduce(defines);
  13010. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13011. }
  13012. else {
  13013. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  13014. BABYLON.Tools.Error("Defines: " + defines);
  13015. BABYLON.Tools.Error("Error: " + e.message);
  13016. this._compilationError = e.message;
  13017. if (this.onError) {
  13018. this.onError(this, this._compilationError);
  13019. }
  13020. }
  13021. }
  13022. };
  13023. Effect.prototype._bindTexture = function (channel, texture) {
  13024. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  13025. };
  13026. Effect.prototype.setTexture = function (channel, texture) {
  13027. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  13028. };
  13029. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13030. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  13031. };
  13032. //public _cacheMatrix(uniformName, matrix) {
  13033. // if (!this._valueCache[uniformName]) {
  13034. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13035. // }
  13036. // for (var index = 0; index < 16; index++) {
  13037. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13038. // }
  13039. //};
  13040. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13041. if (!this._valueCache[uniformName]) {
  13042. this._valueCache[uniformName] = [x, y];
  13043. return;
  13044. }
  13045. this._valueCache[uniformName][0] = x;
  13046. this._valueCache[uniformName][1] = y;
  13047. };
  13048. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13049. if (!this._valueCache[uniformName]) {
  13050. this._valueCache[uniformName] = [x, y, z];
  13051. return;
  13052. }
  13053. this._valueCache[uniformName][0] = x;
  13054. this._valueCache[uniformName][1] = y;
  13055. this._valueCache[uniformName][2] = z;
  13056. };
  13057. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13058. if (!this._valueCache[uniformName]) {
  13059. this._valueCache[uniformName] = [x, y, z, w];
  13060. return;
  13061. }
  13062. this._valueCache[uniformName][0] = x;
  13063. this._valueCache[uniformName][1] = y;
  13064. this._valueCache[uniformName][2] = z;
  13065. this._valueCache[uniformName][3] = w;
  13066. };
  13067. Effect.prototype.setArray = function (uniformName, array) {
  13068. this._engine.setArray(this.getUniform(uniformName), array);
  13069. return this;
  13070. };
  13071. Effect.prototype.setArray2 = function (uniformName, array) {
  13072. this._engine.setArray2(this.getUniform(uniformName), array);
  13073. return this;
  13074. };
  13075. Effect.prototype.setArray3 = function (uniformName, array) {
  13076. this._engine.setArray3(this.getUniform(uniformName), array);
  13077. return this;
  13078. };
  13079. Effect.prototype.setArray4 = function (uniformName, array) {
  13080. this._engine.setArray4(this.getUniform(uniformName), array);
  13081. return this;
  13082. };
  13083. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13084. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13085. return this;
  13086. };
  13087. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13088. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13089. // return;
  13090. //this._cacheMatrix(uniformName, matrix);
  13091. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13092. return this;
  13093. };
  13094. Effect.prototype.setFloat = function (uniformName, value) {
  13095. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13096. return this;
  13097. this._valueCache[uniformName] = value;
  13098. this._engine.setFloat(this.getUniform(uniformName), value);
  13099. return this;
  13100. };
  13101. Effect.prototype.setBool = function (uniformName, bool) {
  13102. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13103. return this;
  13104. this._valueCache[uniformName] = bool;
  13105. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13106. return this;
  13107. };
  13108. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13109. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13110. return this;
  13111. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13112. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13113. return this;
  13114. };
  13115. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13116. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13117. return this;
  13118. this._cacheFloat2(uniformName, x, y);
  13119. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13120. return this;
  13121. };
  13122. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13123. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13124. return this;
  13125. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13126. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13127. return this;
  13128. };
  13129. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13130. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13131. return this;
  13132. this._cacheFloat3(uniformName, x, y, z);
  13133. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13134. return this;
  13135. };
  13136. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13137. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13138. return this;
  13139. this._cacheFloat4(uniformName, x, y, z, w);
  13140. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13141. return this;
  13142. };
  13143. Effect.prototype.setColor3 = function (uniformName, color3) {
  13144. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13145. return this;
  13146. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13147. this._engine.setColor3(this.getUniform(uniformName), color3);
  13148. return this;
  13149. };
  13150. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13151. 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)
  13152. return this;
  13153. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13154. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13155. return this;
  13156. };
  13157. // Statics
  13158. 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}",
  13159. 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}",
  13160. 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}",
  13161. 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}",
  13162. 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}",
  13163. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13164. 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}",
  13165. 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}",
  13166. 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}",
  13167. 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}",
  13168. 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}",
  13169. 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}",
  13170. 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}",
  13171. 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}",
  13172. 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}",
  13173. 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}",
  13174. 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}",
  13175. 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}",
  13176. 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}",
  13177. 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}",
  13178. 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}",
  13179. 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}",
  13180. 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}",
  13181. 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}",
  13182. 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}",
  13183. 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}",
  13184. 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}",
  13185. 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}",
  13186. 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}",
  13187. 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}",
  13188. 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}",
  13189. 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}",
  13190. 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}",
  13191. 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}",
  13192. 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}",
  13193. 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}",
  13194. 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}",
  13195. 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}",
  13196. ssaoPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\n\nuniform vec3 sampleSphere[16];\n\nvarying vec2 vUV;\n\nvec3 normalFromDepth(float depth, vec2 coords) {\n const vec2 offset1 = vec2(0.0, 0.001);\n const vec2 offset2 = vec2(0.001, 0.0);\n\n float depth1 = texture2D(textureSampler, coords + offset1).r;\n float depth2 = texture2D(textureSampler, coords + offset2).r;\n\n vec3 p1 = vec3(offset1, depth1 - depth);\n vec3 p2 = vec3(offset2, depth2 - depth);\n\n vec3 normal = cross(p1, p2);\n normal.z = -normal.z;\n\n return normalize(normal);\n}\n\nvoid main(void) {\n\n const float totalStrength = 1.0;\n const float base = 0.2;\n const float area = 0.0075;\n const float fallOff = 0.000001;\n const float radius = 0.002;\n\n vec3 random = normalize(texture2D(randomSampler, vUV * 4.0).rgb);\n float depth = texture2D(textureSampler, vUV).r;\n\n vec3 position = vec3(vUV, depth);\n vec3 normal = normalFromDepth(depth, vUV);\n\n float radiusDepth = radius / depth;\n float occlusion = 0.0;\n\n const int samples = 16;\n for (int i = 0; i < samples; i++) {\n vec3 ray = radiusDepth * reflect(sampleSphere[i], random);\n vec3 hemiRay = position + sign(dot(ray, normal)) * ray;\n\n float occlusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\n float difference = depth - occlusionDepth;\n\n occlusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\n }\n\n float ao = 1.0 - totalStrength * occlusion * (1.0 / float(samples));\n\n float result = clamp(ao + base, 0.0, 1.0);\n gl_FragColor.r = result;\n gl_FragColor.g = result;\n gl_FragColor.b = result;\n gl_FragColor.a = 1.0;\n\n}",
  13197. ssaoCombinePixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D originalColor;\n\nvarying vec2 vUV;\n\nvoid main(void) {\n gl_FragColor = texture2D(textureSampler, vUV) * texture2D(originalColor, vUV);\n}",
  13198. 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}",
  13199. };
  13200. return Effect;
  13201. })();
  13202. BABYLON.Effect = Effect;
  13203. })(BABYLON || (BABYLON = {}));
  13204. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13205. (function (BABYLON) {
  13206. var Material = (function () {
  13207. function Material(name, scene, doNotAdd) {
  13208. this.name = name;
  13209. this.checkReadyOnEveryCall = true;
  13210. this.checkReadyOnlyOnce = false;
  13211. this.state = "";
  13212. this.alpha = 1.0;
  13213. this.backFaceCulling = true;
  13214. this._wasPreviouslyReady = false;
  13215. this._fillMode = Material.TriangleFillMode;
  13216. this.pointSize = 1.0;
  13217. this.id = name;
  13218. this._scene = scene;
  13219. if (!doNotAdd) {
  13220. scene.materials.push(this);
  13221. }
  13222. }
  13223. Object.defineProperty(Material, "TriangleFillMode", {
  13224. get: function () {
  13225. return Material._TriangleFillMode;
  13226. },
  13227. enumerable: true,
  13228. configurable: true
  13229. });
  13230. Object.defineProperty(Material, "WireFrameFillMode", {
  13231. get: function () {
  13232. return Material._WireFrameFillMode;
  13233. },
  13234. enumerable: true,
  13235. configurable: true
  13236. });
  13237. Object.defineProperty(Material, "PointFillMode", {
  13238. get: function () {
  13239. return Material._PointFillMode;
  13240. },
  13241. enumerable: true,
  13242. configurable: true
  13243. });
  13244. Object.defineProperty(Material.prototype, "wireframe", {
  13245. get: function () {
  13246. return this._fillMode === Material.WireFrameFillMode;
  13247. },
  13248. set: function (value) {
  13249. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13250. },
  13251. enumerable: true,
  13252. configurable: true
  13253. });
  13254. Object.defineProperty(Material.prototype, "pointsCloud", {
  13255. get: function () {
  13256. return this._fillMode === Material.PointFillMode;
  13257. },
  13258. set: function (value) {
  13259. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13260. },
  13261. enumerable: true,
  13262. configurable: true
  13263. });
  13264. Object.defineProperty(Material.prototype, "fillMode", {
  13265. get: function () {
  13266. return this._fillMode;
  13267. },
  13268. set: function (value) {
  13269. this._fillMode = value;
  13270. },
  13271. enumerable: true,
  13272. configurable: true
  13273. });
  13274. Material.prototype.isReady = function (mesh, useInstances) {
  13275. return true;
  13276. };
  13277. Material.prototype.getEffect = function () {
  13278. return this._effect;
  13279. };
  13280. Material.prototype.getScene = function () {
  13281. return this._scene;
  13282. };
  13283. Material.prototype.needAlphaBlending = function () {
  13284. return (this.alpha < 1.0);
  13285. };
  13286. Material.prototype.needAlphaTesting = function () {
  13287. return false;
  13288. };
  13289. Material.prototype.getAlphaTestTexture = function () {
  13290. return null;
  13291. };
  13292. Material.prototype.trackCreation = function (onCompiled, onError) {
  13293. };
  13294. Material.prototype._preBind = function () {
  13295. var engine = this._scene.getEngine();
  13296. engine.enableEffect(this._effect);
  13297. engine.setState(this.backFaceCulling);
  13298. };
  13299. Material.prototype.bind = function (world, mesh) {
  13300. this._scene._cachedMaterial = this;
  13301. if (this.onBind) {
  13302. this.onBind(this);
  13303. }
  13304. };
  13305. Material.prototype.bindOnlyWorldMatrix = function (world) {
  13306. };
  13307. Material.prototype.unbind = function () {
  13308. };
  13309. Material.prototype.dispose = function (forceDisposeEffect) {
  13310. // Remove from scene
  13311. var index = this._scene.materials.indexOf(this);
  13312. this._scene.materials.splice(index, 1);
  13313. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  13314. if (forceDisposeEffect && this._effect) {
  13315. this._scene.getEngine()._releaseEffect(this._effect);
  13316. this._effect = null;
  13317. }
  13318. // Callback
  13319. if (this.onDispose) {
  13320. this.onDispose();
  13321. }
  13322. };
  13323. Material._TriangleFillMode = 0;
  13324. Material._WireFrameFillMode = 1;
  13325. Material._PointFillMode = 2;
  13326. return Material;
  13327. })();
  13328. BABYLON.Material = Material;
  13329. })(BABYLON || (BABYLON = {}));
  13330. //# sourceMappingURL=babylon.material.js.map
  13331. var BABYLON;
  13332. (function (BABYLON) {
  13333. var maxSimultaneousLights = 4;
  13334. var FresnelParameters = (function () {
  13335. function FresnelParameters() {
  13336. this.isEnabled = true;
  13337. this.leftColor = BABYLON.Color3.White();
  13338. this.rightColor = BABYLON.Color3.Black();
  13339. this.bias = 0;
  13340. this.power = 1;
  13341. }
  13342. return FresnelParameters;
  13343. })();
  13344. BABYLON.FresnelParameters = FresnelParameters;
  13345. var StandardMaterial = (function (_super) {
  13346. __extends(StandardMaterial, _super);
  13347. function StandardMaterial(name, scene) {
  13348. var _this = this;
  13349. _super.call(this, name, scene);
  13350. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13351. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  13352. this.specularColor = new BABYLON.Color3(1, 1, 1);
  13353. this.specularPower = 64;
  13354. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  13355. this.useAlphaFromDiffuseTexture = false;
  13356. this.useSpecularOverAlpha = true;
  13357. this.fogEnabled = true;
  13358. this._cachedDefines = null;
  13359. this._renderTargets = new BABYLON.SmartArray(16);
  13360. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  13361. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  13362. this._scaledDiffuse = new BABYLON.Color3();
  13363. this._scaledSpecular = new BABYLON.Color3();
  13364. this.getRenderTargetTextures = function () {
  13365. _this._renderTargets.reset();
  13366. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  13367. _this._renderTargets.push(_this.reflectionTexture);
  13368. }
  13369. return _this._renderTargets;
  13370. };
  13371. }
  13372. StandardMaterial.prototype.needAlphaBlending = function () {
  13373. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  13374. };
  13375. StandardMaterial.prototype.needAlphaTesting = function () {
  13376. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  13377. };
  13378. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  13379. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  13380. };
  13381. StandardMaterial.prototype.getAlphaTestTexture = function () {
  13382. return this.diffuseTexture;
  13383. };
  13384. // Methods
  13385. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  13386. if (this.checkReadyOnlyOnce) {
  13387. if (this._wasPreviouslyReady) {
  13388. return true;
  13389. }
  13390. }
  13391. var scene = this.getScene();
  13392. if (!this.checkReadyOnEveryCall) {
  13393. if (this._renderId === scene.getRenderId()) {
  13394. return true;
  13395. }
  13396. }
  13397. var engine = scene.getEngine();
  13398. var defines = [];
  13399. var fallbacks = new BABYLON.EffectFallbacks();
  13400. // Textures
  13401. if (scene.texturesEnabled) {
  13402. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13403. if (!this.diffuseTexture.isReady()) {
  13404. return false;
  13405. }
  13406. else {
  13407. defines.push("#define DIFFUSE");
  13408. }
  13409. }
  13410. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13411. if (!this.ambientTexture.isReady()) {
  13412. return false;
  13413. }
  13414. else {
  13415. defines.push("#define AMBIENT");
  13416. }
  13417. }
  13418. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13419. if (!this.opacityTexture.isReady()) {
  13420. return false;
  13421. }
  13422. else {
  13423. defines.push("#define OPACITY");
  13424. if (this.opacityTexture.getAlphaFromRGB) {
  13425. defines.push("#define OPACITYRGB");
  13426. }
  13427. }
  13428. }
  13429. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13430. if (!this.reflectionTexture.isReady()) {
  13431. return false;
  13432. }
  13433. else {
  13434. defines.push("#define REFLECTION");
  13435. fallbacks.addFallback(0, "REFLECTION");
  13436. }
  13437. }
  13438. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13439. if (!this.emissiveTexture.isReady()) {
  13440. return false;
  13441. }
  13442. else {
  13443. defines.push("#define EMISSIVE");
  13444. }
  13445. }
  13446. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13447. if (!this.specularTexture.isReady()) {
  13448. return false;
  13449. }
  13450. else {
  13451. defines.push("#define SPECULAR");
  13452. fallbacks.addFallback(0, "SPECULAR");
  13453. }
  13454. }
  13455. }
  13456. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  13457. if (!this.bumpTexture.isReady()) {
  13458. return false;
  13459. }
  13460. else {
  13461. defines.push("#define BUMP");
  13462. fallbacks.addFallback(0, "BUMP");
  13463. }
  13464. }
  13465. // Effect
  13466. if (this.useSpecularOverAlpha) {
  13467. defines.push("#define SPECULAROVERALPHA");
  13468. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  13469. }
  13470. if (scene.clipPlane) {
  13471. defines.push("#define CLIPPLANE");
  13472. }
  13473. if (engine.getAlphaTesting()) {
  13474. defines.push("#define ALPHATEST");
  13475. }
  13476. if (this._shouldUseAlphaFromDiffuseTexture()) {
  13477. defines.push("#define ALPHAFROMDIFFUSE");
  13478. }
  13479. // Point size
  13480. if (this.pointsCloud || scene.forcePointsCloud) {
  13481. defines.push("#define POINTSIZE");
  13482. }
  13483. // Fog
  13484. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13485. defines.push("#define FOG");
  13486. fallbacks.addFallback(1, "FOG");
  13487. }
  13488. var shadowsActivated = false;
  13489. var lightIndex = 0;
  13490. if (scene.lightsEnabled) {
  13491. for (var index = 0; index < scene.lights.length; index++) {
  13492. var light = scene.lights[index];
  13493. if (!light.isEnabled()) {
  13494. continue;
  13495. }
  13496. // Excluded check
  13497. if (light._excludedMeshesIds.length > 0) {
  13498. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  13499. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  13500. if (excludedMesh) {
  13501. light.excludedMeshes.push(excludedMesh);
  13502. }
  13503. }
  13504. light._excludedMeshesIds = [];
  13505. }
  13506. // Included check
  13507. if (light._includedOnlyMeshesIds.length > 0) {
  13508. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  13509. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  13510. if (includedOnlyMesh) {
  13511. light.includedOnlyMeshes.push(includedOnlyMesh);
  13512. }
  13513. }
  13514. light._includedOnlyMeshesIds = [];
  13515. }
  13516. if (!light.canAffectMesh(mesh)) {
  13517. continue;
  13518. }
  13519. defines.push("#define LIGHT" + lightIndex);
  13520. if (lightIndex > 0) {
  13521. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  13522. }
  13523. var type;
  13524. if (light instanceof BABYLON.SpotLight) {
  13525. type = "#define SPOTLIGHT" + lightIndex;
  13526. }
  13527. else if (light instanceof BABYLON.HemisphericLight) {
  13528. type = "#define HEMILIGHT" + lightIndex;
  13529. }
  13530. else {
  13531. type = "#define POINTDIRLIGHT" + lightIndex;
  13532. }
  13533. defines.push(type);
  13534. if (lightIndex > 0) {
  13535. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  13536. }
  13537. // Shadows
  13538. if (scene.shadowsEnabled) {
  13539. var shadowGenerator = light.getShadowGenerator();
  13540. if (mesh && mesh.receiveShadows && shadowGenerator) {
  13541. defines.push("#define SHADOW" + lightIndex);
  13542. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  13543. if (!shadowsActivated) {
  13544. defines.push("#define SHADOWS");
  13545. shadowsActivated = true;
  13546. }
  13547. if (shadowGenerator.useVarianceShadowMap) {
  13548. defines.push("#define SHADOWVSM" + lightIndex);
  13549. if (lightIndex > 0) {
  13550. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  13551. }
  13552. }
  13553. if (shadowGenerator.usePoissonSampling) {
  13554. defines.push("#define SHADOWPCF" + lightIndex);
  13555. if (lightIndex > 0) {
  13556. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  13557. }
  13558. }
  13559. }
  13560. }
  13561. lightIndex++;
  13562. if (lightIndex === maxSimultaneousLights)
  13563. break;
  13564. }
  13565. }
  13566. if (StandardMaterial.FresnelEnabled) {
  13567. // Fresnel
  13568. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13569. var fresnelRank = 1;
  13570. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13571. defines.push("#define DIFFUSEFRESNEL");
  13572. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  13573. fresnelRank++;
  13574. }
  13575. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13576. defines.push("#define OPACITYFRESNEL");
  13577. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  13578. fresnelRank++;
  13579. }
  13580. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13581. defines.push("#define REFLECTIONFRESNEL");
  13582. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  13583. fresnelRank++;
  13584. }
  13585. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13586. defines.push("#define EMISSIVEFRESNEL");
  13587. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  13588. fresnelRank++;
  13589. }
  13590. defines.push("#define FRESNEL");
  13591. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  13592. }
  13593. }
  13594. // Attribs
  13595. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  13596. if (mesh) {
  13597. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13598. attribs.push(BABYLON.VertexBuffer.UVKind);
  13599. defines.push("#define UV1");
  13600. }
  13601. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13602. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  13603. defines.push("#define UV2");
  13604. }
  13605. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13606. attribs.push(BABYLON.VertexBuffer.ColorKind);
  13607. defines.push("#define VERTEXCOLOR");
  13608. if (mesh.hasVertexAlpha) {
  13609. defines.push("#define VERTEXALPHA");
  13610. }
  13611. }
  13612. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13613. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13614. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13615. defines.push("#define BONES");
  13616. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13617. defines.push("#define BONES4");
  13618. fallbacks.addFallback(0, "BONES4");
  13619. }
  13620. // Instances
  13621. if (useInstances) {
  13622. defines.push("#define INSTANCES");
  13623. attribs.push("world0");
  13624. attribs.push("world1");
  13625. attribs.push("world2");
  13626. attribs.push("world3");
  13627. }
  13628. }
  13629. // Get correct effect
  13630. var join = defines.join("\n");
  13631. if (this._cachedDefines !== join) {
  13632. this._cachedDefines = join;
  13633. scene.resetCachedMaterial();
  13634. // Legacy browser patch
  13635. var shaderName = "default";
  13636. if (!scene.getEngine().getCaps().standardDerivatives) {
  13637. shaderName = "legacydefault";
  13638. }
  13639. 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);
  13640. }
  13641. if (!this._effect.isReady()) {
  13642. return false;
  13643. }
  13644. this._renderId = scene.getRenderId();
  13645. this._wasPreviouslyReady = true;
  13646. return true;
  13647. };
  13648. StandardMaterial.prototype.unbind = function () {
  13649. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  13650. this._effect.setTexture("reflection2DSampler", null);
  13651. }
  13652. };
  13653. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  13654. this._effect.setMatrix("world", world);
  13655. };
  13656. StandardMaterial.prototype.bind = function (world, mesh) {
  13657. var scene = this.getScene();
  13658. // Matrices
  13659. this.bindOnlyWorldMatrix(world);
  13660. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  13661. // Bones
  13662. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13663. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  13664. }
  13665. if (scene.getCachedMaterial() !== this) {
  13666. if (StandardMaterial.FresnelEnabled) {
  13667. // Fresnel
  13668. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13669. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  13670. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  13671. }
  13672. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13673. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  13674. }
  13675. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13676. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  13677. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  13678. }
  13679. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13680. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  13681. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  13682. }
  13683. }
  13684. // Textures
  13685. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13686. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  13687. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  13688. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  13689. }
  13690. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13691. this._effect.setTexture("ambientSampler", this.ambientTexture);
  13692. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  13693. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  13694. }
  13695. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13696. this._effect.setTexture("opacitySampler", this.opacityTexture);
  13697. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  13698. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  13699. }
  13700. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13701. if (this.reflectionTexture.isCube) {
  13702. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  13703. }
  13704. else {
  13705. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  13706. }
  13707. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  13708. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  13709. }
  13710. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13711. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  13712. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  13713. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  13714. }
  13715. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13716. this._effect.setTexture("specularSampler", this.specularTexture);
  13717. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  13718. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  13719. }
  13720. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  13721. this._effect.setTexture("bumpSampler", this.bumpTexture);
  13722. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  13723. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  13724. }
  13725. // Clip plane
  13726. if (scene.clipPlane) {
  13727. var clipPlane = scene.clipPlane;
  13728. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13729. }
  13730. // Point size
  13731. if (this.pointsCloud) {
  13732. this._effect.setFloat("pointSize", this.pointSize);
  13733. }
  13734. // Colors
  13735. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  13736. // Scaling down color according to emissive
  13737. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13738. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13739. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13740. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  13741. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  13742. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  13743. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  13744. }
  13745. // Scaling down color according to emissive
  13746. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13747. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13748. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13749. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  13750. if (scene.lightsEnabled) {
  13751. var lightIndex = 0;
  13752. for (var index = 0; index < scene.lights.length; index++) {
  13753. var light = scene.lights[index];
  13754. if (!light.isEnabled()) {
  13755. continue;
  13756. }
  13757. if (!light.canAffectMesh(mesh)) {
  13758. continue;
  13759. }
  13760. if (light instanceof BABYLON.PointLight) {
  13761. // Point Light
  13762. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13763. }
  13764. else if (light instanceof BABYLON.DirectionalLight) {
  13765. // Directional Light
  13766. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13767. }
  13768. else if (light instanceof BABYLON.SpotLight) {
  13769. // Spot Light
  13770. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  13771. }
  13772. else if (light instanceof BABYLON.HemisphericLight) {
  13773. // Hemispheric Light
  13774. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  13775. }
  13776. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  13777. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  13778. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  13779. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  13780. // Shadows
  13781. if (scene.shadowsEnabled) {
  13782. var shadowGenerator = light.getShadowGenerator();
  13783. if (mesh.receiveShadows && shadowGenerator) {
  13784. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13785. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13786. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13787. }
  13788. }
  13789. lightIndex++;
  13790. if (lightIndex === maxSimultaneousLights)
  13791. break;
  13792. }
  13793. }
  13794. // View
  13795. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13796. this._effect.setMatrix("view", scene.getViewMatrix());
  13797. }
  13798. // Fog
  13799. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13800. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13801. this._effect.setColor3("vFogColor", scene.fogColor);
  13802. }
  13803. _super.prototype.bind.call(this, world, mesh);
  13804. };
  13805. StandardMaterial.prototype.getAnimatables = function () {
  13806. var results = [];
  13807. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  13808. results.push(this.diffuseTexture);
  13809. }
  13810. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  13811. results.push(this.ambientTexture);
  13812. }
  13813. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  13814. results.push(this.opacityTexture);
  13815. }
  13816. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  13817. results.push(this.reflectionTexture);
  13818. }
  13819. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  13820. results.push(this.emissiveTexture);
  13821. }
  13822. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  13823. results.push(this.specularTexture);
  13824. }
  13825. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  13826. results.push(this.bumpTexture);
  13827. }
  13828. return results;
  13829. };
  13830. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  13831. if (this.diffuseTexture) {
  13832. this.diffuseTexture.dispose();
  13833. }
  13834. if (this.ambientTexture) {
  13835. this.ambientTexture.dispose();
  13836. }
  13837. if (this.opacityTexture) {
  13838. this.opacityTexture.dispose();
  13839. }
  13840. if (this.reflectionTexture) {
  13841. this.reflectionTexture.dispose();
  13842. }
  13843. if (this.emissiveTexture) {
  13844. this.emissiveTexture.dispose();
  13845. }
  13846. if (this.specularTexture) {
  13847. this.specularTexture.dispose();
  13848. }
  13849. if (this.bumpTexture) {
  13850. this.bumpTexture.dispose();
  13851. }
  13852. _super.prototype.dispose.call(this, forceDisposeEffect);
  13853. };
  13854. StandardMaterial.prototype.clone = function (name) {
  13855. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  13856. // Base material
  13857. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  13858. newStandardMaterial.alpha = this.alpha;
  13859. newStandardMaterial.fillMode = this.fillMode;
  13860. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  13861. // Standard material
  13862. if (this.diffuseTexture && this.diffuseTexture.clone) {
  13863. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  13864. }
  13865. if (this.ambientTexture && this.ambientTexture.clone) {
  13866. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  13867. }
  13868. if (this.opacityTexture && this.opacityTexture.clone) {
  13869. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  13870. }
  13871. if (this.reflectionTexture && this.reflectionTexture.clone) {
  13872. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  13873. }
  13874. if (this.emissiveTexture && this.emissiveTexture.clone) {
  13875. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  13876. }
  13877. if (this.specularTexture && this.specularTexture.clone) {
  13878. newStandardMaterial.specularTexture = this.specularTexture.clone();
  13879. }
  13880. if (this.bumpTexture && this.bumpTexture.clone) {
  13881. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  13882. }
  13883. newStandardMaterial.ambientColor = this.ambientColor.clone();
  13884. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  13885. newStandardMaterial.specularColor = this.specularColor.clone();
  13886. newStandardMaterial.specularPower = this.specularPower;
  13887. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  13888. return newStandardMaterial;
  13889. };
  13890. // Statics
  13891. // Flags used to enable or disable a type of texture for all Standard Materials
  13892. StandardMaterial.DiffuseTextureEnabled = true;
  13893. StandardMaterial.AmbientTextureEnabled = true;
  13894. StandardMaterial.OpacityTextureEnabled = true;
  13895. StandardMaterial.ReflectionTextureEnabled = true;
  13896. StandardMaterial.EmissiveTextureEnabled = true;
  13897. StandardMaterial.SpecularTextureEnabled = true;
  13898. StandardMaterial.BumpTextureEnabled = true;
  13899. StandardMaterial.FresnelEnabled = true;
  13900. return StandardMaterial;
  13901. })(BABYLON.Material);
  13902. BABYLON.StandardMaterial = StandardMaterial;
  13903. })(BABYLON || (BABYLON = {}));
  13904. //# sourceMappingURL=babylon.standardMaterial.js.map
  13905. var BABYLON;
  13906. (function (BABYLON) {
  13907. var MultiMaterial = (function (_super) {
  13908. __extends(MultiMaterial, _super);
  13909. function MultiMaterial(name, scene) {
  13910. _super.call(this, name, scene, true);
  13911. this.subMaterials = new Array();
  13912. scene.multiMaterials.push(this);
  13913. }
  13914. // Properties
  13915. MultiMaterial.prototype.getSubMaterial = function (index) {
  13916. if (index < 0 || index >= this.subMaterials.length) {
  13917. return this.getScene().defaultMaterial;
  13918. }
  13919. return this.subMaterials[index];
  13920. };
  13921. // Methods
  13922. MultiMaterial.prototype.isReady = function (mesh) {
  13923. for (var index = 0; index < this.subMaterials.length; index++) {
  13924. var subMaterial = this.subMaterials[index];
  13925. if (subMaterial) {
  13926. if (!this.subMaterials[index].isReady(mesh)) {
  13927. return false;
  13928. }
  13929. }
  13930. }
  13931. return true;
  13932. };
  13933. return MultiMaterial;
  13934. })(BABYLON.Material);
  13935. BABYLON.MultiMaterial = MultiMaterial;
  13936. })(BABYLON || (BABYLON = {}));
  13937. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  13938. (function (BABYLON) {
  13939. var Database = (function () {
  13940. function Database(urlToScene, callbackManifestChecked) {
  13941. // Handling various flavors of prefixed version of IndexedDB
  13942. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  13943. this.callbackManifestChecked = callbackManifestChecked;
  13944. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  13945. this.db = null;
  13946. this.enableSceneOffline = false;
  13947. this.enableTexturesOffline = false;
  13948. this.manifestVersionFound = 0;
  13949. this.mustUpdateRessources = false;
  13950. this.hasReachedQuota = false;
  13951. this.checkManifestFile();
  13952. }
  13953. Database.prototype.checkManifestFile = function () {
  13954. var _this = this;
  13955. function noManifestFile() {
  13956. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  13957. that.enableSceneOffline = false;
  13958. that.enableTexturesOffline = false;
  13959. that.callbackManifestChecked(false);
  13960. }
  13961. var that = this;
  13962. var manifestURL = this.currentSceneUrl + ".manifest";
  13963. var xhr = new XMLHttpRequest();
  13964. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  13965. xhr.open("GET", manifestURLTimeStamped, true);
  13966. xhr.addEventListener("load", function () {
  13967. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13968. try {
  13969. var manifestFile = JSON.parse(xhr.response);
  13970. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  13971. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  13972. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  13973. _this.manifestVersionFound = manifestFile.version;
  13974. }
  13975. if (_this.callbackManifestChecked) {
  13976. _this.callbackManifestChecked(true);
  13977. }
  13978. }
  13979. catch (ex) {
  13980. noManifestFile();
  13981. }
  13982. }
  13983. else {
  13984. noManifestFile();
  13985. }
  13986. }, false);
  13987. xhr.addEventListener("error", function (event) {
  13988. noManifestFile();
  13989. }, false);
  13990. try {
  13991. xhr.send();
  13992. }
  13993. catch (ex) {
  13994. BABYLON.Tools.Error("Error on XHR send request.");
  13995. that.callbackManifestChecked(false);
  13996. }
  13997. };
  13998. Database.prototype.openAsync = function (successCallback, errorCallback) {
  13999. var _this = this;
  14000. function handleError() {
  14001. that.isSupported = false;
  14002. if (errorCallback)
  14003. errorCallback();
  14004. }
  14005. var that = this;
  14006. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  14007. // Your browser doesn't support IndexedDB
  14008. this.isSupported = false;
  14009. if (errorCallback)
  14010. errorCallback();
  14011. }
  14012. else {
  14013. // If the DB hasn't been opened or created yet
  14014. if (!this.db) {
  14015. this.hasReachedQuota = false;
  14016. this.isSupported = true;
  14017. var request = this.idbFactory.open("babylonjs", 1);
  14018. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  14019. request.onerror = function (event) {
  14020. handleError();
  14021. };
  14022. // executes when a version change transaction cannot complete due to other active transactions
  14023. request.onblocked = function (event) {
  14024. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  14025. handleError();
  14026. };
  14027. // DB has been opened successfully
  14028. request.onsuccess = function (event) {
  14029. _this.db = request.result;
  14030. successCallback();
  14031. };
  14032. // Initialization of the DB. Creating Scenes & Textures stores
  14033. request.onupgradeneeded = function (event) {
  14034. _this.db = (event.target).result;
  14035. try {
  14036. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  14037. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  14038. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  14039. }
  14040. catch (ex) {
  14041. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  14042. handleError();
  14043. }
  14044. };
  14045. }
  14046. else {
  14047. if (successCallback)
  14048. successCallback();
  14049. }
  14050. }
  14051. };
  14052. Database.prototype.loadImageFromDB = function (url, image) {
  14053. var _this = this;
  14054. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  14055. var saveAndLoadImage = function () {
  14056. if (!_this.hasReachedQuota && _this.db !== null) {
  14057. // the texture is not yet in the DB, let's try to save it
  14058. _this._saveImageIntoDBAsync(completeURL, image);
  14059. }
  14060. else {
  14061. image.src = url;
  14062. }
  14063. };
  14064. if (!this.mustUpdateRessources) {
  14065. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14066. }
  14067. else {
  14068. saveAndLoadImage();
  14069. }
  14070. };
  14071. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14072. if (this.isSupported && this.db !== null) {
  14073. var texture;
  14074. var transaction = this.db.transaction(["textures"]);
  14075. transaction.onabort = function (event) {
  14076. image.src = url;
  14077. };
  14078. transaction.oncomplete = function (event) {
  14079. var blobTextureURL;
  14080. if (texture) {
  14081. var URL = window.URL || window.webkitURL;
  14082. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14083. image.onerror = function () {
  14084. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14085. image.src = url;
  14086. };
  14087. image.src = blobTextureURL;
  14088. }
  14089. else {
  14090. notInDBCallback();
  14091. }
  14092. };
  14093. var getRequest = transaction.objectStore("textures").get(url);
  14094. getRequest.onsuccess = function (event) {
  14095. texture = (event.target).result;
  14096. };
  14097. getRequest.onerror = function (event) {
  14098. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14099. image.src = url;
  14100. };
  14101. }
  14102. else {
  14103. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14104. image.src = url;
  14105. }
  14106. };
  14107. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14108. var _this = this;
  14109. if (this.isSupported) {
  14110. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14111. var generateBlobUrl = function () {
  14112. var blobTextureURL;
  14113. if (blob) {
  14114. var URL = window.URL || window.webkitURL;
  14115. try {
  14116. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14117. }
  14118. catch (ex) {
  14119. blobTextureURL = URL.createObjectURL(blob);
  14120. }
  14121. }
  14122. image.src = blobTextureURL;
  14123. };
  14124. if (BABYLON.Database.isUASupportingBlobStorage) {
  14125. var xhr = new XMLHttpRequest(), blob;
  14126. xhr.open("GET", url, true);
  14127. xhr.responseType = "blob";
  14128. xhr.addEventListener("load", function () {
  14129. if (xhr.status === 200) {
  14130. // Blob as response (XHR2)
  14131. blob = xhr.response;
  14132. var transaction = _this.db.transaction(["textures"], "readwrite");
  14133. // the transaction could abort because of a QuotaExceededError error
  14134. transaction.onabort = function (event) {
  14135. try {
  14136. if (event.srcElement.error.name === "QuotaExceededError") {
  14137. this.hasReachedQuota = true;
  14138. }
  14139. }
  14140. catch (ex) {
  14141. }
  14142. generateBlobUrl();
  14143. };
  14144. transaction.oncomplete = function (event) {
  14145. generateBlobUrl();
  14146. };
  14147. var newTexture = { textureUrl: url, data: blob };
  14148. try {
  14149. // Put the blob into the dabase
  14150. var addRequest = transaction.objectStore("textures").put(newTexture);
  14151. addRequest.onsuccess = function (event) {
  14152. };
  14153. addRequest.onerror = function (event) {
  14154. generateBlobUrl();
  14155. };
  14156. }
  14157. catch (ex) {
  14158. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14159. if (ex.code === 25) {
  14160. BABYLON.Database.isUASupportingBlobStorage = false;
  14161. }
  14162. image.src = url;
  14163. }
  14164. }
  14165. else {
  14166. image.src = url;
  14167. }
  14168. }, false);
  14169. xhr.addEventListener("error", function (event) {
  14170. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14171. image.src = url;
  14172. }, false);
  14173. xhr.send();
  14174. }
  14175. else {
  14176. image.src = url;
  14177. }
  14178. }
  14179. else {
  14180. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14181. image.src = url;
  14182. }
  14183. };
  14184. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14185. var _this = this;
  14186. var updateVersion = function (event) {
  14187. // the version is not yet in the DB or we need to update it
  14188. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14189. };
  14190. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14191. };
  14192. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14193. var _this = this;
  14194. if (this.isSupported) {
  14195. var version;
  14196. try {
  14197. var transaction = this.db.transaction(["versions"]);
  14198. transaction.oncomplete = function (event) {
  14199. if (version) {
  14200. // If the version in the JSON file is > than the version in DB
  14201. if (_this.manifestVersionFound > version.data) {
  14202. _this.mustUpdateRessources = true;
  14203. updateInDBCallback();
  14204. }
  14205. else {
  14206. callback(version.data);
  14207. }
  14208. }
  14209. else {
  14210. _this.mustUpdateRessources = true;
  14211. updateInDBCallback();
  14212. }
  14213. };
  14214. transaction.onabort = function (event) {
  14215. callback(-1);
  14216. };
  14217. var getRequest = transaction.objectStore("versions").get(url);
  14218. getRequest.onsuccess = function (event) {
  14219. version = (event.target).result;
  14220. };
  14221. getRequest.onerror = function (event) {
  14222. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14223. callback(-1);
  14224. };
  14225. }
  14226. catch (ex) {
  14227. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14228. callback(-1);
  14229. }
  14230. }
  14231. else {
  14232. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14233. callback(-1);
  14234. }
  14235. };
  14236. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14237. var _this = this;
  14238. if (this.isSupported && !this.hasReachedQuota) {
  14239. try {
  14240. // Open a transaction to the database
  14241. var transaction = this.db.transaction(["versions"], "readwrite");
  14242. // the transaction could abort because of a QuotaExceededError error
  14243. transaction.onabort = function (event) {
  14244. try {
  14245. if (event.srcElement.error.name === "QuotaExceededError") {
  14246. _this.hasReachedQuota = true;
  14247. }
  14248. }
  14249. catch (ex) {
  14250. }
  14251. callback(-1);
  14252. };
  14253. transaction.oncomplete = function (event) {
  14254. callback(_this.manifestVersionFound);
  14255. };
  14256. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14257. // Put the scene into the database
  14258. var addRequest = transaction.objectStore("versions").put(newVersion);
  14259. addRequest.onsuccess = function (event) {
  14260. };
  14261. addRequest.onerror = function (event) {
  14262. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14263. };
  14264. }
  14265. catch (ex) {
  14266. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14267. callback(-1);
  14268. }
  14269. }
  14270. else {
  14271. callback(-1);
  14272. }
  14273. };
  14274. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  14275. var _this = this;
  14276. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  14277. var saveAndLoadFile = function (event) {
  14278. // the scene is not yet in the DB, let's try to save it
  14279. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  14280. };
  14281. this._checkVersionFromDB(completeUrl, function (version) {
  14282. if (version !== -1) {
  14283. if (!_this.mustUpdateRessources) {
  14284. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  14285. }
  14286. else {
  14287. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  14288. }
  14289. }
  14290. else {
  14291. errorCallback();
  14292. }
  14293. });
  14294. };
  14295. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  14296. if (this.isSupported) {
  14297. var targetStore;
  14298. if (url.indexOf(".babylon") !== -1) {
  14299. targetStore = "scenes";
  14300. }
  14301. else {
  14302. targetStore = "textures";
  14303. }
  14304. var file;
  14305. var transaction = this.db.transaction([targetStore]);
  14306. transaction.oncomplete = function (event) {
  14307. if (file) {
  14308. callback(file.data);
  14309. }
  14310. else {
  14311. notInDBCallback();
  14312. }
  14313. };
  14314. transaction.onabort = function (event) {
  14315. notInDBCallback();
  14316. };
  14317. var getRequest = transaction.objectStore(targetStore).get(url);
  14318. getRequest.onsuccess = function (event) {
  14319. file = (event.target).result;
  14320. };
  14321. getRequest.onerror = function (event) {
  14322. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  14323. notInDBCallback();
  14324. };
  14325. }
  14326. else {
  14327. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14328. callback();
  14329. }
  14330. };
  14331. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  14332. var _this = this;
  14333. if (this.isSupported) {
  14334. var targetStore;
  14335. if (url.indexOf(".babylon") !== -1) {
  14336. targetStore = "scenes";
  14337. }
  14338. else {
  14339. targetStore = "textures";
  14340. }
  14341. // Create XHR
  14342. var xhr = new XMLHttpRequest(), fileData;
  14343. xhr.open("GET", url, true);
  14344. if (useArrayBuffer) {
  14345. xhr.responseType = "arraybuffer";
  14346. }
  14347. xhr.onprogress = progressCallback;
  14348. xhr.addEventListener("load", function () {
  14349. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  14350. // Blob as response (XHR2)
  14351. //fileData = xhr.responseText;
  14352. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  14353. if (!_this.hasReachedQuota) {
  14354. // Open a transaction to the database
  14355. var transaction = _this.db.transaction([targetStore], "readwrite");
  14356. // the transaction could abort because of a QuotaExceededError error
  14357. transaction.onabort = function (event) {
  14358. try {
  14359. if (event.srcElement.error.name === "QuotaExceededError") {
  14360. this.hasReachedQuota = true;
  14361. }
  14362. }
  14363. catch (ex) {
  14364. }
  14365. callback(fileData);
  14366. };
  14367. transaction.oncomplete = function (event) {
  14368. callback(fileData);
  14369. };
  14370. var newFile;
  14371. if (targetStore === "scenes") {
  14372. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  14373. }
  14374. else {
  14375. newFile = { textureUrl: url, data: fileData };
  14376. }
  14377. try {
  14378. // Put the scene into the database
  14379. var addRequest = transaction.objectStore(targetStore).put(newFile);
  14380. addRequest.onsuccess = function (event) {
  14381. };
  14382. addRequest.onerror = function (event) {
  14383. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  14384. };
  14385. }
  14386. catch (ex) {
  14387. callback(fileData);
  14388. }
  14389. }
  14390. else {
  14391. callback(fileData);
  14392. }
  14393. }
  14394. else {
  14395. callback();
  14396. }
  14397. }, false);
  14398. xhr.addEventListener("error", function (event) {
  14399. BABYLON.Tools.Error("error on XHR request.");
  14400. callback();
  14401. }, false);
  14402. xhr.send();
  14403. }
  14404. else {
  14405. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14406. callback();
  14407. }
  14408. };
  14409. Database.isUASupportingBlobStorage = true;
  14410. Database.parseURL = function (url) {
  14411. var a = document.createElement('a');
  14412. a.href = url;
  14413. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  14414. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  14415. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  14416. return absLocation;
  14417. };
  14418. Database.ReturnFullUrlLocation = function (url) {
  14419. if (url.indexOf("http:/") === -1) {
  14420. return (BABYLON.Database.parseURL(window.location.href) + url);
  14421. }
  14422. else {
  14423. return url;
  14424. }
  14425. };
  14426. return Database;
  14427. })();
  14428. BABYLON.Database = Database;
  14429. })(BABYLON || (BABYLON = {}));
  14430. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  14431. (function (BABYLON) {
  14432. var SpriteManager = (function () {
  14433. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  14434. this.name = name;
  14435. this.cellSize = cellSize;
  14436. this.sprites = new Array();
  14437. this.renderingGroupId = 0;
  14438. this.fogEnabled = true;
  14439. this._vertexDeclaration = [3, 4, 4, 4];
  14440. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  14441. this._capacity = capacity;
  14442. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  14443. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14444. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14445. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  14446. this._scene = scene;
  14447. this._scene.spriteManagers.push(this);
  14448. // VBO
  14449. this._vertexDeclaration = [3, 4, 4, 4];
  14450. this._vertexStrideSize = 15 * 4;
  14451. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14452. var indices = [];
  14453. var index = 0;
  14454. for (var count = 0; count < capacity; count++) {
  14455. indices.push(index);
  14456. indices.push(index + 1);
  14457. indices.push(index + 2);
  14458. indices.push(index);
  14459. indices.push(index + 2);
  14460. indices.push(index + 3);
  14461. index += 4;
  14462. }
  14463. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14464. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14465. // Effects
  14466. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  14467. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  14468. }
  14469. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  14470. var arrayOffset = index * 15;
  14471. if (offsetX == 0)
  14472. offsetX = this._epsilon;
  14473. else if (offsetX == 1)
  14474. offsetX = 1 - this._epsilon;
  14475. if (offsetY == 0)
  14476. offsetY = this._epsilon;
  14477. else if (offsetY == 1)
  14478. offsetY = 1 - this._epsilon;
  14479. this._vertices[arrayOffset] = sprite.position.x;
  14480. this._vertices[arrayOffset + 1] = sprite.position.y;
  14481. this._vertices[arrayOffset + 2] = sprite.position.z;
  14482. this._vertices[arrayOffset + 3] = sprite.angle;
  14483. this._vertices[arrayOffset + 4] = sprite.size;
  14484. this._vertices[arrayOffset + 5] = offsetX;
  14485. this._vertices[arrayOffset + 6] = offsetY;
  14486. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  14487. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  14488. var offset = (sprite.cellIndex / rowSize) >> 0;
  14489. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  14490. this._vertices[arrayOffset + 10] = offset;
  14491. // Color
  14492. this._vertices[arrayOffset + 11] = sprite.color.r;
  14493. this._vertices[arrayOffset + 12] = sprite.color.g;
  14494. this._vertices[arrayOffset + 13] = sprite.color.b;
  14495. this._vertices[arrayOffset + 14] = sprite.color.a;
  14496. };
  14497. SpriteManager.prototype.render = function () {
  14498. // Check
  14499. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  14500. return;
  14501. var engine = this._scene.getEngine();
  14502. var baseSize = this._spriteTexture.getBaseSize();
  14503. // Sprites
  14504. var deltaTime = engine.getDeltaTime();
  14505. var max = Math.min(this._capacity, this.sprites.length);
  14506. var rowSize = baseSize.width / this.cellSize;
  14507. var offset = 0;
  14508. for (var index = 0; index < max; index++) {
  14509. var sprite = this.sprites[index];
  14510. if (!sprite) {
  14511. continue;
  14512. }
  14513. sprite._animate(deltaTime);
  14514. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  14515. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  14516. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  14517. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  14518. }
  14519. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14520. // Render
  14521. var effect = this._effectBase;
  14522. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14523. effect = this._effectFog;
  14524. }
  14525. engine.enableEffect(effect);
  14526. var viewMatrix = this._scene.getViewMatrix();
  14527. effect.setTexture("diffuseSampler", this._spriteTexture);
  14528. effect.setMatrix("view", viewMatrix);
  14529. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14530. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  14531. // Fog
  14532. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14533. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  14534. effect.setColor3("vFogColor", this._scene.fogColor);
  14535. }
  14536. // VBOs
  14537. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14538. // Draw order
  14539. effect.setBool("alphaTest", true);
  14540. engine.setColorWrite(false);
  14541. engine.draw(true, 0, max * 6);
  14542. engine.setColorWrite(true);
  14543. effect.setBool("alphaTest", false);
  14544. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14545. engine.draw(true, 0, max * 6);
  14546. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14547. };
  14548. SpriteManager.prototype.dispose = function () {
  14549. if (this._vertexBuffer) {
  14550. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14551. this._vertexBuffer = null;
  14552. }
  14553. if (this._indexBuffer) {
  14554. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14555. this._indexBuffer = null;
  14556. }
  14557. if (this._spriteTexture) {
  14558. this._spriteTexture.dispose();
  14559. this._spriteTexture = null;
  14560. }
  14561. // Remove from scene
  14562. var index = this._scene.spriteManagers.indexOf(this);
  14563. this._scene.spriteManagers.splice(index, 1);
  14564. // Callback
  14565. if (this.onDispose) {
  14566. this.onDispose();
  14567. }
  14568. };
  14569. return SpriteManager;
  14570. })();
  14571. BABYLON.SpriteManager = SpriteManager;
  14572. })(BABYLON || (BABYLON = {}));
  14573. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  14574. (function (BABYLON) {
  14575. var Sprite = (function () {
  14576. function Sprite(name, manager) {
  14577. this.name = name;
  14578. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14579. this.size = 1.0;
  14580. this.angle = 0;
  14581. this.cellIndex = 0;
  14582. this.invertU = 0;
  14583. this.invertV = 0;
  14584. this.animations = new Array();
  14585. this._animationStarted = false;
  14586. this._loopAnimation = false;
  14587. this._fromIndex = 0;
  14588. this._toIndex = 0;
  14589. this._delay = 0;
  14590. this._direction = 1;
  14591. this._frameCount = 0;
  14592. this._time = 0;
  14593. this._manager = manager;
  14594. this._manager.sprites.push(this);
  14595. this.position = BABYLON.Vector3.Zero();
  14596. }
  14597. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  14598. this._fromIndex = from;
  14599. this._toIndex = to;
  14600. this._loopAnimation = loop;
  14601. this._delay = delay;
  14602. this._animationStarted = true;
  14603. this._direction = from < to ? 1 : -1;
  14604. this.cellIndex = from;
  14605. this._time = 0;
  14606. };
  14607. Sprite.prototype.stopAnimation = function () {
  14608. this._animationStarted = false;
  14609. };
  14610. Sprite.prototype._animate = function (deltaTime) {
  14611. if (!this._animationStarted)
  14612. return;
  14613. this._time += deltaTime;
  14614. if (this._time > this._delay) {
  14615. this._time = this._time % this._delay;
  14616. this.cellIndex += this._direction;
  14617. if (this.cellIndex == this._toIndex) {
  14618. if (this._loopAnimation) {
  14619. this.cellIndex = this._fromIndex;
  14620. }
  14621. else {
  14622. this._animationStarted = false;
  14623. if (this.disposeWhenFinishedAnimating) {
  14624. this.dispose();
  14625. }
  14626. }
  14627. }
  14628. }
  14629. };
  14630. Sprite.prototype.dispose = function () {
  14631. for (var i = 0; i < this._manager.sprites.length; i++) {
  14632. if (this._manager.sprites[i] == this) {
  14633. this._manager.sprites.splice(i, 1);
  14634. }
  14635. }
  14636. };
  14637. return Sprite;
  14638. })();
  14639. BABYLON.Sprite = Sprite;
  14640. })(BABYLON || (BABYLON = {}));
  14641. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  14642. (function (BABYLON) {
  14643. var Layer = (function () {
  14644. function Layer(name, imgUrl, scene, isBackground, color) {
  14645. this.name = name;
  14646. this._vertexDeclaration = [2];
  14647. this._vertexStrideSize = 2 * 4;
  14648. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  14649. this.isBackground = isBackground === undefined ? true : isBackground;
  14650. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  14651. this._scene = scene;
  14652. this._scene.layers.push(this);
  14653. // VBO
  14654. var vertices = [];
  14655. vertices.push(1, 1);
  14656. vertices.push(-1, 1);
  14657. vertices.push(-1, -1);
  14658. vertices.push(1, -1);
  14659. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14660. // Indices
  14661. var indices = [];
  14662. indices.push(0);
  14663. indices.push(1);
  14664. indices.push(2);
  14665. indices.push(0);
  14666. indices.push(2);
  14667. indices.push(3);
  14668. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14669. // Effects
  14670. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  14671. }
  14672. Layer.prototype.render = function () {
  14673. // Check
  14674. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  14675. return;
  14676. var engine = this._scene.getEngine();
  14677. // Render
  14678. engine.enableEffect(this._effect);
  14679. engine.setState(false);
  14680. // Texture
  14681. this._effect.setTexture("textureSampler", this.texture);
  14682. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  14683. // Color
  14684. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  14685. // VBOs
  14686. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14687. // Draw order
  14688. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14689. engine.draw(true, 0, 6);
  14690. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14691. };
  14692. Layer.prototype.dispose = function () {
  14693. if (this._vertexBuffer) {
  14694. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14695. this._vertexBuffer = null;
  14696. }
  14697. if (this._indexBuffer) {
  14698. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14699. this._indexBuffer = null;
  14700. }
  14701. if (this.texture) {
  14702. this.texture.dispose();
  14703. this.texture = null;
  14704. }
  14705. // Remove from scene
  14706. var index = this._scene.layers.indexOf(this);
  14707. this._scene.layers.splice(index, 1);
  14708. // Callback
  14709. if (this.onDispose) {
  14710. this.onDispose();
  14711. }
  14712. };
  14713. return Layer;
  14714. })();
  14715. BABYLON.Layer = Layer;
  14716. })(BABYLON || (BABYLON = {}));
  14717. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  14718. (function (BABYLON) {
  14719. var Particle = (function () {
  14720. function Particle() {
  14721. this.position = BABYLON.Vector3.Zero();
  14722. this.direction = BABYLON.Vector3.Zero();
  14723. this.color = new BABYLON.Color4(0, 0, 0, 0);
  14724. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  14725. this.lifeTime = 1.0;
  14726. this.age = 0;
  14727. this.size = 0;
  14728. this.angle = 0;
  14729. this.angularSpeed = 0;
  14730. }
  14731. Particle.prototype.copyTo = function (other) {
  14732. other.position.copyFrom(this.position);
  14733. other.direction.copyFrom(this.direction);
  14734. other.color.copyFrom(this.color);
  14735. other.colorStep.copyFrom(this.colorStep);
  14736. other.lifeTime = this.lifeTime;
  14737. other.age = this.age;
  14738. other.size = this.size;
  14739. other.angle = this.angle;
  14740. other.angularSpeed = this.angularSpeed;
  14741. };
  14742. return Particle;
  14743. })();
  14744. BABYLON.Particle = Particle;
  14745. })(BABYLON || (BABYLON = {}));
  14746. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  14747. (function (BABYLON) {
  14748. var randomNumber = function (min, max) {
  14749. if (min === max) {
  14750. return (min);
  14751. }
  14752. var random = Math.random();
  14753. return ((random * (max - min)) + min);
  14754. };
  14755. var ParticleSystem = (function () {
  14756. function ParticleSystem(name, capacity, scene, customEffect) {
  14757. var _this = this;
  14758. this.name = name;
  14759. this.renderingGroupId = 0;
  14760. this.emitter = null;
  14761. this.emitRate = 10;
  14762. this.manualEmitCount = -1;
  14763. this.updateSpeed = 0.01;
  14764. this.targetStopDuration = 0;
  14765. this.disposeOnStop = false;
  14766. this.minEmitPower = 1;
  14767. this.maxEmitPower = 1;
  14768. this.minLifeTime = 1;
  14769. this.maxLifeTime = 1;
  14770. this.minSize = 1;
  14771. this.maxSize = 1;
  14772. this.minAngularSpeed = 0;
  14773. this.maxAngularSpeed = 0;
  14774. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  14775. this.forceDepthWrite = false;
  14776. this.gravity = BABYLON.Vector3.Zero();
  14777. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  14778. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  14779. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  14780. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14781. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14782. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14783. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  14784. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14785. this.particles = new Array();
  14786. this._vertexDeclaration = [3, 4, 4];
  14787. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  14788. this._stockParticles = new Array();
  14789. this._newPartsExcess = 0;
  14790. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  14791. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  14792. this._scaledDirection = BABYLON.Vector3.Zero();
  14793. this._scaledGravity = BABYLON.Vector3.Zero();
  14794. this._currentRenderId = -1;
  14795. this._started = false;
  14796. this._stopped = false;
  14797. this._actualFrame = 0;
  14798. this.id = name;
  14799. this._capacity = capacity;
  14800. this._scene = scene;
  14801. this._customEffect = customEffect;
  14802. scene.particleSystems.push(this);
  14803. // VBO
  14804. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14805. var indices = [];
  14806. var index = 0;
  14807. for (var count = 0; count < capacity; count++) {
  14808. indices.push(index);
  14809. indices.push(index + 1);
  14810. indices.push(index + 2);
  14811. indices.push(index);
  14812. indices.push(index + 2);
  14813. indices.push(index + 3);
  14814. index += 4;
  14815. }
  14816. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14817. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14818. // Default behaviors
  14819. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  14820. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  14821. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  14822. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  14823. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  14824. };
  14825. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  14826. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  14827. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  14828. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  14829. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  14830. };
  14831. this.updateFunction = function (particles) {
  14832. for (var index = 0; index < particles.length; index++) {
  14833. var particle = particles[index];
  14834. particle.age += _this._scaledUpdateSpeed;
  14835. if (particle.age >= particle.lifeTime) {
  14836. _this.recycleParticle(particle);
  14837. index--;
  14838. continue;
  14839. }
  14840. else {
  14841. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  14842. particle.color.addInPlace(_this._scaledColorStep);
  14843. if (particle.color.a < 0)
  14844. particle.color.a = 0;
  14845. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  14846. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  14847. particle.position.addInPlace(_this._scaledDirection);
  14848. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  14849. particle.direction.addInPlace(_this._scaledGravity);
  14850. }
  14851. }
  14852. };
  14853. }
  14854. ParticleSystem.prototype.recycleParticle = function (particle) {
  14855. var lastParticle = this.particles.pop();
  14856. if (lastParticle !== particle) {
  14857. lastParticle.copyTo(particle);
  14858. this._stockParticles.push(lastParticle);
  14859. }
  14860. };
  14861. ParticleSystem.prototype.getCapacity = function () {
  14862. return this._capacity;
  14863. };
  14864. ParticleSystem.prototype.isAlive = function () {
  14865. return this._alive;
  14866. };
  14867. ParticleSystem.prototype.isStarted = function () {
  14868. return this._started;
  14869. };
  14870. ParticleSystem.prototype.start = function () {
  14871. this._started = true;
  14872. this._stopped = false;
  14873. this._actualFrame = 0;
  14874. };
  14875. ParticleSystem.prototype.stop = function () {
  14876. this._stopped = true;
  14877. };
  14878. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  14879. var offset = index * 11;
  14880. this._vertices[offset] = particle.position.x;
  14881. this._vertices[offset + 1] = particle.position.y;
  14882. this._vertices[offset + 2] = particle.position.z;
  14883. this._vertices[offset + 3] = particle.color.r;
  14884. this._vertices[offset + 4] = particle.color.g;
  14885. this._vertices[offset + 5] = particle.color.b;
  14886. this._vertices[offset + 6] = particle.color.a;
  14887. this._vertices[offset + 7] = particle.angle;
  14888. this._vertices[offset + 8] = particle.size;
  14889. this._vertices[offset + 9] = offsetX;
  14890. this._vertices[offset + 10] = offsetY;
  14891. };
  14892. ParticleSystem.prototype._update = function (newParticles) {
  14893. // Update current
  14894. this._alive = this.particles.length > 0;
  14895. this.updateFunction(this.particles);
  14896. // Add new ones
  14897. var worldMatrix;
  14898. if (this.emitter.position) {
  14899. worldMatrix = this.emitter.getWorldMatrix();
  14900. }
  14901. else {
  14902. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  14903. }
  14904. for (var index = 0; index < newParticles; index++) {
  14905. if (this.particles.length === this._capacity) {
  14906. break;
  14907. }
  14908. if (this._stockParticles.length !== 0) {
  14909. var particle = this._stockParticles.pop();
  14910. particle.age = 0;
  14911. }
  14912. else {
  14913. particle = new BABYLON.Particle();
  14914. }
  14915. this.particles.push(particle);
  14916. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  14917. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  14918. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  14919. particle.size = randomNumber(this.minSize, this.maxSize);
  14920. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  14921. this.startPositionFunction(worldMatrix, particle.position);
  14922. var step = randomNumber(0, 1.0);
  14923. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  14924. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  14925. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  14926. }
  14927. };
  14928. ParticleSystem.prototype._getEffect = function () {
  14929. if (this._customEffect) {
  14930. return this._customEffect;
  14931. }
  14932. ;
  14933. var defines = [];
  14934. if (this._scene.clipPlane) {
  14935. defines.push("#define CLIPPLANE");
  14936. }
  14937. // Effect
  14938. var join = defines.join("\n");
  14939. if (this._cachedDefines !== join) {
  14940. this._cachedDefines = join;
  14941. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  14942. }
  14943. return this._effect;
  14944. };
  14945. ParticleSystem.prototype.animate = function () {
  14946. if (!this._started)
  14947. return;
  14948. var effect = this._getEffect();
  14949. // Check
  14950. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  14951. return;
  14952. if (this._currentRenderId === this._scene.getRenderId()) {
  14953. return;
  14954. }
  14955. this._currentRenderId = this._scene.getRenderId();
  14956. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  14957. // determine the number of particles we need to create
  14958. var emitCout;
  14959. if (this.manualEmitCount > -1) {
  14960. emitCout = this.manualEmitCount;
  14961. this.manualEmitCount = 0;
  14962. }
  14963. else {
  14964. emitCout = this.emitRate;
  14965. }
  14966. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  14967. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  14968. if (this._newPartsExcess > 1.0) {
  14969. newParticles += this._newPartsExcess >> 0;
  14970. this._newPartsExcess -= this._newPartsExcess >> 0;
  14971. }
  14972. this._alive = false;
  14973. if (!this._stopped) {
  14974. this._actualFrame += this._scaledUpdateSpeed;
  14975. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  14976. this.stop();
  14977. }
  14978. else {
  14979. newParticles = 0;
  14980. }
  14981. this._update(newParticles);
  14982. // Stopped?
  14983. if (this._stopped) {
  14984. if (!this._alive) {
  14985. this._started = false;
  14986. if (this.disposeOnStop) {
  14987. this._scene._toBeDisposed.push(this);
  14988. }
  14989. }
  14990. }
  14991. // Update VBO
  14992. var offset = 0;
  14993. for (var index = 0; index < this.particles.length; index++) {
  14994. var particle = this.particles[index];
  14995. this._appendParticleVertex(offset++, particle, 0, 0);
  14996. this._appendParticleVertex(offset++, particle, 1, 0);
  14997. this._appendParticleVertex(offset++, particle, 1, 1);
  14998. this._appendParticleVertex(offset++, particle, 0, 1);
  14999. }
  15000. var engine = this._scene.getEngine();
  15001. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15002. };
  15003. ParticleSystem.prototype.render = function () {
  15004. var effect = this._getEffect();
  15005. // Check
  15006. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  15007. return 0;
  15008. var engine = this._scene.getEngine();
  15009. // Render
  15010. engine.enableEffect(effect);
  15011. engine.setState(false);
  15012. var viewMatrix = this._scene.getViewMatrix();
  15013. effect.setTexture("diffuseSampler", this.particleTexture);
  15014. effect.setMatrix("view", viewMatrix);
  15015. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15016. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  15017. if (this._scene.clipPlane) {
  15018. var clipPlane = this._scene.clipPlane;
  15019. var invView = viewMatrix.clone();
  15020. invView.invert();
  15021. effect.setMatrix("invView", invView);
  15022. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15023. }
  15024. // VBOs
  15025. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15026. // Draw order
  15027. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  15028. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15029. }
  15030. else {
  15031. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15032. }
  15033. if (this.forceDepthWrite) {
  15034. engine.setDepthWrite(true);
  15035. }
  15036. engine.draw(true, 0, this.particles.length * 6);
  15037. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15038. return this.particles.length;
  15039. };
  15040. ParticleSystem.prototype.dispose = function () {
  15041. if (this._vertexBuffer) {
  15042. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15043. this._vertexBuffer = null;
  15044. }
  15045. if (this._indexBuffer) {
  15046. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15047. this._indexBuffer = null;
  15048. }
  15049. if (this.particleTexture) {
  15050. this.particleTexture.dispose();
  15051. this.particleTexture = null;
  15052. }
  15053. // Remove from scene
  15054. var index = this._scene.particleSystems.indexOf(this);
  15055. this._scene.particleSystems.splice(index, 1);
  15056. // Callback
  15057. if (this.onDispose) {
  15058. this.onDispose();
  15059. }
  15060. };
  15061. // Clone
  15062. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15063. var result = new ParticleSystem(name, this._capacity, this._scene);
  15064. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15065. if (newEmitter === undefined) {
  15066. newEmitter = this.emitter;
  15067. }
  15068. result.emitter = newEmitter;
  15069. if (this.particleTexture) {
  15070. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15071. }
  15072. result.start();
  15073. return result;
  15074. };
  15075. // Statics
  15076. ParticleSystem.BLENDMODE_ONEONE = 0;
  15077. ParticleSystem.BLENDMODE_STANDARD = 1;
  15078. return ParticleSystem;
  15079. })();
  15080. BABYLON.ParticleSystem = ParticleSystem;
  15081. })(BABYLON || (BABYLON = {}));
  15082. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15083. (function (BABYLON) {
  15084. var Animation = (function () {
  15085. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15086. this.name = name;
  15087. this.targetProperty = targetProperty;
  15088. this.framePerSecond = framePerSecond;
  15089. this.dataType = dataType;
  15090. this.loopMode = loopMode;
  15091. this._offsetsCache = {};
  15092. this._highLimitsCache = {};
  15093. this._stopped = false;
  15094. this.targetPropertyPath = targetProperty.split(".");
  15095. this.dataType = dataType;
  15096. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15097. }
  15098. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15099. var dataType = undefined;
  15100. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15101. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15102. }
  15103. else if (from instanceof BABYLON.Quaternion) {
  15104. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15105. }
  15106. else if (from instanceof BABYLON.Vector3) {
  15107. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15108. }
  15109. else if (from instanceof BABYLON.Vector2) {
  15110. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15111. }
  15112. else if (from instanceof BABYLON.Color3) {
  15113. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15114. }
  15115. if (dataType == undefined) {
  15116. return;
  15117. }
  15118. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15119. var keys = [];
  15120. keys.push({ frame: 0, value: from });
  15121. keys.push({ frame: totalFrame, value: to });
  15122. animation.setKeys(keys);
  15123. mesh.animations.push(animation);
  15124. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15125. };
  15126. // Methods
  15127. Animation.prototype.isStopped = function () {
  15128. return this._stopped;
  15129. };
  15130. Animation.prototype.getKeys = function () {
  15131. return this._keys;
  15132. };
  15133. Animation.prototype.getEasingFunction = function () {
  15134. return this._easingFunction;
  15135. };
  15136. Animation.prototype.setEasingFunction = function (easingFunction) {
  15137. this._easingFunction = easingFunction;
  15138. };
  15139. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15140. return startValue + (endValue - startValue) * gradient;
  15141. };
  15142. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15143. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15144. };
  15145. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15146. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15147. };
  15148. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15149. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15150. };
  15151. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15152. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15153. };
  15154. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15155. var startScale = new BABYLON.Vector3(0, 0, 0);
  15156. var startRotation = new BABYLON.Quaternion();
  15157. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15158. startValue.decompose(startScale, startRotation, startTranslation);
  15159. var endScale = new BABYLON.Vector3(0, 0, 0);
  15160. var endRotation = new BABYLON.Quaternion();
  15161. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15162. endValue.decompose(endScale, endRotation, endTranslation);
  15163. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15164. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15165. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15166. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15167. return result;
  15168. };
  15169. Animation.prototype.clone = function () {
  15170. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15171. clone.setKeys(this._keys);
  15172. return clone;
  15173. };
  15174. Animation.prototype.setKeys = function (values) {
  15175. this._keys = values.slice(0);
  15176. this._offsetsCache = {};
  15177. this._highLimitsCache = {};
  15178. };
  15179. Animation.prototype._getKeyValue = function (value) {
  15180. if (typeof value === "function") {
  15181. return value();
  15182. }
  15183. return value;
  15184. };
  15185. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15186. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15187. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15188. }
  15189. this.currentFrame = currentFrame;
  15190. for (var key = 0; key < this._keys.length; key++) {
  15191. // for each frame, we need the key just before the frame superior
  15192. if (this._keys[key + 1].frame >= currentFrame) {
  15193. var startValue = this._getKeyValue(this._keys[key].value);
  15194. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15195. // gradient : percent of currentFrame between the frame inf and the frame sup
  15196. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15197. // check for easingFunction and correction of gradient
  15198. if (this._easingFunction != null) {
  15199. gradient = this._easingFunction.ease(gradient);
  15200. }
  15201. switch (this.dataType) {
  15202. case Animation.ANIMATIONTYPE_FLOAT:
  15203. switch (loopMode) {
  15204. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15205. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15206. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15207. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15208. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15209. }
  15210. break;
  15211. case Animation.ANIMATIONTYPE_QUATERNION:
  15212. var quaternion = null;
  15213. switch (loopMode) {
  15214. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15215. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15216. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15217. break;
  15218. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15219. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15220. break;
  15221. }
  15222. return quaternion;
  15223. case Animation.ANIMATIONTYPE_VECTOR3:
  15224. switch (loopMode) {
  15225. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15226. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15227. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15228. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15229. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15230. }
  15231. case Animation.ANIMATIONTYPE_VECTOR2:
  15232. switch (loopMode) {
  15233. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15234. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15235. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15236. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15237. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15238. }
  15239. case Animation.ANIMATIONTYPE_COLOR3:
  15240. switch (loopMode) {
  15241. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15242. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15243. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15244. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15245. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15246. }
  15247. case Animation.ANIMATIONTYPE_MATRIX:
  15248. switch (loopMode) {
  15249. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15250. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15251. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15252. return startValue;
  15253. }
  15254. default:
  15255. break;
  15256. }
  15257. break;
  15258. }
  15259. }
  15260. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15261. };
  15262. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15263. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15264. this._stopped = true;
  15265. return false;
  15266. }
  15267. var returnValue = true;
  15268. // Adding a start key at frame 0 if missing
  15269. if (this._keys[0].frame !== 0) {
  15270. var newKey = { frame: 0, value: this._keys[0].value };
  15271. this._keys.splice(0, 0, newKey);
  15272. }
  15273. // Check limits
  15274. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  15275. from = this._keys[0].frame;
  15276. }
  15277. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  15278. to = this._keys[this._keys.length - 1].frame;
  15279. }
  15280. // Compute ratio
  15281. var range = to - from;
  15282. var offsetValue;
  15283. // ratio represents the frame delta between from and to
  15284. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  15285. var highLimitValue = 0;
  15286. if (ratio > range && !loop) {
  15287. returnValue = false;
  15288. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  15289. }
  15290. else {
  15291. // Get max value if required
  15292. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  15293. var keyOffset = to.toString() + from.toString();
  15294. if (!this._offsetsCache[keyOffset]) {
  15295. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15296. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15297. switch (this.dataType) {
  15298. case Animation.ANIMATIONTYPE_FLOAT:
  15299. this._offsetsCache[keyOffset] = toValue - fromValue;
  15300. break;
  15301. case Animation.ANIMATIONTYPE_QUATERNION:
  15302. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15303. break;
  15304. case Animation.ANIMATIONTYPE_VECTOR3:
  15305. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15306. case Animation.ANIMATIONTYPE_VECTOR2:
  15307. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15308. case Animation.ANIMATIONTYPE_COLOR3:
  15309. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15310. default:
  15311. break;
  15312. }
  15313. this._highLimitsCache[keyOffset] = toValue;
  15314. }
  15315. highLimitValue = this._highLimitsCache[keyOffset];
  15316. offsetValue = this._offsetsCache[keyOffset];
  15317. }
  15318. }
  15319. if (offsetValue === undefined) {
  15320. switch (this.dataType) {
  15321. case Animation.ANIMATIONTYPE_FLOAT:
  15322. offsetValue = 0;
  15323. break;
  15324. case Animation.ANIMATIONTYPE_QUATERNION:
  15325. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  15326. break;
  15327. case Animation.ANIMATIONTYPE_VECTOR3:
  15328. offsetValue = BABYLON.Vector3.Zero();
  15329. break;
  15330. case Animation.ANIMATIONTYPE_VECTOR2:
  15331. offsetValue = BABYLON.Vector2.Zero();
  15332. break;
  15333. case Animation.ANIMATIONTYPE_COLOR3:
  15334. offsetValue = BABYLON.Color3.Black();
  15335. }
  15336. }
  15337. // Compute value
  15338. var repeatCount = (ratio / range) >> 0;
  15339. var currentFrame = returnValue ? from + ratio % range : to;
  15340. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  15341. // Set value
  15342. if (this.targetPropertyPath.length > 1) {
  15343. var property = this._target[this.targetPropertyPath[0]];
  15344. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  15345. property = property[this.targetPropertyPath[index]];
  15346. }
  15347. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  15348. }
  15349. else {
  15350. this._target[this.targetPropertyPath[0]] = currentValue;
  15351. }
  15352. if (this._target.markAsDirty) {
  15353. this._target.markAsDirty(this.targetProperty);
  15354. }
  15355. if (!returnValue) {
  15356. this._stopped = true;
  15357. }
  15358. return returnValue;
  15359. };
  15360. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  15361. get: function () {
  15362. return Animation._ANIMATIONTYPE_FLOAT;
  15363. },
  15364. enumerable: true,
  15365. configurable: true
  15366. });
  15367. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  15368. get: function () {
  15369. return Animation._ANIMATIONTYPE_VECTOR3;
  15370. },
  15371. enumerable: true,
  15372. configurable: true
  15373. });
  15374. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  15375. get: function () {
  15376. return Animation._ANIMATIONTYPE_VECTOR2;
  15377. },
  15378. enumerable: true,
  15379. configurable: true
  15380. });
  15381. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  15382. get: function () {
  15383. return Animation._ANIMATIONTYPE_QUATERNION;
  15384. },
  15385. enumerable: true,
  15386. configurable: true
  15387. });
  15388. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  15389. get: function () {
  15390. return Animation._ANIMATIONTYPE_MATRIX;
  15391. },
  15392. enumerable: true,
  15393. configurable: true
  15394. });
  15395. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  15396. get: function () {
  15397. return Animation._ANIMATIONTYPE_COLOR3;
  15398. },
  15399. enumerable: true,
  15400. configurable: true
  15401. });
  15402. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  15403. get: function () {
  15404. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  15405. },
  15406. enumerable: true,
  15407. configurable: true
  15408. });
  15409. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  15410. get: function () {
  15411. return Animation._ANIMATIONLOOPMODE_CYCLE;
  15412. },
  15413. enumerable: true,
  15414. configurable: true
  15415. });
  15416. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  15417. get: function () {
  15418. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  15419. },
  15420. enumerable: true,
  15421. configurable: true
  15422. });
  15423. // Statics
  15424. Animation._ANIMATIONTYPE_FLOAT = 0;
  15425. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  15426. Animation._ANIMATIONTYPE_QUATERNION = 2;
  15427. Animation._ANIMATIONTYPE_MATRIX = 3;
  15428. Animation._ANIMATIONTYPE_COLOR3 = 4;
  15429. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  15430. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  15431. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  15432. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  15433. return Animation;
  15434. })();
  15435. BABYLON.Animation = Animation;
  15436. })(BABYLON || (BABYLON = {}));
  15437. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  15438. (function (BABYLON) {
  15439. var Animatable = (function () {
  15440. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  15441. if (fromFrame === void 0) { fromFrame = 0; }
  15442. if (toFrame === void 0) { toFrame = 100; }
  15443. if (loopAnimation === void 0) { loopAnimation = false; }
  15444. if (speedRatio === void 0) { speedRatio = 1.0; }
  15445. this.target = target;
  15446. this.fromFrame = fromFrame;
  15447. this.toFrame = toFrame;
  15448. this.loopAnimation = loopAnimation;
  15449. this.speedRatio = speedRatio;
  15450. this.onAnimationEnd = onAnimationEnd;
  15451. this._animations = new Array();
  15452. this._paused = false;
  15453. this.animationStarted = false;
  15454. if (animations) {
  15455. this.appendAnimations(target, animations);
  15456. }
  15457. this._scene = scene;
  15458. scene._activeAnimatables.push(this);
  15459. }
  15460. // Methods
  15461. Animatable.prototype.appendAnimations = function (target, animations) {
  15462. for (var index = 0; index < animations.length; index++) {
  15463. var animation = animations[index];
  15464. animation._target = target;
  15465. this._animations.push(animation);
  15466. }
  15467. };
  15468. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  15469. var animations = this._animations;
  15470. for (var index = 0; index < animations.length; index++) {
  15471. if (animations[index].targetProperty === property) {
  15472. return animations[index];
  15473. }
  15474. }
  15475. return null;
  15476. };
  15477. Animatable.prototype.pause = function () {
  15478. if (this._paused) {
  15479. return;
  15480. }
  15481. this._paused = true;
  15482. };
  15483. Animatable.prototype.restart = function () {
  15484. this._paused = false;
  15485. };
  15486. Animatable.prototype.stop = function () {
  15487. var index = this._scene._activeAnimatables.indexOf(this);
  15488. if (index > -1) {
  15489. this._scene._activeAnimatables.splice(index, 1);
  15490. }
  15491. if (this.onAnimationEnd) {
  15492. this.onAnimationEnd();
  15493. }
  15494. };
  15495. Animatable.prototype._animate = function (delay) {
  15496. if (this._paused) {
  15497. if (!this._pausedDelay) {
  15498. this._pausedDelay = delay;
  15499. }
  15500. return true;
  15501. }
  15502. if (!this._localDelayOffset) {
  15503. this._localDelayOffset = delay;
  15504. }
  15505. else if (this._pausedDelay) {
  15506. this._localDelayOffset += delay - this._pausedDelay;
  15507. this._pausedDelay = null;
  15508. }
  15509. // Animating
  15510. var running = false;
  15511. var animations = this._animations;
  15512. for (var index = 0; index < animations.length; index++) {
  15513. var animation = animations[index];
  15514. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  15515. running = running || isRunning;
  15516. }
  15517. if (!running && this.onAnimationEnd) {
  15518. this.onAnimationEnd();
  15519. }
  15520. return running;
  15521. };
  15522. return Animatable;
  15523. })();
  15524. BABYLON.Animatable = Animatable;
  15525. })(BABYLON || (BABYLON = {}));
  15526. //# sourceMappingURL=babylon.animatable.js.map
  15527. var BABYLON;
  15528. (function (BABYLON) {
  15529. var EasingFunction = (function () {
  15530. function EasingFunction() {
  15531. // Properties
  15532. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  15533. }
  15534. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  15535. get: function () {
  15536. return EasingFunction._EASINGMODE_EASEIN;
  15537. },
  15538. enumerable: true,
  15539. configurable: true
  15540. });
  15541. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  15542. get: function () {
  15543. return EasingFunction._EASINGMODE_EASEOUT;
  15544. },
  15545. enumerable: true,
  15546. configurable: true
  15547. });
  15548. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  15549. get: function () {
  15550. return EasingFunction._EASINGMODE_EASEINOUT;
  15551. },
  15552. enumerable: true,
  15553. configurable: true
  15554. });
  15555. EasingFunction.prototype.setEasingMode = function (easingMode) {
  15556. var n = Math.min(Math.max(easingMode, 0), 2);
  15557. this._easingMode = n;
  15558. };
  15559. EasingFunction.prototype.getEasingMode = function () {
  15560. return this._easingMode;
  15561. };
  15562. EasingFunction.prototype.easeInCore = function (gradient) {
  15563. throw new Error('You must implement this method');
  15564. };
  15565. EasingFunction.prototype.ease = function (gradient) {
  15566. switch (this._easingMode) {
  15567. case EasingFunction.EASINGMODE_EASEIN:
  15568. return this.easeInCore(gradient);
  15569. case EasingFunction.EASINGMODE_EASEOUT:
  15570. return (1 - this.easeInCore(1 - gradient));
  15571. }
  15572. if (gradient >= 0.5) {
  15573. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  15574. }
  15575. return (this.easeInCore(gradient * 2) * 0.5);
  15576. };
  15577. //Statics
  15578. EasingFunction._EASINGMODE_EASEIN = 0;
  15579. EasingFunction._EASINGMODE_EASEOUT = 1;
  15580. EasingFunction._EASINGMODE_EASEINOUT = 2;
  15581. return EasingFunction;
  15582. })();
  15583. BABYLON.EasingFunction = EasingFunction;
  15584. var CircleEase = (function (_super) {
  15585. __extends(CircleEase, _super);
  15586. function CircleEase() {
  15587. _super.apply(this, arguments);
  15588. }
  15589. CircleEase.prototype.easeInCore = function (gradient) {
  15590. gradient = Math.max(0, Math.min(1, gradient));
  15591. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  15592. };
  15593. return CircleEase;
  15594. })(EasingFunction);
  15595. BABYLON.CircleEase = CircleEase;
  15596. var BackEase = (function (_super) {
  15597. __extends(BackEase, _super);
  15598. function BackEase(amplitude) {
  15599. if (amplitude === void 0) { amplitude = 1; }
  15600. _super.call(this);
  15601. this.amplitude = amplitude;
  15602. }
  15603. BackEase.prototype.easeInCore = function (gradient) {
  15604. var num = Math.max(0, this.amplitude);
  15605. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  15606. };
  15607. return BackEase;
  15608. })(EasingFunction);
  15609. BABYLON.BackEase = BackEase;
  15610. var BounceEase = (function (_super) {
  15611. __extends(BounceEase, _super);
  15612. function BounceEase(bounces, bounciness) {
  15613. if (bounces === void 0) { bounces = 3; }
  15614. if (bounciness === void 0) { bounciness = 2; }
  15615. _super.call(this);
  15616. this.bounces = bounces;
  15617. this.bounciness = bounciness;
  15618. }
  15619. BounceEase.prototype.easeInCore = function (gradient) {
  15620. var y = Math.max(0.0, this.bounces);
  15621. var bounciness = this.bounciness;
  15622. if (bounciness <= 1.0) {
  15623. bounciness = 1.001;
  15624. }
  15625. var num9 = Math.pow(bounciness, y);
  15626. var num5 = 1.0 - bounciness;
  15627. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  15628. var num15 = gradient * num4;
  15629. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  15630. var num3 = Math.floor(num65);
  15631. var num13 = num3 + 1.0;
  15632. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  15633. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  15634. var num7 = (num8 + num12) * 0.5;
  15635. var num6 = gradient - num7;
  15636. var num2 = num7 - num8;
  15637. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  15638. };
  15639. return BounceEase;
  15640. })(EasingFunction);
  15641. BABYLON.BounceEase = BounceEase;
  15642. var CubicEase = (function (_super) {
  15643. __extends(CubicEase, _super);
  15644. function CubicEase() {
  15645. _super.apply(this, arguments);
  15646. }
  15647. CubicEase.prototype.easeInCore = function (gradient) {
  15648. return (gradient * gradient * gradient);
  15649. };
  15650. return CubicEase;
  15651. })(EasingFunction);
  15652. BABYLON.CubicEase = CubicEase;
  15653. var ElasticEase = (function (_super) {
  15654. __extends(ElasticEase, _super);
  15655. function ElasticEase(oscillations, springiness) {
  15656. if (oscillations === void 0) { oscillations = 3; }
  15657. if (springiness === void 0) { springiness = 3; }
  15658. _super.call(this);
  15659. this.oscillations = oscillations;
  15660. this.springiness = springiness;
  15661. }
  15662. ElasticEase.prototype.easeInCore = function (gradient) {
  15663. var num2;
  15664. var num3 = Math.max(0.0, this.oscillations);
  15665. var num = Math.max(0.0, this.springiness);
  15666. if (num == 0) {
  15667. num2 = gradient;
  15668. }
  15669. else {
  15670. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  15671. }
  15672. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  15673. };
  15674. return ElasticEase;
  15675. })(EasingFunction);
  15676. BABYLON.ElasticEase = ElasticEase;
  15677. var ExponentialEase = (function (_super) {
  15678. __extends(ExponentialEase, _super);
  15679. function ExponentialEase(exponent) {
  15680. if (exponent === void 0) { exponent = 2; }
  15681. _super.call(this);
  15682. this.exponent = exponent;
  15683. }
  15684. ExponentialEase.prototype.easeInCore = function (gradient) {
  15685. if (this.exponent <= 0) {
  15686. return gradient;
  15687. }
  15688. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  15689. };
  15690. return ExponentialEase;
  15691. })(EasingFunction);
  15692. BABYLON.ExponentialEase = ExponentialEase;
  15693. var PowerEase = (function (_super) {
  15694. __extends(PowerEase, _super);
  15695. function PowerEase(power) {
  15696. if (power === void 0) { power = 2; }
  15697. _super.call(this);
  15698. this.power = power;
  15699. }
  15700. PowerEase.prototype.easeInCore = function (gradient) {
  15701. var y = Math.max(0.0, this.power);
  15702. return Math.pow(gradient, y);
  15703. };
  15704. return PowerEase;
  15705. })(EasingFunction);
  15706. BABYLON.PowerEase = PowerEase;
  15707. var QuadraticEase = (function (_super) {
  15708. __extends(QuadraticEase, _super);
  15709. function QuadraticEase() {
  15710. _super.apply(this, arguments);
  15711. }
  15712. QuadraticEase.prototype.easeInCore = function (gradient) {
  15713. return (gradient * gradient);
  15714. };
  15715. return QuadraticEase;
  15716. })(EasingFunction);
  15717. BABYLON.QuadraticEase = QuadraticEase;
  15718. var QuarticEase = (function (_super) {
  15719. __extends(QuarticEase, _super);
  15720. function QuarticEase() {
  15721. _super.apply(this, arguments);
  15722. }
  15723. QuarticEase.prototype.easeInCore = function (gradient) {
  15724. return (gradient * gradient * gradient * gradient);
  15725. };
  15726. return QuarticEase;
  15727. })(EasingFunction);
  15728. BABYLON.QuarticEase = QuarticEase;
  15729. var QuinticEase = (function (_super) {
  15730. __extends(QuinticEase, _super);
  15731. function QuinticEase() {
  15732. _super.apply(this, arguments);
  15733. }
  15734. QuinticEase.prototype.easeInCore = function (gradient) {
  15735. return (gradient * gradient * gradient * gradient * gradient);
  15736. };
  15737. return QuinticEase;
  15738. })(EasingFunction);
  15739. BABYLON.QuinticEase = QuinticEase;
  15740. var SineEase = (function (_super) {
  15741. __extends(SineEase, _super);
  15742. function SineEase() {
  15743. _super.apply(this, arguments);
  15744. }
  15745. SineEase.prototype.easeInCore = function (gradient) {
  15746. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  15747. };
  15748. return SineEase;
  15749. })(EasingFunction);
  15750. BABYLON.SineEase = SineEase;
  15751. var BezierCurveEase = (function (_super) {
  15752. __extends(BezierCurveEase, _super);
  15753. function BezierCurveEase(x1, y1, x2, y2) {
  15754. if (x1 === void 0) { x1 = 0; }
  15755. if (y1 === void 0) { y1 = 0; }
  15756. if (x2 === void 0) { x2 = 1; }
  15757. if (y2 === void 0) { y2 = 1; }
  15758. _super.call(this);
  15759. this.x1 = x1;
  15760. this.y1 = y1;
  15761. this.x2 = x2;
  15762. this.y2 = y2;
  15763. }
  15764. BezierCurveEase.prototype.easeInCore = function (gradient) {
  15765. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  15766. };
  15767. return BezierCurveEase;
  15768. })(EasingFunction);
  15769. BABYLON.BezierCurveEase = BezierCurveEase;
  15770. })(BABYLON || (BABYLON = {}));
  15771. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  15772. (function (BABYLON) {
  15773. var Octree = (function () {
  15774. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  15775. if (maxDepth === void 0) { maxDepth = 2; }
  15776. this.maxDepth = maxDepth;
  15777. this.dynamicContent = new Array();
  15778. this._maxBlockCapacity = maxBlockCapacity || 64;
  15779. this._selectionContent = new BABYLON.SmartArray(1024);
  15780. this._creationFunc = creationFunc;
  15781. }
  15782. // Methods
  15783. Octree.prototype.update = function (worldMin, worldMax, entries) {
  15784. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  15785. };
  15786. Octree.prototype.addMesh = function (entry) {
  15787. for (var index = 0; index < this.blocks.length; index++) {
  15788. var block = this.blocks[index];
  15789. block.addEntry(entry);
  15790. }
  15791. };
  15792. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  15793. this._selectionContent.reset();
  15794. for (var index = 0; index < this.blocks.length; index++) {
  15795. var block = this.blocks[index];
  15796. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  15797. }
  15798. if (allowDuplicate) {
  15799. this._selectionContent.concat(this.dynamicContent);
  15800. }
  15801. else {
  15802. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15803. }
  15804. return this._selectionContent;
  15805. };
  15806. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  15807. this._selectionContent.reset();
  15808. for (var index = 0; index < this.blocks.length; index++) {
  15809. var block = this.blocks[index];
  15810. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  15811. }
  15812. if (allowDuplicate) {
  15813. this._selectionContent.concat(this.dynamicContent);
  15814. }
  15815. else {
  15816. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15817. }
  15818. return this._selectionContent;
  15819. };
  15820. Octree.prototype.intersectsRay = function (ray) {
  15821. this._selectionContent.reset();
  15822. for (var index = 0; index < this.blocks.length; index++) {
  15823. var block = this.blocks[index];
  15824. block.intersectsRay(ray, this._selectionContent);
  15825. }
  15826. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15827. return this._selectionContent;
  15828. };
  15829. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  15830. target.blocks = new Array();
  15831. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  15832. for (var x = 0; x < 2; x++) {
  15833. for (var y = 0; y < 2; y++) {
  15834. for (var z = 0; z < 2; z++) {
  15835. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  15836. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  15837. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  15838. block.addEntries(entries);
  15839. target.blocks.push(block);
  15840. }
  15841. }
  15842. }
  15843. };
  15844. Octree.CreationFuncForMeshes = function (entry, block) {
  15845. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15846. block.entries.push(entry);
  15847. }
  15848. };
  15849. Octree.CreationFuncForSubMeshes = function (entry, block) {
  15850. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15851. block.entries.push(entry);
  15852. }
  15853. };
  15854. return Octree;
  15855. })();
  15856. BABYLON.Octree = Octree;
  15857. })(BABYLON || (BABYLON = {}));
  15858. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  15859. (function (BABYLON) {
  15860. var OctreeBlock = (function () {
  15861. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  15862. this.entries = new Array();
  15863. this._boundingVectors = new Array();
  15864. this._capacity = capacity;
  15865. this._depth = depth;
  15866. this._maxDepth = maxDepth;
  15867. this._creationFunc = creationFunc;
  15868. this._minPoint = minPoint;
  15869. this._maxPoint = maxPoint;
  15870. this._boundingVectors.push(minPoint.clone());
  15871. this._boundingVectors.push(maxPoint.clone());
  15872. this._boundingVectors.push(minPoint.clone());
  15873. this._boundingVectors[2].x = maxPoint.x;
  15874. this._boundingVectors.push(minPoint.clone());
  15875. this._boundingVectors[3].y = maxPoint.y;
  15876. this._boundingVectors.push(minPoint.clone());
  15877. this._boundingVectors[4].z = maxPoint.z;
  15878. this._boundingVectors.push(maxPoint.clone());
  15879. this._boundingVectors[5].z = minPoint.z;
  15880. this._boundingVectors.push(maxPoint.clone());
  15881. this._boundingVectors[6].x = minPoint.x;
  15882. this._boundingVectors.push(maxPoint.clone());
  15883. this._boundingVectors[7].y = minPoint.y;
  15884. }
  15885. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  15886. // Property
  15887. get: function () {
  15888. return this._capacity;
  15889. },
  15890. enumerable: true,
  15891. configurable: true
  15892. });
  15893. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  15894. get: function () {
  15895. return this._minPoint;
  15896. },
  15897. enumerable: true,
  15898. configurable: true
  15899. });
  15900. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  15901. get: function () {
  15902. return this._maxPoint;
  15903. },
  15904. enumerable: true,
  15905. configurable: true
  15906. });
  15907. // Methods
  15908. OctreeBlock.prototype.addEntry = function (entry) {
  15909. if (this.blocks) {
  15910. for (var index = 0; index < this.blocks.length; index++) {
  15911. var block = this.blocks[index];
  15912. block.addEntry(entry);
  15913. }
  15914. return;
  15915. }
  15916. this._creationFunc(entry, this);
  15917. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  15918. this.createInnerBlocks();
  15919. }
  15920. };
  15921. OctreeBlock.prototype.addEntries = function (entries) {
  15922. for (var index = 0; index < entries.length; index++) {
  15923. var mesh = entries[index];
  15924. this.addEntry(mesh);
  15925. }
  15926. };
  15927. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  15928. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  15929. if (this.blocks) {
  15930. for (var index = 0; index < this.blocks.length; index++) {
  15931. var block = this.blocks[index];
  15932. block.select(frustumPlanes, selection, allowDuplicate);
  15933. }
  15934. return;
  15935. }
  15936. if (allowDuplicate) {
  15937. selection.concat(this.entries);
  15938. }
  15939. else {
  15940. selection.concatWithNoDuplicate(this.entries);
  15941. }
  15942. }
  15943. };
  15944. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  15945. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  15946. if (this.blocks) {
  15947. for (var index = 0; index < this.blocks.length; index++) {
  15948. var block = this.blocks[index];
  15949. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  15950. }
  15951. return;
  15952. }
  15953. if (allowDuplicate) {
  15954. selection.concat(this.entries);
  15955. }
  15956. else {
  15957. selection.concatWithNoDuplicate(this.entries);
  15958. }
  15959. }
  15960. };
  15961. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  15962. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  15963. if (this.blocks) {
  15964. for (var index = 0; index < this.blocks.length; index++) {
  15965. var block = this.blocks[index];
  15966. block.intersectsRay(ray, selection);
  15967. }
  15968. return;
  15969. }
  15970. selection.concatWithNoDuplicate(this.entries);
  15971. }
  15972. };
  15973. OctreeBlock.prototype.createInnerBlocks = function () {
  15974. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  15975. };
  15976. return OctreeBlock;
  15977. })();
  15978. BABYLON.OctreeBlock = OctreeBlock;
  15979. })(BABYLON || (BABYLON = {}));
  15980. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  15981. (function (BABYLON) {
  15982. var Bone = (function () {
  15983. function Bone(name, skeleton, parentBone, matrix) {
  15984. this.name = name;
  15985. this.children = new Array();
  15986. this.animations = new Array();
  15987. this._worldTransform = new BABYLON.Matrix();
  15988. this._absoluteTransform = new BABYLON.Matrix();
  15989. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  15990. this._skeleton = skeleton;
  15991. this._matrix = matrix;
  15992. this._baseMatrix = matrix;
  15993. skeleton.bones.push(this);
  15994. if (parentBone) {
  15995. this._parent = parentBone;
  15996. parentBone.children.push(this);
  15997. }
  15998. else {
  15999. this._parent = null;
  16000. }
  16001. this._updateDifferenceMatrix();
  16002. }
  16003. // Members
  16004. Bone.prototype.getParent = function () {
  16005. return this._parent;
  16006. };
  16007. Bone.prototype.getLocalMatrix = function () {
  16008. return this._matrix;
  16009. };
  16010. Bone.prototype.getBaseMatrix = function () {
  16011. return this._baseMatrix;
  16012. };
  16013. Bone.prototype.getWorldMatrix = function () {
  16014. return this._worldTransform;
  16015. };
  16016. Bone.prototype.getInvertedAbsoluteTransform = function () {
  16017. return this._invertedAbsoluteTransform;
  16018. };
  16019. Bone.prototype.getAbsoluteMatrix = function () {
  16020. var matrix = this._matrix.clone();
  16021. var parent = this._parent;
  16022. while (parent) {
  16023. matrix = matrix.multiply(parent.getLocalMatrix());
  16024. parent = parent.getParent();
  16025. }
  16026. return matrix;
  16027. };
  16028. // Methods
  16029. Bone.prototype.updateMatrix = function (matrix) {
  16030. this._matrix = matrix;
  16031. this._skeleton._markAsDirty();
  16032. this._updateDifferenceMatrix();
  16033. };
  16034. Bone.prototype._updateDifferenceMatrix = function () {
  16035. if (this._parent) {
  16036. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  16037. }
  16038. else {
  16039. this._absoluteTransform.copyFrom(this._matrix);
  16040. }
  16041. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  16042. for (var index = 0; index < this.children.length; index++) {
  16043. this.children[index]._updateDifferenceMatrix();
  16044. }
  16045. };
  16046. Bone.prototype.markAsDirty = function () {
  16047. this._skeleton._markAsDirty();
  16048. };
  16049. return Bone;
  16050. })();
  16051. BABYLON.Bone = Bone;
  16052. })(BABYLON || (BABYLON = {}));
  16053. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16054. (function (BABYLON) {
  16055. var Skeleton = (function () {
  16056. function Skeleton(name, id, scene) {
  16057. this.name = name;
  16058. this.id = id;
  16059. this.bones = new Array();
  16060. this._isDirty = true;
  16061. this._identity = BABYLON.Matrix.Identity();
  16062. this.bones = [];
  16063. this._scene = scene;
  16064. scene.skeletons.push(this);
  16065. }
  16066. // Members
  16067. Skeleton.prototype.getTransformMatrices = function () {
  16068. return this._transformMatrices;
  16069. };
  16070. // Methods
  16071. Skeleton.prototype._markAsDirty = function () {
  16072. this._isDirty = true;
  16073. };
  16074. Skeleton.prototype.prepare = function () {
  16075. if (!this._isDirty) {
  16076. return;
  16077. }
  16078. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16079. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16080. }
  16081. for (var index = 0; index < this.bones.length; index++) {
  16082. var bone = this.bones[index];
  16083. var parentBone = bone.getParent();
  16084. if (parentBone) {
  16085. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16086. }
  16087. else {
  16088. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16089. }
  16090. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16091. }
  16092. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16093. this._isDirty = false;
  16094. };
  16095. Skeleton.prototype.getAnimatables = function () {
  16096. if (!this._animatables || this._animatables.length != this.bones.length) {
  16097. this._animatables = [];
  16098. for (var index = 0; index < this.bones.length; index++) {
  16099. this._animatables.push(this.bones[index]);
  16100. }
  16101. }
  16102. return this._animatables;
  16103. };
  16104. Skeleton.prototype.clone = function (name, id) {
  16105. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  16106. for (var index = 0; index < this.bones.length; index++) {
  16107. var source = this.bones[index];
  16108. var parentBone = null;
  16109. if (source.getParent()) {
  16110. var parentIndex = this.bones.indexOf(source.getParent());
  16111. parentBone = result.bones[parentIndex];
  16112. }
  16113. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16114. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16115. }
  16116. return result;
  16117. };
  16118. return Skeleton;
  16119. })();
  16120. BABYLON.Skeleton = Skeleton;
  16121. })(BABYLON || (BABYLON = {}));
  16122. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16123. (function (BABYLON) {
  16124. var PostProcess = (function () {
  16125. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  16126. this.name = name;
  16127. this.width = -1;
  16128. this.height = -1;
  16129. this._reusable = false;
  16130. this._textures = new BABYLON.SmartArray(2);
  16131. this._currentRenderTextureInd = 0;
  16132. if (camera != null) {
  16133. this._camera = camera;
  16134. this._scene = camera.getScene();
  16135. camera.attachPostProcess(this);
  16136. this._engine = this._scene.getEngine();
  16137. }
  16138. else {
  16139. this._engine = engine;
  16140. }
  16141. this._renderRatio = ratio;
  16142. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16143. this._reusable = reusable || false;
  16144. samplers = samplers || [];
  16145. samplers.push("textureSampler");
  16146. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  16147. }
  16148. PostProcess.prototype.isReusable = function () {
  16149. return this._reusable;
  16150. };
  16151. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16152. camera = camera || this._camera;
  16153. var scene = camera.getScene();
  16154. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16155. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16156. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16157. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16158. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16159. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16160. if (this._textures.length > 0) {
  16161. for (var i = 0; i < this._textures.length; i++) {
  16162. this._engine._releaseTexture(this._textures.data[i]);
  16163. }
  16164. this._textures.reset();
  16165. }
  16166. this.width = desiredWidth;
  16167. this.height = desiredHeight;
  16168. 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 }));
  16169. if (this._reusable) {
  16170. 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 }));
  16171. }
  16172. if (this.onSizeChanged) {
  16173. this.onSizeChanged();
  16174. }
  16175. }
  16176. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16177. if (this.onActivate) {
  16178. this.onActivate(camera);
  16179. }
  16180. // Clear
  16181. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16182. if (this._reusable) {
  16183. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16184. }
  16185. };
  16186. PostProcess.prototype.apply = function () {
  16187. // Check
  16188. if (!this._effect.isReady())
  16189. return null;
  16190. // States
  16191. this._engine.enableEffect(this._effect);
  16192. this._engine.setState(false);
  16193. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16194. this._engine.setDepthBuffer(false);
  16195. this._engine.setDepthWrite(false);
  16196. // Texture
  16197. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16198. // Parameters
  16199. if (this.onApply) {
  16200. this.onApply(this._effect);
  16201. }
  16202. return this._effect;
  16203. };
  16204. PostProcess.prototype.dispose = function (camera) {
  16205. camera = camera || this._camera;
  16206. if (this._textures.length > 0) {
  16207. for (var i = 0; i < this._textures.length; i++) {
  16208. this._engine._releaseTexture(this._textures.data[i]);
  16209. }
  16210. this._textures.reset();
  16211. }
  16212. camera.detachPostProcess(this);
  16213. var index = camera._postProcesses.indexOf(this);
  16214. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  16215. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  16216. }
  16217. };
  16218. return PostProcess;
  16219. })();
  16220. BABYLON.PostProcess = PostProcess;
  16221. })(BABYLON || (BABYLON = {}));
  16222. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  16223. (function (BABYLON) {
  16224. var PostProcessManager = (function () {
  16225. function PostProcessManager(scene) {
  16226. this._vertexDeclaration = [2];
  16227. this._vertexStrideSize = 2 * 4;
  16228. this._scene = scene;
  16229. // VBO
  16230. var vertices = [];
  16231. vertices.push(1, 1);
  16232. vertices.push(-1, 1);
  16233. vertices.push(-1, -1);
  16234. vertices.push(1, -1);
  16235. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16236. // Indices
  16237. var indices = [];
  16238. indices.push(0);
  16239. indices.push(1);
  16240. indices.push(2);
  16241. indices.push(0);
  16242. indices.push(2);
  16243. indices.push(3);
  16244. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16245. }
  16246. // Methods
  16247. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16248. var postProcesses = this._scene.activeCamera._postProcesses;
  16249. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16250. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16251. return false;
  16252. }
  16253. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16254. return true;
  16255. };
  16256. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  16257. var postProcesses = this._scene.activeCamera._postProcesses;
  16258. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16259. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16260. return;
  16261. }
  16262. var engine = this._scene.getEngine();
  16263. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  16264. if (index < postProcessesTakenIndices.length - 1) {
  16265. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  16266. }
  16267. else {
  16268. if (targetTexture) {
  16269. engine.bindFramebuffer(targetTexture);
  16270. }
  16271. else {
  16272. engine.restoreDefaultFramebuffer();
  16273. }
  16274. }
  16275. if (doNotPresent) {
  16276. break;
  16277. }
  16278. var pp = postProcesses[postProcessesTakenIndices[index]];
  16279. var effect = pp.apply();
  16280. if (effect) {
  16281. if (pp.onBeforeRender) {
  16282. pp.onBeforeRender(effect);
  16283. }
  16284. // VBOs
  16285. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16286. // Draw order
  16287. engine.draw(true, 0, 6);
  16288. }
  16289. }
  16290. // Restore depth buffer
  16291. engine.setDepthBuffer(true);
  16292. engine.setDepthWrite(true);
  16293. };
  16294. PostProcessManager.prototype.dispose = function () {
  16295. if (this._vertexBuffer) {
  16296. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16297. this._vertexBuffer = null;
  16298. }
  16299. if (this._indexBuffer) {
  16300. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16301. this._indexBuffer = null;
  16302. }
  16303. };
  16304. return PostProcessManager;
  16305. })();
  16306. BABYLON.PostProcessManager = PostProcessManager;
  16307. })(BABYLON || (BABYLON = {}));
  16308. //# sourceMappingURL=babylon.postProcessManager.js.map
  16309. var BABYLON;
  16310. (function (BABYLON) {
  16311. var PassPostProcess = (function (_super) {
  16312. __extends(PassPostProcess, _super);
  16313. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16314. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  16315. }
  16316. return PassPostProcess;
  16317. })(BABYLON.PostProcess);
  16318. BABYLON.PassPostProcess = PassPostProcess;
  16319. })(BABYLON || (BABYLON = {}));
  16320. //# sourceMappingURL=babylon.passPostProcess.js.map
  16321. var BABYLON;
  16322. (function (BABYLON) {
  16323. var BlurPostProcess = (function (_super) {
  16324. __extends(BlurPostProcess, _super);
  16325. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  16326. var _this = this;
  16327. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  16328. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  16329. this.direction = direction;
  16330. this.blurWidth = blurWidth;
  16331. this.onApply = function (effect) {
  16332. effect.setFloat2("screenSize", _this.width, _this.height);
  16333. effect.setVector2("direction", _this.direction);
  16334. effect.setFloat("blurWidth", _this.blurWidth);
  16335. };
  16336. }
  16337. return BlurPostProcess;
  16338. })(BABYLON.PostProcess);
  16339. BABYLON.BlurPostProcess = BlurPostProcess;
  16340. })(BABYLON || (BABYLON = {}));
  16341. //# sourceMappingURL=babylon.blurPostProcess.js.map
  16342. var BABYLON;
  16343. (function (BABYLON) {
  16344. var FilterPostProcess = (function (_super) {
  16345. __extends(FilterPostProcess, _super);
  16346. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  16347. var _this = this;
  16348. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  16349. this.kernelMatrix = kernelMatrix;
  16350. this.onApply = function (effect) {
  16351. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  16352. };
  16353. }
  16354. return FilterPostProcess;
  16355. })(BABYLON.PostProcess);
  16356. BABYLON.FilterPostProcess = FilterPostProcess;
  16357. })(BABYLON || (BABYLON = {}));
  16358. //# sourceMappingURL=babylon.filterPostProcess.js.map
  16359. var BABYLON;
  16360. (function (BABYLON) {
  16361. var RefractionPostProcess = (function (_super) {
  16362. __extends(RefractionPostProcess, _super);
  16363. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  16364. var _this = this;
  16365. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  16366. this.color = color;
  16367. this.depth = depth;
  16368. this.colorLevel = colorLevel;
  16369. this.onActivate = function (cam) {
  16370. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  16371. };
  16372. this.onApply = function (effect) {
  16373. effect.setColor3("baseColor", _this.color);
  16374. effect.setFloat("depth", _this.depth);
  16375. effect.setFloat("colorLevel", _this.colorLevel);
  16376. effect.setTexture("refractionSampler", _this._refRexture);
  16377. };
  16378. }
  16379. // Methods
  16380. RefractionPostProcess.prototype.dispose = function (camera) {
  16381. if (this._refRexture) {
  16382. this._refRexture.dispose();
  16383. }
  16384. _super.prototype.dispose.call(this, camera);
  16385. };
  16386. return RefractionPostProcess;
  16387. })(BABYLON.PostProcess);
  16388. BABYLON.RefractionPostProcess = RefractionPostProcess;
  16389. })(BABYLON || (BABYLON = {}));
  16390. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  16391. var BABYLON;
  16392. (function (BABYLON) {
  16393. var BlackAndWhitePostProcess = (function (_super) {
  16394. __extends(BlackAndWhitePostProcess, _super);
  16395. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16396. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  16397. }
  16398. return BlackAndWhitePostProcess;
  16399. })(BABYLON.PostProcess);
  16400. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  16401. })(BABYLON || (BABYLON = {}));
  16402. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  16403. var BABYLON;
  16404. (function (BABYLON) {
  16405. var ConvolutionPostProcess = (function (_super) {
  16406. __extends(ConvolutionPostProcess, _super);
  16407. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  16408. var _this = this;
  16409. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  16410. this.kernel = kernel;
  16411. this.onApply = function (effect) {
  16412. effect.setFloat2("screenSize", _this.width, _this.height);
  16413. effect.setArray("kernel", _this.kernel);
  16414. };
  16415. }
  16416. // Statics
  16417. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  16418. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  16419. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  16420. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  16421. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  16422. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  16423. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  16424. return ConvolutionPostProcess;
  16425. })(BABYLON.PostProcess);
  16426. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  16427. })(BABYLON || (BABYLON = {}));
  16428. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  16429. var BABYLON;
  16430. (function (BABYLON) {
  16431. var FxaaPostProcess = (function (_super) {
  16432. __extends(FxaaPostProcess, _super);
  16433. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16434. var _this = this;
  16435. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  16436. this.onSizeChanged = function () {
  16437. _this.texelWidth = 1.0 / _this.width;
  16438. _this.texelHeight = 1.0 / _this.height;
  16439. };
  16440. this.onApply = function (effect) {
  16441. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  16442. };
  16443. }
  16444. return FxaaPostProcess;
  16445. })(BABYLON.PostProcess);
  16446. BABYLON.FxaaPostProcess = FxaaPostProcess;
  16447. })(BABYLON || (BABYLON = {}));
  16448. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  16449. (function (BABYLON) {
  16450. var LensFlare = (function () {
  16451. function LensFlare(size, position, color, imgUrl, system) {
  16452. this.size = size;
  16453. this.position = position;
  16454. this.dispose = function () {
  16455. if (this.texture) {
  16456. this.texture.dispose();
  16457. }
  16458. // Remove from scene
  16459. var index = this._system.lensFlares.indexOf(this);
  16460. this._system.lensFlares.splice(index, 1);
  16461. };
  16462. this.color = color || new BABYLON.Color3(1, 1, 1);
  16463. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  16464. this._system = system;
  16465. system.lensFlares.push(this);
  16466. }
  16467. return LensFlare;
  16468. })();
  16469. BABYLON.LensFlare = LensFlare;
  16470. })(BABYLON || (BABYLON = {}));
  16471. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  16472. (function (BABYLON) {
  16473. var LensFlareSystem = (function () {
  16474. function LensFlareSystem(name, emitter, scene) {
  16475. this.name = name;
  16476. this.lensFlares = new Array();
  16477. this.borderLimit = 300;
  16478. this._vertexDeclaration = [2];
  16479. this._vertexStrideSize = 2 * 4;
  16480. this._isEnabled = true;
  16481. this._scene = scene;
  16482. this._emitter = emitter;
  16483. scene.lensFlareSystems.push(this);
  16484. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  16485. // VBO
  16486. var vertices = [];
  16487. vertices.push(1, 1);
  16488. vertices.push(-1, 1);
  16489. vertices.push(-1, -1);
  16490. vertices.push(1, -1);
  16491. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16492. // Indices
  16493. var indices = [];
  16494. indices.push(0);
  16495. indices.push(1);
  16496. indices.push(2);
  16497. indices.push(0);
  16498. indices.push(2);
  16499. indices.push(3);
  16500. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16501. // Effects
  16502. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  16503. }
  16504. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  16505. get: function () {
  16506. return this._isEnabled;
  16507. },
  16508. set: function (value) {
  16509. this._isEnabled = value;
  16510. },
  16511. enumerable: true,
  16512. configurable: true
  16513. });
  16514. LensFlareSystem.prototype.getScene = function () {
  16515. return this._scene;
  16516. };
  16517. LensFlareSystem.prototype.getEmitter = function () {
  16518. return this._emitter;
  16519. };
  16520. LensFlareSystem.prototype.getEmitterPosition = function () {
  16521. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  16522. };
  16523. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  16524. var position = this.getEmitterPosition();
  16525. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  16526. this._positionX = position.x;
  16527. this._positionY = position.y;
  16528. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  16529. if (position.z > 0) {
  16530. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  16531. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  16532. return true;
  16533. }
  16534. }
  16535. return false;
  16536. };
  16537. LensFlareSystem.prototype._isVisible = function () {
  16538. if (!this._isEnabled) {
  16539. return false;
  16540. }
  16541. var emitterPosition = this.getEmitterPosition();
  16542. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  16543. var distance = direction.length();
  16544. direction.normalize();
  16545. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  16546. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  16547. return !pickInfo.hit || pickInfo.distance > distance;
  16548. };
  16549. LensFlareSystem.prototype.render = function () {
  16550. if (!this._effect.isReady())
  16551. return false;
  16552. var engine = this._scene.getEngine();
  16553. var viewport = this._scene.activeCamera.viewport;
  16554. var globalViewport = viewport.toGlobal(engine);
  16555. // Position
  16556. if (!this.computeEffectivePosition(globalViewport)) {
  16557. return false;
  16558. }
  16559. // Visibility
  16560. if (!this._isVisible()) {
  16561. return false;
  16562. }
  16563. // Intensity
  16564. var awayX;
  16565. var awayY;
  16566. if (this._positionX < this.borderLimit + globalViewport.x) {
  16567. awayX = this.borderLimit + globalViewport.x - this._positionX;
  16568. }
  16569. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  16570. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  16571. }
  16572. else {
  16573. awayX = 0;
  16574. }
  16575. if (this._positionY < this.borderLimit + globalViewport.y) {
  16576. awayY = this.borderLimit + globalViewport.y - this._positionY;
  16577. }
  16578. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  16579. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  16580. }
  16581. else {
  16582. awayY = 0;
  16583. }
  16584. var away = (awayX > awayY) ? awayX : awayY;
  16585. if (away > this.borderLimit) {
  16586. away = this.borderLimit;
  16587. }
  16588. var intensity = 1.0 - (away / this.borderLimit);
  16589. if (intensity < 0) {
  16590. return false;
  16591. }
  16592. if (intensity > 1.0) {
  16593. intensity = 1.0;
  16594. }
  16595. // Position
  16596. var centerX = globalViewport.x + globalViewport.width / 2;
  16597. var centerY = globalViewport.y + globalViewport.height / 2;
  16598. var distX = centerX - this._positionX;
  16599. var distY = centerY - this._positionY;
  16600. // Effects
  16601. engine.enableEffect(this._effect);
  16602. engine.setState(false);
  16603. engine.setDepthBuffer(false);
  16604. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16605. // VBOs
  16606. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16607. for (var index = 0; index < this.lensFlares.length; index++) {
  16608. var flare = this.lensFlares[index];
  16609. var x = centerX - (distX * flare.position);
  16610. var y = centerY - (distY * flare.position);
  16611. var cw = flare.size;
  16612. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  16613. var cx = 2 * (x / globalViewport.width) - 1.0;
  16614. var cy = 1.0 - 2 * (y / globalViewport.height);
  16615. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  16616. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  16617. // Texture
  16618. this._effect.setTexture("textureSampler", flare.texture);
  16619. // Color
  16620. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  16621. // Draw order
  16622. engine.draw(true, 0, 6);
  16623. }
  16624. engine.setDepthBuffer(true);
  16625. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16626. return true;
  16627. };
  16628. LensFlareSystem.prototype.dispose = function () {
  16629. if (this._vertexBuffer) {
  16630. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16631. this._vertexBuffer = null;
  16632. }
  16633. if (this._indexBuffer) {
  16634. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16635. this._indexBuffer = null;
  16636. }
  16637. while (this.lensFlares.length) {
  16638. this.lensFlares[0].dispose();
  16639. }
  16640. // Remove from scene
  16641. var index = this._scene.lensFlareSystems.indexOf(this);
  16642. this._scene.lensFlareSystems.splice(index, 1);
  16643. };
  16644. return LensFlareSystem;
  16645. })();
  16646. BABYLON.LensFlareSystem = LensFlareSystem;
  16647. })(BABYLON || (BABYLON = {}));
  16648. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  16649. (function (BABYLON) {
  16650. var IntersectionInfo = (function () {
  16651. function IntersectionInfo(bu, bv, distance) {
  16652. this.bu = bu;
  16653. this.bv = bv;
  16654. this.distance = distance;
  16655. this.faceId = 0;
  16656. }
  16657. return IntersectionInfo;
  16658. })();
  16659. BABYLON.IntersectionInfo = IntersectionInfo;
  16660. var PickingInfo = (function () {
  16661. function PickingInfo() {
  16662. this.hit = false;
  16663. this.distance = 0;
  16664. this.pickedPoint = null;
  16665. this.pickedMesh = null;
  16666. this.bu = 0;
  16667. this.bv = 0;
  16668. this.faceId = -1;
  16669. }
  16670. // Methods
  16671. PickingInfo.prototype.getNormal = function () {
  16672. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16673. return null;
  16674. }
  16675. var indices = this.pickedMesh.getIndices();
  16676. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16677. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  16678. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  16679. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  16680. normal0 = normal0.scale(this.bu);
  16681. normal1 = normal1.scale(this.bv);
  16682. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  16683. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  16684. };
  16685. PickingInfo.prototype.getTextureCoordinates = function () {
  16686. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16687. return null;
  16688. }
  16689. var indices = this.pickedMesh.getIndices();
  16690. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16691. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  16692. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  16693. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  16694. uv0 = uv0.scale(this.bu);
  16695. uv1 = uv1.scale(this.bv);
  16696. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  16697. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  16698. };
  16699. return PickingInfo;
  16700. })();
  16701. BABYLON.PickingInfo = PickingInfo;
  16702. })(BABYLON || (BABYLON = {}));
  16703. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  16704. (function (BABYLON) {
  16705. var FilesInput = (function () {
  16706. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  16707. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  16708. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  16709. this.engine = p_engine;
  16710. this.canvas = p_canvas;
  16711. this.currentScene = p_scene;
  16712. this.sceneLoadedCallback = p_sceneLoadedCallback;
  16713. this.progressCallback = p_progressCallback;
  16714. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  16715. this.textureLoadingCallback = p_textureLoadingCallback;
  16716. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  16717. }
  16718. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  16719. var _this = this;
  16720. if (p_elementToMonitor) {
  16721. this.elementToMonitor = p_elementToMonitor;
  16722. this.elementToMonitor.addEventListener("dragenter", function (e) {
  16723. _this.drag(e);
  16724. }, false);
  16725. this.elementToMonitor.addEventListener("dragover", function (e) {
  16726. _this.drag(e);
  16727. }, false);
  16728. this.elementToMonitor.addEventListener("drop", function (e) {
  16729. _this.drop(e);
  16730. }, false);
  16731. }
  16732. };
  16733. FilesInput.prototype.renderFunction = function () {
  16734. if (this.additionnalRenderLoopLogicCallback) {
  16735. this.additionnalRenderLoopLogicCallback();
  16736. }
  16737. if (this.currentScene) {
  16738. if (this.textureLoadingCallback) {
  16739. var remaining = this.currentScene.getWaitingItemsCount();
  16740. if (remaining > 0) {
  16741. this.textureLoadingCallback(remaining);
  16742. }
  16743. }
  16744. this.currentScene.render();
  16745. }
  16746. };
  16747. FilesInput.prototype.drag = function (e) {
  16748. e.stopPropagation();
  16749. e.preventDefault();
  16750. };
  16751. FilesInput.prototype.drop = function (eventDrop) {
  16752. eventDrop.stopPropagation();
  16753. eventDrop.preventDefault();
  16754. this.loadFiles(eventDrop);
  16755. };
  16756. FilesInput.prototype.loadFiles = function (event) {
  16757. var _this = this;
  16758. var that = this;
  16759. if (this.startingProcessingFilesCallback)
  16760. this.startingProcessingFilesCallback();
  16761. var sceneFileToLoad;
  16762. var filesToLoad;
  16763. // Handling data transfer via drag'n'drop
  16764. if (event && event.dataTransfer && event.dataTransfer.files) {
  16765. filesToLoad = event.dataTransfer.files;
  16766. }
  16767. // Handling files from input files
  16768. if (event && event.target && event.target.files) {
  16769. filesToLoad = event.target.files;
  16770. }
  16771. if (filesToLoad && filesToLoad.length > 0) {
  16772. for (var i = 0; i < filesToLoad.length; i++) {
  16773. switch (filesToLoad[i].type) {
  16774. case "image/jpeg":
  16775. case "image/png":
  16776. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  16777. break;
  16778. case "image/targa":
  16779. case "image/vnd.ms-dds":
  16780. case "audio/wav":
  16781. case "audio/x-wav":
  16782. case "audio/mpeg":
  16783. case "audio/mpeg3":
  16784. case "audio/x-mpeg-3":
  16785. case "audio/ogg":
  16786. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  16787. break;
  16788. default:
  16789. 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) {
  16790. sceneFileToLoad = filesToLoad[i];
  16791. }
  16792. break;
  16793. }
  16794. }
  16795. // If a ".babylon" file has been provided
  16796. if (sceneFileToLoad) {
  16797. if (this.currentScene) {
  16798. this.engine.stopRenderLoop();
  16799. this.currentScene.dispose();
  16800. }
  16801. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  16802. that.currentScene = newScene;
  16803. // Wait for textures and shaders to be ready
  16804. that.currentScene.executeWhenReady(function () {
  16805. // Attach camera to canvas inputs
  16806. if (that.currentScene.activeCamera) {
  16807. that.currentScene.activeCamera.attachControl(that.canvas);
  16808. }
  16809. if (that.sceneLoadedCallback) {
  16810. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  16811. }
  16812. that.engine.runRenderLoop(function () {
  16813. that.renderFunction();
  16814. });
  16815. });
  16816. }, function (progress) {
  16817. if (_this.progressCallback) {
  16818. _this.progressCallback(progress);
  16819. }
  16820. });
  16821. }
  16822. else {
  16823. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  16824. }
  16825. }
  16826. };
  16827. FilesInput.FilesTextures = new Array();
  16828. FilesInput.FilesToLoad = new Array();
  16829. return FilesInput;
  16830. })();
  16831. BABYLON.FilesInput = FilesInput;
  16832. })(BABYLON || (BABYLON = {}));
  16833. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  16834. (function (BABYLON) {
  16835. var OimoJSPlugin = (function () {
  16836. function OimoJSPlugin() {
  16837. this._registeredMeshes = [];
  16838. /**
  16839. * Update the body position according to the mesh position
  16840. * @param mesh
  16841. */
  16842. this.updateBodyPosition = function (mesh) {
  16843. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16844. var registeredMesh = this._registeredMeshes[index];
  16845. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16846. var body = registeredMesh.body.body;
  16847. mesh.computeWorldMatrix(true);
  16848. var center = mesh.getBoundingInfo().boundingBox.center;
  16849. body.setPosition(center.x, center.y, center.z);
  16850. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  16851. return;
  16852. }
  16853. // Case where the parent has been updated
  16854. if (registeredMesh.mesh.parent === mesh) {
  16855. mesh.computeWorldMatrix(true);
  16856. registeredMesh.mesh.computeWorldMatrix(true);
  16857. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  16858. var absoluteRotation = mesh.rotation;
  16859. body = registeredMesh.body.body;
  16860. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  16861. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  16862. return;
  16863. }
  16864. }
  16865. };
  16866. }
  16867. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  16868. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  16869. };
  16870. OimoJSPlugin.prototype.initialize = function (iterations) {
  16871. this._world = new OIMO.World();
  16872. this._world.clear();
  16873. };
  16874. OimoJSPlugin.prototype.setGravity = function (gravity) {
  16875. this._world.gravity = gravity;
  16876. };
  16877. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  16878. var body = null;
  16879. this.unregisterMesh(mesh);
  16880. mesh.computeWorldMatrix(true);
  16881. switch (impostor) {
  16882. case BABYLON.PhysicsEngine.SphereImpostor:
  16883. var initialRotation = null;
  16884. if (mesh.rotationQuaternion) {
  16885. initialRotation = mesh.rotationQuaternion.clone();
  16886. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16887. mesh.computeWorldMatrix(true);
  16888. }
  16889. var bbox = mesh.getBoundingInfo().boundingBox;
  16890. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16891. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16892. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16893. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16894. // The delta between the mesh position and the mesh bounding box center
  16895. var deltaPosition = mesh.position.subtract(bbox.center);
  16896. // Transform delta position with the rotation
  16897. if (initialRotation) {
  16898. var m = new BABYLON.Matrix();
  16899. initialRotation.toRotationMatrix(m);
  16900. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16901. }
  16902. body = new OIMO.Body({
  16903. type: 'sphere',
  16904. size: [size],
  16905. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16906. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16907. move: options.mass != 0,
  16908. config: [options.mass, options.friction, options.restitution],
  16909. world: this._world
  16910. });
  16911. // Restore rotation
  16912. if (initialRotation) {
  16913. body.setQuaternion(initialRotation);
  16914. }
  16915. this._registeredMeshes.push({
  16916. mesh: mesh,
  16917. body: body,
  16918. delta: deltaPosition
  16919. });
  16920. break;
  16921. case BABYLON.PhysicsEngine.PlaneImpostor:
  16922. case BABYLON.PhysicsEngine.BoxImpostor:
  16923. initialRotation = null;
  16924. if (mesh.rotationQuaternion) {
  16925. initialRotation = mesh.rotationQuaternion.clone();
  16926. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16927. mesh.computeWorldMatrix(true);
  16928. }
  16929. bbox = mesh.getBoundingInfo().boundingBox;
  16930. var min = bbox.minimumWorld;
  16931. var max = bbox.maximumWorld;
  16932. var box = max.subtract(min);
  16933. var sizeX = this._checkWithEpsilon(box.x);
  16934. var sizeY = this._checkWithEpsilon(box.y);
  16935. var sizeZ = this._checkWithEpsilon(box.z);
  16936. // The delta between the mesh position and the mesh boudning box center
  16937. deltaPosition = mesh.position.subtract(bbox.center);
  16938. // Transform delta position with the rotation
  16939. if (initialRotation) {
  16940. m = new BABYLON.Matrix();
  16941. initialRotation.toRotationMatrix(m);
  16942. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16943. }
  16944. body = new OIMO.Body({
  16945. type: 'box',
  16946. size: [sizeX, sizeY, sizeZ],
  16947. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16948. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16949. move: options.mass != 0,
  16950. config: [options.mass, options.friction, options.restitution],
  16951. world: this._world
  16952. });
  16953. if (initialRotation) {
  16954. body.setQuaternion(initialRotation);
  16955. }
  16956. this._registeredMeshes.push({
  16957. mesh: mesh,
  16958. body: body,
  16959. delta: deltaPosition
  16960. });
  16961. break;
  16962. }
  16963. return body;
  16964. };
  16965. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  16966. var types = [], sizes = [], positions = [], rotations = [];
  16967. var initialMesh = parts[0].mesh;
  16968. for (var index = 0; index < parts.length; index++) {
  16969. var part = parts[index];
  16970. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  16971. types.push(bodyParameters.type);
  16972. sizes.push.apply(sizes, bodyParameters.size);
  16973. positions.push.apply(positions, bodyParameters.pos);
  16974. rotations.push.apply(rotations, bodyParameters.rot);
  16975. }
  16976. var body = new OIMO.Body({
  16977. type: types,
  16978. size: sizes,
  16979. pos: positions,
  16980. rot: rotations,
  16981. move: options.mass != 0,
  16982. config: [options.mass, options.friction, options.restitution],
  16983. world: this._world
  16984. });
  16985. this._registeredMeshes.push({
  16986. mesh: initialMesh,
  16987. body: body
  16988. });
  16989. return body;
  16990. };
  16991. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  16992. var bodyParameters = null;
  16993. var mesh = part.mesh;
  16994. // We need the bounding box/sphere info to compute the physics body
  16995. mesh.computeWorldMatrix();
  16996. switch (part.impostor) {
  16997. case BABYLON.PhysicsEngine.SphereImpostor:
  16998. var bbox = mesh.getBoundingInfo().boundingBox;
  16999. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17000. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17001. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17002. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17003. bodyParameters = {
  17004. type: 'sphere',
  17005. /* bug with oimo : sphere needs 3 sizes in this case */
  17006. size: [size, -1, -1],
  17007. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  17008. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17009. };
  17010. break;
  17011. case BABYLON.PhysicsEngine.PlaneImpostor:
  17012. case BABYLON.PhysicsEngine.BoxImpostor:
  17013. bbox = mesh.getBoundingInfo().boundingBox;
  17014. var min = bbox.minimumWorld;
  17015. var max = bbox.maximumWorld;
  17016. var box = max.subtract(min);
  17017. var sizeX = this._checkWithEpsilon(box.x);
  17018. var sizeY = this._checkWithEpsilon(box.y);
  17019. var sizeZ = this._checkWithEpsilon(box.z);
  17020. var relativePosition = mesh.position;
  17021. bodyParameters = {
  17022. type: 'box',
  17023. size: [sizeX, sizeY, sizeZ],
  17024. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  17025. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17026. };
  17027. break;
  17028. }
  17029. return bodyParameters;
  17030. };
  17031. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  17032. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17033. var registeredMesh = this._registeredMeshes[index];
  17034. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17035. if (registeredMesh.body) {
  17036. this._world.removeRigidBody(registeredMesh.body.body);
  17037. this._unbindBody(registeredMesh.body);
  17038. }
  17039. this._registeredMeshes.splice(index, 1);
  17040. return;
  17041. }
  17042. }
  17043. };
  17044. OimoJSPlugin.prototype._unbindBody = function (body) {
  17045. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17046. var registeredMesh = this._registeredMeshes[index];
  17047. if (registeredMesh.body === body) {
  17048. registeredMesh.body = null;
  17049. }
  17050. }
  17051. };
  17052. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17053. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17054. var registeredMesh = this._registeredMeshes[index];
  17055. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17056. // Get object mass to have a behaviour similar to cannon.js
  17057. var mass = registeredMesh.body.body.massInfo.mass;
  17058. // The force is scaled with the mass of object
  17059. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17060. return;
  17061. }
  17062. }
  17063. };
  17064. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17065. var body1 = null, body2 = null;
  17066. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17067. var registeredMesh = this._registeredMeshes[index];
  17068. if (registeredMesh.mesh === mesh1) {
  17069. body1 = registeredMesh.body.body;
  17070. }
  17071. else if (registeredMesh.mesh === mesh2) {
  17072. body2 = registeredMesh.body.body;
  17073. }
  17074. }
  17075. if (!body1 || !body2) {
  17076. return false;
  17077. }
  17078. if (!options) {
  17079. options = {};
  17080. }
  17081. new OIMO.Link({
  17082. type: options.type,
  17083. body1: body1,
  17084. body2: body2,
  17085. min: options.min,
  17086. max: options.max,
  17087. axe1: options.axe1,
  17088. axe2: options.axe2,
  17089. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17090. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17091. collision: options.collision,
  17092. spring: options.spring,
  17093. world: this._world
  17094. });
  17095. return true;
  17096. };
  17097. OimoJSPlugin.prototype.dispose = function () {
  17098. this._world.clear();
  17099. while (this._registeredMeshes.length) {
  17100. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17101. }
  17102. };
  17103. OimoJSPlugin.prototype.isSupported = function () {
  17104. return OIMO !== undefined;
  17105. };
  17106. OimoJSPlugin.prototype._getLastShape = function (body) {
  17107. var lastShape = body.shapes;
  17108. while (lastShape.next) {
  17109. lastShape = lastShape.next;
  17110. }
  17111. return lastShape;
  17112. };
  17113. OimoJSPlugin.prototype.runOneStep = function (time) {
  17114. this._world.step();
  17115. // Update the position of all registered meshes
  17116. var i = this._registeredMeshes.length;
  17117. var m;
  17118. while (i--) {
  17119. var body = this._registeredMeshes[i].body.body;
  17120. var mesh = this._registeredMeshes[i].mesh;
  17121. var delta = this._registeredMeshes[i].delta;
  17122. if (!body.sleeping) {
  17123. if (body.shapes.next) {
  17124. var parentShape = this._getLastShape(body);
  17125. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17126. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17127. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17128. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17129. if (!mesh.rotationQuaternion) {
  17130. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17131. }
  17132. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17133. mesh.computeWorldMatrix();
  17134. }
  17135. else {
  17136. m = body.getMatrix();
  17137. mtx = BABYLON.Matrix.FromArray(m);
  17138. // Body position
  17139. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17140. if (!delta) {
  17141. mesh.position.x = bodyX;
  17142. mesh.position.y = bodyY;
  17143. mesh.position.z = bodyZ;
  17144. }
  17145. else {
  17146. mesh.position.x = bodyX + delta.x;
  17147. mesh.position.y = bodyY + delta.y;
  17148. mesh.position.z = bodyZ + delta.z;
  17149. }
  17150. if (!mesh.rotationQuaternion) {
  17151. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17152. }
  17153. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17154. mesh.computeWorldMatrix();
  17155. }
  17156. }
  17157. }
  17158. };
  17159. return OimoJSPlugin;
  17160. })();
  17161. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17162. })(BABYLON || (BABYLON = {}));
  17163. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17164. (function (BABYLON) {
  17165. var PhysicsEngine = (function () {
  17166. function PhysicsEngine(plugin) {
  17167. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17168. }
  17169. PhysicsEngine.prototype._initialize = function (gravity) {
  17170. this._currentPlugin.initialize();
  17171. this._setGravity(gravity);
  17172. };
  17173. PhysicsEngine.prototype._runOneStep = function (delta) {
  17174. if (delta > 0.1) {
  17175. delta = 0.1;
  17176. }
  17177. else if (delta <= 0) {
  17178. delta = 1.0 / 60.0;
  17179. }
  17180. this._currentPlugin.runOneStep(delta);
  17181. };
  17182. PhysicsEngine.prototype._setGravity = function (gravity) {
  17183. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17184. this._currentPlugin.setGravity(this.gravity);
  17185. };
  17186. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17187. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17188. };
  17189. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17190. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17191. };
  17192. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17193. this._currentPlugin.unregisterMesh(mesh);
  17194. };
  17195. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  17196. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  17197. };
  17198. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17199. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  17200. };
  17201. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  17202. this._currentPlugin.updateBodyPosition(mesh);
  17203. };
  17204. PhysicsEngine.prototype.dispose = function () {
  17205. this._currentPlugin.dispose();
  17206. };
  17207. PhysicsEngine.prototype.isSupported = function () {
  17208. return this._currentPlugin.isSupported();
  17209. };
  17210. // Statics
  17211. PhysicsEngine.NoImpostor = 0;
  17212. PhysicsEngine.SphereImpostor = 1;
  17213. PhysicsEngine.BoxImpostor = 2;
  17214. PhysicsEngine.PlaneImpostor = 3;
  17215. PhysicsEngine.MeshImpostor = 4;
  17216. PhysicsEngine.CapsuleImpostor = 5;
  17217. PhysicsEngine.ConeImpostor = 6;
  17218. PhysicsEngine.CylinderImpostor = 7;
  17219. PhysicsEngine.ConvexHullImpostor = 8;
  17220. PhysicsEngine.Epsilon = 0.001;
  17221. return PhysicsEngine;
  17222. })();
  17223. BABYLON.PhysicsEngine = PhysicsEngine;
  17224. })(BABYLON || (BABYLON = {}));
  17225. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  17226. (function (BABYLON) {
  17227. var serializeLight = function (light) {
  17228. var serializationObject = {};
  17229. serializationObject.name = light.name;
  17230. serializationObject.id = light.id;
  17231. serializationObject.tags = BABYLON.Tags.GetTags(light);
  17232. if (light instanceof BABYLON.PointLight) {
  17233. serializationObject.type = 0;
  17234. serializationObject.position = light.position.asArray();
  17235. }
  17236. else if (light instanceof BABYLON.DirectionalLight) {
  17237. serializationObject.type = 1;
  17238. var directionalLight = light;
  17239. serializationObject.position = directionalLight.position.asArray();
  17240. serializationObject.direction = directionalLight.direction.asArray();
  17241. }
  17242. else if (light instanceof BABYLON.SpotLight) {
  17243. serializationObject.type = 2;
  17244. var spotLight = light;
  17245. serializationObject.position = spotLight.position.asArray();
  17246. serializationObject.direction = spotLight.position.asArray();
  17247. serializationObject.angle = spotLight.angle;
  17248. serializationObject.exponent = spotLight.exponent;
  17249. }
  17250. else if (light instanceof BABYLON.HemisphericLight) {
  17251. serializationObject.type = 3;
  17252. var hemisphericLight = light;
  17253. serializationObject.direction = hemisphericLight.direction.asArray();
  17254. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  17255. }
  17256. if (light.intensity) {
  17257. serializationObject.intensity = light.intensity;
  17258. }
  17259. serializationObject.range = light.range;
  17260. serializationObject.diffuse = light.diffuse.asArray();
  17261. serializationObject.specular = light.specular.asArray();
  17262. return serializationObject;
  17263. };
  17264. var serializeFresnelParameter = function (fresnelParameter) {
  17265. var serializationObject = {};
  17266. serializationObject.isEnabled = fresnelParameter.isEnabled;
  17267. serializationObject.leftColor = fresnelParameter.leftColor;
  17268. serializationObject.rightColor = fresnelParameter.rightColor;
  17269. serializationObject.bias = fresnelParameter.bias;
  17270. serializationObject.power = fresnelParameter.power;
  17271. return serializationObject;
  17272. };
  17273. var serializeCamera = function (camera) {
  17274. var serializationObject = {};
  17275. serializationObject.name = camera.name;
  17276. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  17277. serializationObject.id = camera.id;
  17278. serializationObject.position = camera.position.asArray();
  17279. // Parent
  17280. if (camera.parent) {
  17281. serializationObject.parentId = camera.parent.id;
  17282. }
  17283. // Target
  17284. serializationObject.rotation = camera.rotation.asArray();
  17285. // Locked target
  17286. if (camera.lockedTarget && camera.lockedTarget.id) {
  17287. serializationObject.lockedTargetId = camera.lockedTarget.id;
  17288. }
  17289. serializationObject.fov = camera.fov;
  17290. serializationObject.minZ = camera.minZ;
  17291. serializationObject.maxZ = camera.maxZ;
  17292. serializationObject.speed = camera.speed;
  17293. serializationObject.inertia = camera.inertia;
  17294. serializationObject.checkCollisions = camera.checkCollisions;
  17295. serializationObject.applyGravity = camera.applyGravity;
  17296. if (camera.ellipsoid) {
  17297. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  17298. }
  17299. // Animations
  17300. appendAnimations(camera, serializationObject);
  17301. // Layer mask
  17302. serializationObject.layerMask = camera.layerMask;
  17303. return serializationObject;
  17304. };
  17305. var appendAnimations = function (source, destination) {
  17306. if (source.animations) {
  17307. destination.animations = [];
  17308. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  17309. var animation = source.animations[animationIndex];
  17310. destination.animations.push(serializeAnimation(animation));
  17311. }
  17312. }
  17313. };
  17314. var serializeAnimation = function (animation) {
  17315. var serializationObject = {};
  17316. serializationObject.name = animation.name;
  17317. serializationObject.property = animation.targetProperty;
  17318. serializationObject.framePerSecond = animation.framePerSecond;
  17319. serializationObject.dataType = animation.dataType;
  17320. serializationObject.loopBehavior = animation.loopMode;
  17321. var dataType = animation.dataType;
  17322. serializationObject.keys = [];
  17323. var keys = animation.getKeys();
  17324. for (var index = 0; index < keys.length; index++) {
  17325. var animationKey = keys[index];
  17326. var key = {};
  17327. key.frame = animationKey.frame;
  17328. switch (dataType) {
  17329. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17330. key.values = [animationKey.value];
  17331. break;
  17332. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17333. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17334. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17335. key.values = animationKey.value.asArray();
  17336. break;
  17337. }
  17338. serializationObject.keys.push(key);
  17339. }
  17340. return serializationObject;
  17341. };
  17342. var serializeMultiMaterial = function (material) {
  17343. var serializationObject = {};
  17344. serializationObject.name = material.name;
  17345. serializationObject.id = material.id;
  17346. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17347. serializationObject.materials = [];
  17348. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  17349. var subMat = material.subMaterials[matIndex];
  17350. if (subMat) {
  17351. serializationObject.materials.push(subMat.id);
  17352. }
  17353. else {
  17354. serializationObject.materials.push(null);
  17355. }
  17356. }
  17357. return serializationObject;
  17358. };
  17359. var serializeMaterial = function (material) {
  17360. var serializationObject = {};
  17361. serializationObject.name = material.name;
  17362. serializationObject.ambient = material.ambientColor.asArray();
  17363. serializationObject.diffuse = material.diffuseColor.asArray();
  17364. serializationObject.specular = material.specularColor.asArray();
  17365. serializationObject.specularPower = material.specularPower;
  17366. serializationObject.emissive = material.emissiveColor.asArray();
  17367. serializationObject.alpha = material.alpha;
  17368. serializationObject.id = material.id;
  17369. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17370. serializationObject.backFaceCulling = material.backFaceCulling;
  17371. if (material.diffuseTexture) {
  17372. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  17373. }
  17374. if (material.diffuseFresnelParameters) {
  17375. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  17376. }
  17377. if (material.ambientTexture) {
  17378. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  17379. }
  17380. if (material.opacityTexture) {
  17381. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  17382. }
  17383. if (material.opacityFresnelParameters) {
  17384. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  17385. }
  17386. if (material.reflectionTexture) {
  17387. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  17388. }
  17389. if (material.reflectionFresnelParameters) {
  17390. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  17391. }
  17392. if (material.emissiveTexture) {
  17393. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  17394. }
  17395. if (material.emissiveFresnelParameters) {
  17396. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  17397. }
  17398. if (material.specularTexture) {
  17399. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  17400. }
  17401. if (material.bumpTexture) {
  17402. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  17403. }
  17404. return serializationObject;
  17405. };
  17406. var serializeTexture = function (texture) {
  17407. var serializationObject = {};
  17408. if (!texture.name) {
  17409. return null;
  17410. }
  17411. if (texture instanceof BABYLON.CubeTexture) {
  17412. serializationObject.name = texture.name;
  17413. serializationObject.hasAlpha = texture.hasAlpha;
  17414. serializationObject.level = texture.level;
  17415. serializationObject.coordinatesMode = texture.coordinatesMode;
  17416. return serializationObject;
  17417. }
  17418. if (texture instanceof BABYLON.MirrorTexture) {
  17419. var mirrorTexture = texture;
  17420. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  17421. serializationObject.renderList = [];
  17422. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  17423. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  17424. }
  17425. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  17426. }
  17427. else if (texture instanceof BABYLON.RenderTargetTexture) {
  17428. var renderTargetTexture = texture;
  17429. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  17430. serializationObject.renderList = [];
  17431. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  17432. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  17433. }
  17434. }
  17435. var regularTexture = texture;
  17436. serializationObject.name = texture.name;
  17437. serializationObject.hasAlpha = texture.hasAlpha;
  17438. serializationObject.level = texture.level;
  17439. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  17440. serializationObject.coordinatesMode = texture.coordinatesMode;
  17441. serializationObject.uOffset = regularTexture.uOffset;
  17442. serializationObject.vOffset = regularTexture.vOffset;
  17443. serializationObject.uScale = regularTexture.uScale;
  17444. serializationObject.vScale = regularTexture.vScale;
  17445. serializationObject.uAng = regularTexture.uAng;
  17446. serializationObject.vAng = regularTexture.vAng;
  17447. serializationObject.wAng = regularTexture.wAng;
  17448. serializationObject.wrapU = texture.wrapU;
  17449. serializationObject.wrapV = texture.wrapV;
  17450. // Animations
  17451. appendAnimations(texture, serializationObject);
  17452. return serializationObject;
  17453. };
  17454. var serializeSkeleton = function (skeleton) {
  17455. var serializationObject = {};
  17456. serializationObject.name = skeleton.name;
  17457. serializationObject.id = skeleton.id;
  17458. serializationObject.bones = [];
  17459. for (var index = 0; index < skeleton.bones.length; index++) {
  17460. var bone = skeleton.bones[index];
  17461. var serializedBone = {
  17462. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  17463. name: bone.name,
  17464. matrix: bone.getLocalMatrix().toArray()
  17465. };
  17466. serializationObject.bones.push(serializedBone);
  17467. if (bone.animations && bone.animations.length > 0) {
  17468. serializedBone.animation = serializeAnimation(bone.animations[0]);
  17469. }
  17470. }
  17471. return serializationObject;
  17472. };
  17473. var serializeParticleSystem = function (particleSystem) {
  17474. var serializationObject = {};
  17475. serializationObject.emitterId = particleSystem.emitter.id;
  17476. serializationObject.capacity = particleSystem.getCapacity();
  17477. if (particleSystem.particleTexture) {
  17478. serializationObject.textureName = particleSystem.particleTexture.name;
  17479. }
  17480. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  17481. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  17482. serializationObject.minSize = particleSystem.minSize;
  17483. serializationObject.maxSize = particleSystem.maxSize;
  17484. serializationObject.minLifeTime = particleSystem.minLifeTime;
  17485. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  17486. serializationObject.emitRate = particleSystem.emitRate;
  17487. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  17488. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  17489. serializationObject.gravity = particleSystem.gravity.asArray();
  17490. serializationObject.direction1 = particleSystem.direction1.asArray();
  17491. serializationObject.direction2 = particleSystem.direction2.asArray();
  17492. serializationObject.color1 = particleSystem.color1.asArray();
  17493. serializationObject.color2 = particleSystem.color2.asArray();
  17494. serializationObject.colorDead = particleSystem.colorDead.asArray();
  17495. serializationObject.updateSpeed = particleSystem.updateSpeed;
  17496. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  17497. serializationObject.textureMask = particleSystem.textureMask.asArray();
  17498. serializationObject.blendMode = particleSystem.blendMode;
  17499. return serializationObject;
  17500. };
  17501. var serializeLensFlareSystem = function (lensFlareSystem) {
  17502. var serializationObject = {};
  17503. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  17504. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  17505. serializationObject.flares = [];
  17506. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  17507. var flare = lensFlareSystem.lensFlares[index];
  17508. serializationObject.flares.push({
  17509. size: flare.size,
  17510. position: flare.position,
  17511. color: flare.color.asArray(),
  17512. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  17513. });
  17514. }
  17515. return serializationObject;
  17516. };
  17517. var serializeShadowGenerator = function (light) {
  17518. var serializationObject = {};
  17519. var shadowGenerator = light.getShadowGenerator();
  17520. serializationObject.lightId = light.id;
  17521. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  17522. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  17523. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  17524. serializationObject.renderList = [];
  17525. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  17526. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  17527. serializationObject.renderList.push(mesh.id);
  17528. }
  17529. return serializationObject;
  17530. };
  17531. var serializedGeometries = [];
  17532. var serializeGeometry = function (geometry, serializationGeometries) {
  17533. if (serializedGeometries[geometry.id]) {
  17534. return;
  17535. }
  17536. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  17537. serializationGeometries.boxes.push(serializeBox(geometry));
  17538. }
  17539. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  17540. serializationGeometries.spheres.push(serializeSphere(geometry));
  17541. }
  17542. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  17543. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  17544. }
  17545. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  17546. serializationGeometries.toruses.push(serializeTorus(geometry));
  17547. }
  17548. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  17549. serializationGeometries.grounds.push(serializeGround(geometry));
  17550. }
  17551. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  17552. serializationGeometries.planes.push(serializePlane(geometry));
  17553. }
  17554. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  17555. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  17556. }
  17557. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  17558. throw new Error("Unknow primitive type");
  17559. }
  17560. else {
  17561. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  17562. }
  17563. serializedGeometries[geometry.id] = true;
  17564. };
  17565. var serializeGeometryBase = function (geometry) {
  17566. var serializationObject = {};
  17567. serializationObject.id = geometry.id;
  17568. if (BABYLON.Tags.HasTags(geometry)) {
  17569. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  17570. }
  17571. return serializationObject;
  17572. };
  17573. var serializeVertexData = function (vertexData) {
  17574. var serializationObject = serializeGeometryBase(vertexData);
  17575. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17576. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17577. }
  17578. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17579. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17580. }
  17581. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17582. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17583. }
  17584. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17585. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17586. }
  17587. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17588. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17589. }
  17590. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17591. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17592. serializationObject.matricesIndices._isExpanded = true;
  17593. }
  17594. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17595. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17596. }
  17597. serializationObject.indices = vertexData.getIndices();
  17598. return serializationObject;
  17599. };
  17600. var serializePrimitive = function (primitive) {
  17601. var serializationObject = serializeGeometryBase(primitive);
  17602. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  17603. return serializationObject;
  17604. };
  17605. var serializeBox = function (box) {
  17606. var serializationObject = serializePrimitive(box);
  17607. serializationObject.size = box.size;
  17608. return serializationObject;
  17609. };
  17610. var serializeSphere = function (sphere) {
  17611. var serializationObject = serializePrimitive(sphere);
  17612. serializationObject.segments = sphere.segments;
  17613. serializationObject.diameter = sphere.diameter;
  17614. return serializationObject;
  17615. };
  17616. var serializeCylinder = function (cylinder) {
  17617. var serializationObject = serializePrimitive(cylinder);
  17618. serializationObject.height = cylinder.height;
  17619. serializationObject.diameterTop = cylinder.diameterTop;
  17620. serializationObject.diameterBottom = cylinder.diameterBottom;
  17621. serializationObject.tessellation = cylinder.tessellation;
  17622. return serializationObject;
  17623. };
  17624. var serializeTorus = function (torus) {
  17625. var serializationObject = serializePrimitive(torus);
  17626. serializationObject.diameter = torus.diameter;
  17627. serializationObject.thickness = torus.thickness;
  17628. serializationObject.tessellation = torus.tessellation;
  17629. return serializationObject;
  17630. };
  17631. var serializeGround = function (ground) {
  17632. var serializationObject = serializePrimitive(ground);
  17633. serializationObject.width = ground.width;
  17634. serializationObject.height = ground.height;
  17635. serializationObject.subdivisions = ground.subdivisions;
  17636. return serializationObject;
  17637. };
  17638. var serializePlane = function (plane) {
  17639. var serializationObject = serializePrimitive(plane);
  17640. serializationObject.size = plane.size;
  17641. return serializationObject;
  17642. };
  17643. var serializeTorusKnot = function (torusKnot) {
  17644. var serializationObject = serializePrimitive(torusKnot);
  17645. serializationObject.radius = torusKnot.radius;
  17646. serializationObject.tube = torusKnot.tube;
  17647. serializationObject.radialSegments = torusKnot.radialSegments;
  17648. serializationObject.tubularSegments = torusKnot.tubularSegments;
  17649. serializationObject.p = torusKnot.p;
  17650. serializationObject.q = torusKnot.q;
  17651. return serializationObject;
  17652. };
  17653. var serializeMesh = function (mesh, serializationScene) {
  17654. var serializationObject = {};
  17655. serializationObject.name = mesh.name;
  17656. serializationObject.id = mesh.id;
  17657. if (BABYLON.Tags.HasTags(mesh)) {
  17658. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  17659. }
  17660. serializationObject.position = mesh.position.asArray();
  17661. if (mesh.rotationQuaternion) {
  17662. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  17663. }
  17664. else if (mesh.rotation) {
  17665. serializationObject.rotation = mesh.rotation.asArray();
  17666. }
  17667. serializationObject.scaling = mesh.scaling.asArray();
  17668. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  17669. serializationObject.isEnabled = mesh.isEnabled();
  17670. serializationObject.isVisible = mesh.isVisible;
  17671. serializationObject.infiniteDistance = mesh.infiniteDistance;
  17672. serializationObject.pickable = mesh.isPickable;
  17673. serializationObject.receiveShadows = mesh.receiveShadows;
  17674. serializationObject.billboardMode = mesh.billboardMode;
  17675. serializationObject.visibility = mesh.visibility;
  17676. serializationObject.checkCollisions = mesh.checkCollisions;
  17677. // Parent
  17678. if (mesh.parent) {
  17679. serializationObject.parentId = mesh.parent.id;
  17680. }
  17681. // Geometry
  17682. var geometry = mesh._geometry;
  17683. if (geometry) {
  17684. var geometryId = geometry.id;
  17685. serializationObject.geometryId = geometryId;
  17686. if (!mesh.getScene().getGeometryByID(geometryId)) {
  17687. // 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
  17688. serializeGeometry(geometry, serializationScene.geometries);
  17689. }
  17690. // SubMeshes
  17691. serializationObject.subMeshes = [];
  17692. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17693. var subMesh = mesh.subMeshes[subIndex];
  17694. serializationObject.subMeshes.push({
  17695. materialIndex: subMesh.materialIndex,
  17696. verticesStart: subMesh.verticesStart,
  17697. verticesCount: subMesh.verticesCount,
  17698. indexStart: subMesh.indexStart,
  17699. indexCount: subMesh.indexCount
  17700. });
  17701. }
  17702. }
  17703. // Material
  17704. if (mesh.material) {
  17705. serializationObject.materialId = mesh.material.id;
  17706. }
  17707. else {
  17708. mesh.material = null;
  17709. }
  17710. // Skeleton
  17711. if (mesh.skeleton) {
  17712. serializationObject.skeletonId = mesh.skeleton.id;
  17713. }
  17714. // Physics
  17715. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  17716. serializationObject.physicsMass = mesh.getPhysicsMass();
  17717. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  17718. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  17719. switch (mesh.getPhysicsImpostor()) {
  17720. case BABYLON.PhysicsEngine.BoxImpostor:
  17721. serializationObject.physicsImpostor = 1;
  17722. break;
  17723. case BABYLON.PhysicsEngine.SphereImpostor:
  17724. serializationObject.physicsImpostor = 2;
  17725. break;
  17726. }
  17727. }
  17728. // Instances
  17729. serializationObject.instances = [];
  17730. for (var index = 0; index < mesh.instances.length; index++) {
  17731. var instance = mesh.instances[index];
  17732. var serializationInstance = {
  17733. name: instance.name,
  17734. position: instance.position,
  17735. rotation: instance.rotation,
  17736. rotationQuaternion: instance.rotationQuaternion,
  17737. scaling: instance.scaling
  17738. };
  17739. serializationObject.instances.push(serializationInstance);
  17740. // Animations
  17741. appendAnimations(instance, serializationInstance);
  17742. }
  17743. // Animations
  17744. appendAnimations(mesh, serializationObject);
  17745. // Layer mask
  17746. serializationObject.layerMask = mesh.layerMask;
  17747. return serializationObject;
  17748. };
  17749. var SceneSerializer = (function () {
  17750. function SceneSerializer() {
  17751. }
  17752. SceneSerializer.Serialize = function (scene) {
  17753. var serializationObject = {};
  17754. // Scene
  17755. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  17756. serializationObject.autoClear = scene.autoClear;
  17757. serializationObject.clearColor = scene.clearColor.asArray();
  17758. serializationObject.ambientColor = scene.ambientColor.asArray();
  17759. serializationObject.gravity = scene.gravity.asArray();
  17760. // Fog
  17761. if (scene.fogMode && scene.fogMode !== 0) {
  17762. serializationObject.fogMode = scene.fogMode;
  17763. serializationObject.fogColor = scene.fogColor.asArray();
  17764. serializationObject.fogStart = scene.fogStart;
  17765. serializationObject.fogEnd = scene.fogEnd;
  17766. serializationObject.fogDensity = scene.fogDensity;
  17767. }
  17768. // Lights
  17769. serializationObject.lights = [];
  17770. for (var index = 0; index < scene.lights.length; index++) {
  17771. var light = scene.lights[index];
  17772. serializationObject.lights.push(serializeLight(light));
  17773. }
  17774. // Cameras
  17775. serializationObject.cameras = [];
  17776. for (index = 0; index < scene.cameras.length; index++) {
  17777. var camera = scene.cameras[index];
  17778. if (camera instanceof BABYLON.FreeCamera) {
  17779. serializationObject.cameras.push(serializeCamera(camera));
  17780. }
  17781. }
  17782. if (scene.activeCamera) {
  17783. serializationObject.activeCameraID = scene.activeCamera.id;
  17784. }
  17785. // Materials
  17786. serializationObject.materials = [];
  17787. serializationObject.multiMaterials = [];
  17788. for (index = 0; index < scene.materials.length; index++) {
  17789. var material = scene.materials[index];
  17790. if (material instanceof BABYLON.StandardMaterial) {
  17791. serializationObject.materials.push(serializeMaterial(material));
  17792. }
  17793. else if (material instanceof BABYLON.MultiMaterial) {
  17794. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  17795. }
  17796. }
  17797. // Skeletons
  17798. serializationObject.skeletons = [];
  17799. for (index = 0; index < scene.skeletons.length; index++) {
  17800. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  17801. }
  17802. // Geometries
  17803. serializationObject.geometries = {};
  17804. serializationObject.geometries.boxes = [];
  17805. serializationObject.geometries.spheres = [];
  17806. serializationObject.geometries.cylinders = [];
  17807. serializationObject.geometries.toruses = [];
  17808. serializationObject.geometries.grounds = [];
  17809. serializationObject.geometries.planes = [];
  17810. serializationObject.geometries.torusKnots = [];
  17811. serializationObject.geometries.vertexData = [];
  17812. serializedGeometries = [];
  17813. var geometries = scene.getGeometries();
  17814. for (var index = 0; index < geometries.length; index++) {
  17815. var geometry = geometries[index];
  17816. if (geometry.isReady()) {
  17817. serializeGeometry(geometry, serializationObject.geometries);
  17818. }
  17819. }
  17820. // Meshes
  17821. serializationObject.meshes = [];
  17822. for (index = 0; index < scene.meshes.length; index++) {
  17823. var abstractMesh = scene.meshes[index];
  17824. if (abstractMesh instanceof BABYLON.Mesh) {
  17825. var mesh = abstractMesh;
  17826. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  17827. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  17828. }
  17829. }
  17830. }
  17831. // Particles Systems
  17832. serializationObject.particleSystems = [];
  17833. for (index = 0; index < scene.particleSystems.length; index++) {
  17834. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  17835. }
  17836. // Lens flares
  17837. serializationObject.lensFlareSystems = [];
  17838. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  17839. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  17840. }
  17841. // Shadows
  17842. serializationObject.shadowGenerators = [];
  17843. for (index = 0; index < scene.lights.length; index++) {
  17844. light = scene.lights[index];
  17845. if (light.getShadowGenerator()) {
  17846. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  17847. }
  17848. }
  17849. return serializationObject;
  17850. };
  17851. return SceneSerializer;
  17852. })();
  17853. BABYLON.SceneSerializer = SceneSerializer;
  17854. })(BABYLON || (BABYLON = {}));
  17855. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  17856. (function (BABYLON) {
  17857. var SceneLoader = (function () {
  17858. function SceneLoader() {
  17859. }
  17860. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  17861. get: function () {
  17862. return SceneLoader._ForceFullSceneLoadingForIncremental;
  17863. },
  17864. set: function (value) {
  17865. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  17866. },
  17867. enumerable: true,
  17868. configurable: true
  17869. });
  17870. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  17871. get: function () {
  17872. return SceneLoader._ShowLoadingScreen;
  17873. },
  17874. set: function (value) {
  17875. SceneLoader._ShowLoadingScreen = value;
  17876. },
  17877. enumerable: true,
  17878. configurable: true
  17879. });
  17880. SceneLoader._getPluginForFilename = function (sceneFilename) {
  17881. var dotPosition = sceneFilename.lastIndexOf(".");
  17882. var queryStringPosition = sceneFilename.indexOf("?");
  17883. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17884. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17885. var plugin = this._registeredPlugins[index];
  17886. if (plugin.extensions.indexOf(extension) !== -1) {
  17887. return plugin;
  17888. }
  17889. }
  17890. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17891. };
  17892. // Public functions
  17893. SceneLoader.RegisterPlugin = function (plugin) {
  17894. plugin.extensions = plugin.extensions.toLowerCase();
  17895. SceneLoader._registeredPlugins.push(plugin);
  17896. };
  17897. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17898. var manifestChecked = function (success) {
  17899. scene.database = database;
  17900. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17901. var importMeshFromData = function (data) {
  17902. var meshes = [];
  17903. var particleSystems = [];
  17904. var skeletons = [];
  17905. try {
  17906. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17907. if (onerror) {
  17908. onerror(scene, 'unable to load the scene');
  17909. }
  17910. return;
  17911. }
  17912. }
  17913. catch (e) {
  17914. if (onerror) {
  17915. onerror(scene, e);
  17916. }
  17917. return;
  17918. }
  17919. if (onsuccess) {
  17920. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17921. onsuccess(meshes, particleSystems, skeletons);
  17922. }
  17923. };
  17924. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17925. // Direct load
  17926. importMeshFromData(sceneFilename.substr(5));
  17927. return;
  17928. }
  17929. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17930. importMeshFromData(data);
  17931. }, progressCallBack, database);
  17932. };
  17933. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17934. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17935. };
  17936. /**
  17937. * Load a scene
  17938. * @param rootUrl a string that defines the root url for scene and resources
  17939. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17940. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17941. */
  17942. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17943. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17944. };
  17945. /**
  17946. * Append a scene
  17947. * @param rootUrl a string that defines the root url for scene and resources
  17948. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17949. * @param scene is the instance of BABYLON.Scene to append to
  17950. */
  17951. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17952. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17953. var database;
  17954. if (SceneLoader.ShowLoadingScreen) {
  17955. scene.getEngine().displayLoadingUI();
  17956. }
  17957. var loadSceneFromData = function (data) {
  17958. scene.database = database;
  17959. if (!plugin.load(scene, data, rootUrl)) {
  17960. if (onerror) {
  17961. onerror(scene);
  17962. }
  17963. scene.getEngine().hideLoadingUI();
  17964. return;
  17965. }
  17966. if (onsuccess) {
  17967. onsuccess(scene);
  17968. }
  17969. if (SceneLoader.ShowLoadingScreen) {
  17970. scene.executeWhenReady(function () {
  17971. scene.getEngine().hideLoadingUI();
  17972. });
  17973. }
  17974. };
  17975. var manifestChecked = function (success) {
  17976. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17977. };
  17978. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17979. // Direct load
  17980. loadSceneFromData(sceneFilename.substr(5));
  17981. return;
  17982. }
  17983. if (rootUrl.indexOf("file:") === -1) {
  17984. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17985. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17986. }
  17987. else {
  17988. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17989. }
  17990. };
  17991. // Flags
  17992. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17993. SceneLoader._ShowLoadingScreen = true;
  17994. // Members
  17995. SceneLoader._registeredPlugins = new Array();
  17996. return SceneLoader;
  17997. })();
  17998. BABYLON.SceneLoader = SceneLoader;
  17999. ;
  18000. })(BABYLON || (BABYLON = {}));
  18001. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  18002. (function (BABYLON) {
  18003. var Internals;
  18004. (function (Internals) {
  18005. var checkColors4 = function (colors, count) {
  18006. // Check if color3 was used
  18007. if (colors.length === count * 3) {
  18008. var colors4 = [];
  18009. for (var index = 0; index < colors.length; index += 3) {
  18010. var newIndex = (index / 3) * 4;
  18011. colors4[newIndex] = colors[index];
  18012. colors4[newIndex + 1] = colors[index + 1];
  18013. colors4[newIndex + 2] = colors[index + 2];
  18014. colors4[newIndex + 3] = 1.0;
  18015. }
  18016. return colors4;
  18017. }
  18018. return colors;
  18019. };
  18020. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18021. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18022. texture.name = parsedTexture.name;
  18023. texture.hasAlpha = parsedTexture.hasAlpha;
  18024. texture.level = parsedTexture.level;
  18025. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18026. return texture;
  18027. };
  18028. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18029. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18030. return null;
  18031. }
  18032. if (parsedTexture.isCube) {
  18033. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18034. }
  18035. var texture;
  18036. if (parsedTexture.mirrorPlane) {
  18037. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18038. texture._waitingRenderList = parsedTexture.renderList;
  18039. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18040. }
  18041. else if (parsedTexture.isRenderTarget) {
  18042. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18043. texture._waitingRenderList = parsedTexture.renderList;
  18044. }
  18045. else {
  18046. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18047. }
  18048. texture.name = parsedTexture.name;
  18049. texture.hasAlpha = parsedTexture.hasAlpha;
  18050. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18051. texture.level = parsedTexture.level;
  18052. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18053. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18054. texture.uOffset = parsedTexture.uOffset;
  18055. texture.vOffset = parsedTexture.vOffset;
  18056. texture.uScale = parsedTexture.uScale;
  18057. texture.vScale = parsedTexture.vScale;
  18058. texture.uAng = parsedTexture.uAng;
  18059. texture.vAng = parsedTexture.vAng;
  18060. texture.wAng = parsedTexture.wAng;
  18061. texture.wrapU = parsedTexture.wrapU;
  18062. texture.wrapV = parsedTexture.wrapV;
  18063. // Animations
  18064. if (parsedTexture.animations) {
  18065. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18066. var parsedAnimation = parsedTexture.animations[animationIndex];
  18067. texture.animations.push(parseAnimation(parsedAnimation));
  18068. }
  18069. }
  18070. return texture;
  18071. };
  18072. var parseSkeleton = function (parsedSkeleton, scene) {
  18073. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18074. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18075. var parsedBone = parsedSkeleton.bones[index];
  18076. var parentBone = null;
  18077. if (parsedBone.parentBoneIndex > -1) {
  18078. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18079. }
  18080. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18081. if (parsedBone.animation) {
  18082. bone.animations.push(parseAnimation(parsedBone.animation));
  18083. }
  18084. }
  18085. return skeleton;
  18086. };
  18087. var parseFresnelParameters = function (parsedFresnelParameters) {
  18088. var fresnelParameters = new BABYLON.FresnelParameters();
  18089. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18090. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18091. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18092. fresnelParameters.bias = parsedFresnelParameters.bias;
  18093. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18094. return fresnelParameters;
  18095. };
  18096. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18097. var material;
  18098. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18099. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18100. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18101. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18102. material.specularPower = parsedMaterial.specularPower;
  18103. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18104. material.alpha = parsedMaterial.alpha;
  18105. material.id = parsedMaterial.id;
  18106. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18107. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18108. material.wireframe = parsedMaterial.wireframe;
  18109. if (parsedMaterial.diffuseTexture) {
  18110. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18111. }
  18112. if (parsedMaterial.diffuseFresnelParameters) {
  18113. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18114. }
  18115. if (parsedMaterial.ambientTexture) {
  18116. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18117. }
  18118. if (parsedMaterial.opacityTexture) {
  18119. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18120. }
  18121. if (parsedMaterial.opacityFresnelParameters) {
  18122. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18123. }
  18124. if (parsedMaterial.reflectionTexture) {
  18125. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18126. }
  18127. if (parsedMaterial.reflectionFresnelParameters) {
  18128. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18129. }
  18130. if (parsedMaterial.emissiveTexture) {
  18131. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18132. }
  18133. if (parsedMaterial.emissiveFresnelParameters) {
  18134. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18135. }
  18136. if (parsedMaterial.specularTexture) {
  18137. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18138. }
  18139. if (parsedMaterial.bumpTexture) {
  18140. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18141. }
  18142. return material;
  18143. };
  18144. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18145. for (var index = 0; index < parsedData.materials.length; index++) {
  18146. var parsedMaterial = parsedData.materials[index];
  18147. if (parsedMaterial.id === id) {
  18148. return parseMaterial(parsedMaterial, scene, rootUrl);
  18149. }
  18150. }
  18151. return null;
  18152. };
  18153. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18154. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18155. multiMaterial.id = parsedMultiMaterial.id;
  18156. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18157. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18158. var subMatId = parsedMultiMaterial.materials[matIndex];
  18159. if (subMatId) {
  18160. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18161. }
  18162. else {
  18163. multiMaterial.subMaterials.push(null);
  18164. }
  18165. }
  18166. return multiMaterial;
  18167. };
  18168. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18169. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18170. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18171. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18172. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18173. var parsedFlare = parsedLensFlareSystem.flares[index];
  18174. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18175. }
  18176. return lensFlareSystem;
  18177. };
  18178. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18179. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18180. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18181. if (parsedParticleSystem.textureName) {
  18182. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18183. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18184. }
  18185. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18186. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18187. particleSystem.minSize = parsedParticleSystem.minSize;
  18188. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18189. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18190. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18191. particleSystem.emitter = emitter;
  18192. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18193. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18194. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18195. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18196. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18197. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18198. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18199. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18200. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18201. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18202. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18203. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18204. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18205. particleSystem.start();
  18206. return particleSystem;
  18207. };
  18208. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18209. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18210. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18211. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18212. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18213. shadowGenerator.getShadowMap().renderList.push(mesh);
  18214. }
  18215. if (parsedShadowGenerator.usePoissonSampling) {
  18216. shadowGenerator.usePoissonSampling = true;
  18217. }
  18218. else {
  18219. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  18220. }
  18221. return shadowGenerator;
  18222. };
  18223. var parseAnimation = function (parsedAnimation) {
  18224. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18225. var dataType = parsedAnimation.dataType;
  18226. var keys = [];
  18227. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18228. var key = parsedAnimation.keys[index];
  18229. var data;
  18230. switch (dataType) {
  18231. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18232. data = key.values[0];
  18233. break;
  18234. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18235. data = BABYLON.Quaternion.FromArray(key.values);
  18236. break;
  18237. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18238. data = BABYLON.Matrix.FromArray(key.values);
  18239. break;
  18240. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18241. default:
  18242. data = BABYLON.Vector3.FromArray(key.values);
  18243. break;
  18244. }
  18245. keys.push({
  18246. frame: key.frame,
  18247. value: data
  18248. });
  18249. }
  18250. animation.setKeys(keys);
  18251. return animation;
  18252. };
  18253. var parseLight = function (parsedLight, scene) {
  18254. var light;
  18255. switch (parsedLight.type) {
  18256. case 0:
  18257. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18258. break;
  18259. case 1:
  18260. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18261. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  18262. break;
  18263. case 2:
  18264. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18265. break;
  18266. case 3:
  18267. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18268. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18269. break;
  18270. }
  18271. light.id = parsedLight.id;
  18272. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18273. if (parsedLight.intensity !== undefined) {
  18274. light.intensity = parsedLight.intensity;
  18275. }
  18276. if (parsedLight.range) {
  18277. light.range = parsedLight.range;
  18278. }
  18279. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18280. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18281. if (parsedLight.excludedMeshesIds) {
  18282. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18283. }
  18284. // Parent
  18285. if (parsedLight.parentId) {
  18286. light._waitingParentId = parsedLight.parentId;
  18287. }
  18288. if (parsedLight.includedOnlyMeshesIds) {
  18289. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18290. }
  18291. // Animations
  18292. if (parsedLight.animations) {
  18293. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18294. var parsedAnimation = parsedLight.animations[animationIndex];
  18295. light.animations.push(parseAnimation(parsedAnimation));
  18296. }
  18297. }
  18298. if (parsedLight.autoAnimate) {
  18299. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  18300. }
  18301. };
  18302. var parseCamera = function (parsedCamera, scene) {
  18303. var camera;
  18304. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  18305. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  18306. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  18307. var alpha = parsedCamera.alpha;
  18308. var beta = parsedCamera.beta;
  18309. var radius = parsedCamera.radius;
  18310. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18311. var eye_space = parsedCamera.eye_space;
  18312. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18313. }
  18314. else {
  18315. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18316. }
  18317. }
  18318. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18319. eye_space = parsedCamera.eye_space;
  18320. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18321. }
  18322. else if (parsedCamera.type === "DeviceOrientationCamera") {
  18323. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18324. }
  18325. else if (parsedCamera.type === "FollowCamera") {
  18326. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18327. camera.heightOffset = parsedCamera.heightOffset;
  18328. camera.radius = parsedCamera.radius;
  18329. camera.rotationOffset = parsedCamera.rotationOffset;
  18330. if (lockedTargetMesh)
  18331. camera.target = lockedTargetMesh;
  18332. }
  18333. else if (parsedCamera.type === "GamepadCamera") {
  18334. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  18335. }
  18336. else if (parsedCamera.type === "OculusCamera") {
  18337. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  18338. }
  18339. else if (parsedCamera.type === "OculusGamepadCamera") {
  18340. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  18341. }
  18342. else if (parsedCamera.type === "TouchCamera") {
  18343. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  18344. }
  18345. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  18346. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  18347. }
  18348. else if (parsedCamera.type === "WebVRCamera") {
  18349. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  18350. }
  18351. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  18352. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  18353. }
  18354. else {
  18355. // Free Camera is the default value
  18356. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  18357. }
  18358. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  18359. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  18360. camera.lockedTarget = lockedTargetMesh;
  18361. }
  18362. camera.id = parsedCamera.id;
  18363. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  18364. // Parent
  18365. if (parsedCamera.parentId) {
  18366. camera._waitingParentId = parsedCamera.parentId;
  18367. }
  18368. // Target
  18369. if (parsedCamera.target) {
  18370. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18371. }
  18372. else {
  18373. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  18374. }
  18375. camera.fov = parsedCamera.fov;
  18376. camera.minZ = parsedCamera.minZ;
  18377. camera.maxZ = parsedCamera.maxZ;
  18378. camera.speed = parsedCamera.speed;
  18379. camera.inertia = parsedCamera.inertia;
  18380. camera.checkCollisions = parsedCamera.checkCollisions;
  18381. camera.applyGravity = parsedCamera.applyGravity;
  18382. if (parsedCamera.ellipsoid) {
  18383. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  18384. }
  18385. // Animations
  18386. if (parsedCamera.animations) {
  18387. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18388. var parsedAnimation = parsedCamera.animations[animationIndex];
  18389. camera.animations.push(parseAnimation(parsedAnimation));
  18390. }
  18391. }
  18392. if (parsedCamera.autoAnimate) {
  18393. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  18394. }
  18395. // Layer Mask
  18396. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  18397. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  18398. }
  18399. else {
  18400. camera.layerMask = 0xFFFFFFFF;
  18401. }
  18402. return camera;
  18403. };
  18404. var parseGeometry = function (parsedGeometry, scene) {
  18405. var id = parsedGeometry.id;
  18406. return scene.getGeometryByID(id);
  18407. };
  18408. var parseBox = function (parsedBox, scene) {
  18409. if (parseGeometry(parsedBox, scene)) {
  18410. return null; // null since geometry could be something else than a box...
  18411. }
  18412. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  18413. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  18414. scene.pushGeometry(box, true);
  18415. return box;
  18416. };
  18417. var parseSphere = function (parsedSphere, scene) {
  18418. if (parseGeometry(parsedSphere, scene)) {
  18419. return null; // null since geometry could be something else than a sphere...
  18420. }
  18421. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18422. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18423. scene.pushGeometry(sphere, true);
  18424. return sphere;
  18425. };
  18426. var parseCylinder = function (parsedCylinder, scene) {
  18427. if (parseGeometry(parsedCylinder, scene)) {
  18428. return null; // null since geometry could be something else than a cylinder...
  18429. }
  18430. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18431. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18432. scene.pushGeometry(cylinder, true);
  18433. return cylinder;
  18434. };
  18435. var parseTorus = function (parsedTorus, scene) {
  18436. if (parseGeometry(parsedTorus, scene)) {
  18437. return null; // null since geometry could be something else than a torus...
  18438. }
  18439. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18440. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18441. scene.pushGeometry(torus, true);
  18442. return torus;
  18443. };
  18444. var parseGround = function (parsedGround, scene) {
  18445. if (parseGeometry(parsedGround, scene)) {
  18446. return null; // null since geometry could be something else than a ground...
  18447. }
  18448. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18449. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18450. scene.pushGeometry(ground, true);
  18451. return ground;
  18452. };
  18453. var parsePlane = function (parsedPlane, scene) {
  18454. if (parseGeometry(parsedPlane, scene)) {
  18455. return null; // null since geometry could be something else than a plane...
  18456. }
  18457. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18458. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18459. scene.pushGeometry(plane, true);
  18460. return plane;
  18461. };
  18462. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18463. if (parseGeometry(parsedTorusKnot, scene)) {
  18464. return null; // null since geometry could be something else than a torusKnot...
  18465. }
  18466. 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);
  18467. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18468. scene.pushGeometry(torusKnot, true);
  18469. return torusKnot;
  18470. };
  18471. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18472. if (parseGeometry(parsedVertexData, scene)) {
  18473. return null; // null since geometry could be a primitive
  18474. }
  18475. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18476. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18477. if (parsedVertexData.delayLoadingFile) {
  18478. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18479. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18480. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18481. geometry._delayInfo = [];
  18482. if (parsedVertexData.hasUVs) {
  18483. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18484. }
  18485. if (parsedVertexData.hasUVs2) {
  18486. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18487. }
  18488. if (parsedVertexData.hasColors) {
  18489. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18490. }
  18491. if (parsedVertexData.hasMatricesIndices) {
  18492. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18493. }
  18494. if (parsedVertexData.hasMatricesWeights) {
  18495. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18496. }
  18497. geometry._delayLoadingFunction = importVertexData;
  18498. }
  18499. else {
  18500. importVertexData(parsedVertexData, geometry);
  18501. }
  18502. scene.pushGeometry(geometry, true);
  18503. return geometry;
  18504. };
  18505. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18506. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18507. mesh.id = parsedMesh.id;
  18508. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18509. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18510. if (parsedMesh.rotationQuaternion) {
  18511. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18512. }
  18513. else if (parsedMesh.rotation) {
  18514. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18515. }
  18516. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18517. if (parsedMesh.localMatrix) {
  18518. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18519. }
  18520. else if (parsedMesh.pivotMatrix) {
  18521. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18522. }
  18523. mesh.setEnabled(parsedMesh.isEnabled);
  18524. mesh.isVisible = parsedMesh.isVisible;
  18525. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18526. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18527. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18528. if (parsedMesh.applyFog !== undefined) {
  18529. mesh.applyFog = parsedMesh.applyFog;
  18530. }
  18531. if (parsedMesh.pickable !== undefined) {
  18532. mesh.isPickable = parsedMesh.pickable;
  18533. }
  18534. if (parsedMesh.alphaIndex !== undefined) {
  18535. mesh.alphaIndex = parsedMesh.alphaIndex;
  18536. }
  18537. mesh.receiveShadows = parsedMesh.receiveShadows;
  18538. mesh.billboardMode = parsedMesh.billboardMode;
  18539. if (parsedMesh.visibility !== undefined) {
  18540. mesh.visibility = parsedMesh.visibility;
  18541. }
  18542. mesh.checkCollisions = parsedMesh.checkCollisions;
  18543. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18544. // Parent
  18545. if (parsedMesh.parentId) {
  18546. mesh._waitingParentId = parsedMesh.parentId;
  18547. }
  18548. // Actions
  18549. if (parsedMesh.actions !== undefined) {
  18550. mesh._waitingActions = parsedMesh.actions;
  18551. }
  18552. // Geometry
  18553. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18554. if (parsedMesh.delayLoadingFile) {
  18555. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18556. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18557. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18558. if (parsedMesh._binaryInfo) {
  18559. mesh._binaryInfo = parsedMesh._binaryInfo;
  18560. }
  18561. mesh._delayInfo = [];
  18562. if (parsedMesh.hasUVs) {
  18563. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18564. }
  18565. if (parsedMesh.hasUVs2) {
  18566. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18567. }
  18568. if (parsedMesh.hasColors) {
  18569. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18570. }
  18571. if (parsedMesh.hasMatricesIndices) {
  18572. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18573. }
  18574. if (parsedMesh.hasMatricesWeights) {
  18575. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18576. }
  18577. mesh._delayLoadingFunction = importGeometry;
  18578. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18579. mesh._checkDelayState();
  18580. }
  18581. }
  18582. else {
  18583. importGeometry(parsedMesh, mesh);
  18584. }
  18585. // Material
  18586. if (parsedMesh.materialId) {
  18587. mesh.setMaterialByID(parsedMesh.materialId);
  18588. }
  18589. else {
  18590. mesh.material = null;
  18591. }
  18592. // Skeleton
  18593. if (parsedMesh.skeletonId > -1) {
  18594. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18595. }
  18596. // Physics
  18597. if (parsedMesh.physicsImpostor) {
  18598. if (!scene.isPhysicsEnabled()) {
  18599. scene.enablePhysics();
  18600. }
  18601. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18602. }
  18603. // Animations
  18604. if (parsedMesh.animations) {
  18605. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18606. var parsedAnimation = parsedMesh.animations[animationIndex];
  18607. mesh.animations.push(parseAnimation(parsedAnimation));
  18608. }
  18609. }
  18610. if (parsedMesh.autoAnimate) {
  18611. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18612. }
  18613. // Layer Mask
  18614. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18615. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18616. }
  18617. else {
  18618. mesh.layerMask = 0xFFFFFFFF;
  18619. }
  18620. // Instances
  18621. if (parsedMesh.instances) {
  18622. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18623. var parsedInstance = parsedMesh.instances[index];
  18624. var instance = mesh.createInstance(parsedInstance.name);
  18625. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18626. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18627. if (parsedInstance.rotationQuaternion) {
  18628. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18629. }
  18630. else if (parsedInstance.rotation) {
  18631. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18632. }
  18633. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18634. instance.checkCollisions = mesh.checkCollisions;
  18635. if (parsedMesh.animations) {
  18636. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18637. parsedAnimation = parsedMesh.animations[animationIndex];
  18638. instance.animations.push(parseAnimation(parsedAnimation));
  18639. }
  18640. }
  18641. }
  18642. }
  18643. return mesh;
  18644. };
  18645. var parseActions = function (parsedActions, object, scene) {
  18646. var actionManager = new BABYLON.ActionManager(scene);
  18647. if (object === null)
  18648. scene.actionManager = actionManager;
  18649. else
  18650. object.actionManager = actionManager;
  18651. // instanciate a new object
  18652. var instanciate = function (name, params) {
  18653. var newInstance = Object.create(BABYLON[name].prototype);
  18654. newInstance.constructor.apply(newInstance, params);
  18655. return newInstance;
  18656. };
  18657. var parseParameter = function (name, value, target, propertyPath) {
  18658. if (propertyPath === null) {
  18659. // String, boolean or float
  18660. var floatValue = parseFloat(value);
  18661. if (value === "true" || value === "false")
  18662. return value === "true";
  18663. else
  18664. return isNaN(floatValue) ? value : floatValue;
  18665. }
  18666. var effectiveTarget = propertyPath.split(".");
  18667. var values = value.split(",");
  18668. for (var i = 0; i < effectiveTarget.length; i++) {
  18669. target = target[effectiveTarget[i]];
  18670. }
  18671. // Return appropriate value with its type
  18672. if (target instanceof Boolean)
  18673. return values[0] === "true";
  18674. if (target instanceof String)
  18675. return values[0];
  18676. // Parameters with multiple values such as Vector3 etc.
  18677. var split = new Array();
  18678. for (var i = 0; i < values.length; i++)
  18679. split.push(parseFloat(values[i]));
  18680. if (target instanceof BABYLON.Vector3)
  18681. return BABYLON.Vector3.FromArray(split);
  18682. if (target instanceof BABYLON.Vector4)
  18683. return BABYLON.Vector4.FromArray(split);
  18684. if (target instanceof BABYLON.Color3)
  18685. return BABYLON.Color3.FromArray(split);
  18686. if (target instanceof BABYLON.Color4)
  18687. return BABYLON.Color4.FromArray(split);
  18688. return parseFloat(values[0]);
  18689. };
  18690. // traverse graph per trigger
  18691. var traverse = function (parsedAction, trigger, condition, action) {
  18692. var parameters = new Array();
  18693. var target = null;
  18694. var propertyPath = null;
  18695. // Parameters
  18696. if (parsedAction.type === 2)
  18697. parameters.push(actionManager);
  18698. else
  18699. parameters.push(trigger);
  18700. for (var i = 0; i < parsedAction.properties.length; i++) {
  18701. var value = parsedAction.properties[i].value;
  18702. var name = parsedAction.properties[i].name;
  18703. if (name === "target")
  18704. value = target = scene.getNodeByName(value);
  18705. else if (name === "parent")
  18706. value = scene.getNodeByName(value);
  18707. else if (name !== "propertyPath") {
  18708. if (parsedAction.type === 2 && name === "operator")
  18709. value = BABYLON.ValueCondition[value];
  18710. else
  18711. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  18712. }
  18713. else {
  18714. propertyPath = value;
  18715. }
  18716. parameters.push(value);
  18717. }
  18718. parameters.push(condition);
  18719. // If interpolate value action
  18720. if (parsedAction.name === "InterpolateValueAction") {
  18721. var param = parameters[parameters.length - 2];
  18722. parameters[parameters.length - 1] = param;
  18723. parameters[parameters.length - 2] = condition;
  18724. }
  18725. // Action or condition(s)
  18726. var newAction = instanciate(parsedAction.name, parameters);
  18727. if (newAction instanceof BABYLON.Condition) {
  18728. condition = newAction;
  18729. newAction = action;
  18730. }
  18731. else {
  18732. condition = null;
  18733. if (action)
  18734. action.then(newAction);
  18735. else
  18736. actionManager.registerAction(newAction);
  18737. }
  18738. for (var i = 0; i < parsedAction.children.length; i++)
  18739. traverse(parsedAction.children[i], trigger, condition, newAction);
  18740. };
  18741. for (var i = 0; i < parsedActions.children.length; i++) {
  18742. var triggerParams;
  18743. var trigger = parsedActions.children[i];
  18744. if (trigger.properties.length > 0) {
  18745. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  18746. }
  18747. else
  18748. triggerParams = BABYLON.ActionManager[trigger.name];
  18749. for (var j = 0; j < trigger.children.length; j++)
  18750. traverse(trigger.children[j], triggerParams, null, null);
  18751. }
  18752. };
  18753. var parseSound = function (parsedSound, scene, rootUrl) {
  18754. var soundName = parsedSound.name;
  18755. var soundUrl = rootUrl + soundName;
  18756. var options = {
  18757. autoplay: parsedSound.autoplay,
  18758. loop: parsedSound.loop,
  18759. volume: parsedSound.volume,
  18760. spatialSound: parsedSound.spatialSound,
  18761. maxDistance: parsedSound.maxDistance,
  18762. rolloffFactor: parsedSound.rolloffFactor,
  18763. refDistance: parsedSound.refDistance,
  18764. distanceModel: parsedSound.distanceModel,
  18765. panningModel: parsedSound.panningModel,
  18766. playbackRate: parsedSound.playbackRate
  18767. };
  18768. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  18769. scene._removePendingData(newSound);
  18770. }, options);
  18771. scene._addPendingData(newSound);
  18772. if (parsedSound.position) {
  18773. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  18774. newSound.setPosition(soundPosition);
  18775. }
  18776. if (parsedSound.isDirectional) {
  18777. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  18778. if (parsedSound.localDirectionToMesh) {
  18779. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  18780. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  18781. }
  18782. }
  18783. if (parsedSound.connectedMeshId) {
  18784. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  18785. if (connectedMesh) {
  18786. newSound.attachToMesh(connectedMesh);
  18787. }
  18788. }
  18789. };
  18790. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18791. names = (names instanceof Array) ? names : [names];
  18792. for (var i in names) {
  18793. if (mesh.name === names[i]) {
  18794. hierarchyIds.push(mesh.id);
  18795. return true;
  18796. }
  18797. }
  18798. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18799. hierarchyIds.push(mesh.id);
  18800. return true;
  18801. }
  18802. return false;
  18803. };
  18804. var importVertexData = function (parsedVertexData, geometry) {
  18805. var vertexData = new BABYLON.VertexData();
  18806. // positions
  18807. var positions = parsedVertexData.positions;
  18808. if (positions) {
  18809. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18810. }
  18811. // normals
  18812. var normals = parsedVertexData.normals;
  18813. if (normals) {
  18814. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18815. }
  18816. // uvs
  18817. var uvs = parsedVertexData.uvs;
  18818. if (uvs) {
  18819. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  18820. }
  18821. // uv2s
  18822. var uv2s = parsedVertexData.uv2s;
  18823. if (uv2s) {
  18824. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  18825. }
  18826. // colors
  18827. var colors = parsedVertexData.colors;
  18828. if (colors) {
  18829. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  18830. }
  18831. // matricesIndices
  18832. var matricesIndices = parsedVertexData.matricesIndices;
  18833. if (matricesIndices) {
  18834. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  18835. }
  18836. // matricesWeights
  18837. var matricesWeights = parsedVertexData.matricesWeights;
  18838. if (matricesWeights) {
  18839. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  18840. }
  18841. // indices
  18842. var indices = parsedVertexData.indices;
  18843. if (indices) {
  18844. vertexData.indices = indices;
  18845. }
  18846. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  18847. };
  18848. var importGeometry = function (parsedGeometry, mesh) {
  18849. var scene = mesh.getScene();
  18850. // Geometry
  18851. var geometryId = parsedGeometry.geometryId;
  18852. if (geometryId) {
  18853. var geometry = scene.getGeometryByID(geometryId);
  18854. if (geometry) {
  18855. geometry.applyToMesh(mesh);
  18856. }
  18857. }
  18858. else if (parsedGeometry instanceof ArrayBuffer) {
  18859. var binaryInfo = mesh._binaryInfo;
  18860. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  18861. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  18862. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  18863. }
  18864. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  18865. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  18866. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  18867. }
  18868. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  18869. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  18870. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  18871. }
  18872. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  18873. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  18874. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  18875. }
  18876. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  18877. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  18878. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  18879. }
  18880. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  18881. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  18882. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  18883. }
  18884. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  18885. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  18886. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  18887. }
  18888. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  18889. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  18890. mesh.setIndices(indicesData);
  18891. }
  18892. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  18893. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  18894. mesh.subMeshes = [];
  18895. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  18896. var materialIndex = subMeshesData[(i * 5) + 0];
  18897. var verticesStart = subMeshesData[(i * 5) + 1];
  18898. var verticesCount = subMeshesData[(i * 5) + 2];
  18899. var indexStart = subMeshesData[(i * 5) + 3];
  18900. var indexCount = subMeshesData[(i * 5) + 4];
  18901. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  18902. }
  18903. }
  18904. }
  18905. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  18906. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  18907. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  18908. if (parsedGeometry.uvs) {
  18909. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  18910. }
  18911. if (parsedGeometry.uvs2) {
  18912. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  18913. }
  18914. if (parsedGeometry.colors) {
  18915. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  18916. }
  18917. if (parsedGeometry.matricesIndices) {
  18918. if (!parsedGeometry.matricesIndices._isExpanded) {
  18919. var floatIndices = [];
  18920. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  18921. var matricesIndex = parsedGeometry.matricesIndices[i];
  18922. floatIndices.push(matricesIndex & 0x000000FF);
  18923. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  18924. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  18925. floatIndices.push(matricesIndex >> 24);
  18926. }
  18927. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  18928. }
  18929. else {
  18930. delete parsedGeometry.matricesIndices._isExpanded;
  18931. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  18932. }
  18933. }
  18934. if (parsedGeometry.matricesWeights) {
  18935. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  18936. }
  18937. mesh.setIndices(parsedGeometry.indices);
  18938. // SubMeshes
  18939. if (parsedGeometry.subMeshes) {
  18940. mesh.subMeshes = [];
  18941. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  18942. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  18943. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  18944. }
  18945. }
  18946. }
  18947. // Flat shading
  18948. if (mesh._shouldGenerateFlatShading) {
  18949. mesh.convertToFlatShadedMesh();
  18950. delete mesh._shouldGenerateFlatShading;
  18951. }
  18952. // Update
  18953. mesh.computeWorldMatrix(true);
  18954. // Octree
  18955. if (scene._selectionOctree) {
  18956. scene._selectionOctree.addMesh(mesh);
  18957. }
  18958. };
  18959. BABYLON.SceneLoader.RegisterPlugin({
  18960. extensions: ".babylon",
  18961. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  18962. var parsedData = JSON.parse(data);
  18963. var loadedSkeletonsIds = [];
  18964. var loadedMaterialsIds = [];
  18965. var hierarchyIds = [];
  18966. for (var index = 0; index < parsedData.meshes.length; index++) {
  18967. var parsedMesh = parsedData.meshes[index];
  18968. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  18969. if (meshesNames instanceof Array) {
  18970. // Remove found mesh name from list.
  18971. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  18972. }
  18973. // Material ?
  18974. if (parsedMesh.materialId) {
  18975. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  18976. if (!materialFound) {
  18977. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  18978. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  18979. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  18980. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18981. var subMatId = parsedMultiMaterial.materials[matIndex];
  18982. loadedMaterialsIds.push(subMatId);
  18983. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  18984. }
  18985. loadedMaterialsIds.push(parsedMultiMaterial.id);
  18986. parseMultiMaterial(parsedMultiMaterial, scene);
  18987. materialFound = true;
  18988. break;
  18989. }
  18990. }
  18991. }
  18992. if (!materialFound) {
  18993. loadedMaterialsIds.push(parsedMesh.materialId);
  18994. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  18995. }
  18996. }
  18997. // Skeleton ?
  18998. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  18999. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19000. if (!skeletonAlreadyLoaded) {
  19001. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19002. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19003. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19004. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19005. loadedSkeletonsIds.push(parsedSkeleton.id);
  19006. }
  19007. }
  19008. }
  19009. }
  19010. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19011. meshes.push(mesh);
  19012. }
  19013. }
  19014. for (index = 0; index < scene.meshes.length; index++) {
  19015. var currentMesh = scene.meshes[index];
  19016. if (currentMesh._waitingParentId) {
  19017. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19018. currentMesh._waitingParentId = undefined;
  19019. }
  19020. }
  19021. // Particles
  19022. if (parsedData.particleSystems) {
  19023. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19024. var parsedParticleSystem = parsedData.particleSystems[index];
  19025. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19026. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19027. }
  19028. }
  19029. }
  19030. return true;
  19031. },
  19032. load: function (scene, data, rootUrl) {
  19033. var parsedData = JSON.parse(data);
  19034. // Scene
  19035. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19036. scene.autoClear = parsedData.autoClear;
  19037. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19038. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19039. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19040. // Fog
  19041. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19042. scene.fogMode = parsedData.fogMode;
  19043. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19044. scene.fogStart = parsedData.fogStart;
  19045. scene.fogEnd = parsedData.fogEnd;
  19046. scene.fogDensity = parsedData.fogDensity;
  19047. }
  19048. for (var index = 0; index < parsedData.lights.length; index++) {
  19049. var parsedLight = parsedData.lights[index];
  19050. parseLight(parsedLight, scene);
  19051. }
  19052. // Materials
  19053. if (parsedData.materials) {
  19054. for (index = 0; index < parsedData.materials.length; index++) {
  19055. var parsedMaterial = parsedData.materials[index];
  19056. parseMaterial(parsedMaterial, scene, rootUrl);
  19057. }
  19058. }
  19059. if (parsedData.multiMaterials) {
  19060. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19061. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19062. parseMultiMaterial(parsedMultiMaterial, scene);
  19063. }
  19064. }
  19065. // Skeletons
  19066. if (parsedData.skeletons) {
  19067. for (index = 0; index < parsedData.skeletons.length; index++) {
  19068. var parsedSkeleton = parsedData.skeletons[index];
  19069. parseSkeleton(parsedSkeleton, scene);
  19070. }
  19071. }
  19072. // Geometries
  19073. var geometries = parsedData.geometries;
  19074. if (geometries) {
  19075. // Boxes
  19076. var boxes = geometries.boxes;
  19077. if (boxes) {
  19078. for (index = 0; index < boxes.length; index++) {
  19079. var parsedBox = boxes[index];
  19080. parseBox(parsedBox, scene);
  19081. }
  19082. }
  19083. // Spheres
  19084. var spheres = geometries.spheres;
  19085. if (spheres) {
  19086. for (index = 0; index < spheres.length; index++) {
  19087. var parsedSphere = spheres[index];
  19088. parseSphere(parsedSphere, scene);
  19089. }
  19090. }
  19091. // Cylinders
  19092. var cylinders = geometries.cylinders;
  19093. if (cylinders) {
  19094. for (index = 0; index < cylinders.length; index++) {
  19095. var parsedCylinder = cylinders[index];
  19096. parseCylinder(parsedCylinder, scene);
  19097. }
  19098. }
  19099. // Toruses
  19100. var toruses = geometries.toruses;
  19101. if (toruses) {
  19102. for (index = 0; index < toruses.length; index++) {
  19103. var parsedTorus = toruses[index];
  19104. parseTorus(parsedTorus, scene);
  19105. }
  19106. }
  19107. // Grounds
  19108. var grounds = geometries.grounds;
  19109. if (grounds) {
  19110. for (index = 0; index < grounds.length; index++) {
  19111. var parsedGround = grounds[index];
  19112. parseGround(parsedGround, scene);
  19113. }
  19114. }
  19115. // Planes
  19116. var planes = geometries.planes;
  19117. if (planes) {
  19118. for (index = 0; index < planes.length; index++) {
  19119. var parsedPlane = planes[index];
  19120. parsePlane(parsedPlane, scene);
  19121. }
  19122. }
  19123. // TorusKnots
  19124. var torusKnots = geometries.torusKnots;
  19125. if (torusKnots) {
  19126. for (index = 0; index < torusKnots.length; index++) {
  19127. var parsedTorusKnot = torusKnots[index];
  19128. parseTorusKnot(parsedTorusKnot, scene);
  19129. }
  19130. }
  19131. // VertexData
  19132. var vertexData = geometries.vertexData;
  19133. if (vertexData) {
  19134. for (index = 0; index < vertexData.length; index++) {
  19135. var parsedVertexData = vertexData[index];
  19136. parseVertexData(parsedVertexData, scene, rootUrl);
  19137. }
  19138. }
  19139. }
  19140. for (index = 0; index < parsedData.meshes.length; index++) {
  19141. var parsedMesh = parsedData.meshes[index];
  19142. parseMesh(parsedMesh, scene, rootUrl);
  19143. }
  19144. for (index = 0; index < parsedData.cameras.length; index++) {
  19145. var parsedCamera = parsedData.cameras[index];
  19146. parseCamera(parsedCamera, scene);
  19147. }
  19148. if (parsedData.activeCameraID) {
  19149. scene.setActiveCameraByID(parsedData.activeCameraID);
  19150. }
  19151. for (index = 0; index < scene.cameras.length; index++) {
  19152. var camera = scene.cameras[index];
  19153. if (camera._waitingParentId) {
  19154. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19155. camera._waitingParentId = undefined;
  19156. }
  19157. }
  19158. for (index = 0; index < scene.lights.length; index++) {
  19159. var light = scene.lights[index];
  19160. if (light._waitingParentId) {
  19161. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19162. light._waitingParentId = undefined;
  19163. }
  19164. }
  19165. for (index = 0; index < scene.meshes.length; index++) {
  19166. var mesh = scene.meshes[index];
  19167. if (mesh._waitingParentId) {
  19168. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19169. mesh._waitingParentId = undefined;
  19170. }
  19171. if (mesh._waitingActions) {
  19172. parseActions(mesh._waitingActions, mesh, scene);
  19173. mesh._waitingActions = undefined;
  19174. }
  19175. }
  19176. // Particles Systems
  19177. if (parsedData.particleSystems) {
  19178. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19179. var parsedParticleSystem = parsedData.particleSystems[index];
  19180. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19181. }
  19182. }
  19183. // Lens flares
  19184. if (parsedData.lensFlareSystems) {
  19185. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19186. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19187. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19188. }
  19189. }
  19190. // Shadows
  19191. if (parsedData.shadowGenerators) {
  19192. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  19193. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  19194. parseShadowGenerator(parsedShadowGenerator, scene);
  19195. }
  19196. }
  19197. // Sounds
  19198. if (parsedData.sounds && BABYLON.Engine.audioEngine.canUseWebAudio) {
  19199. for (index = 0; index < parsedData.sounds.length; index++) {
  19200. var parsedSound = parsedData.sounds[index];
  19201. parseSound(parsedSound, scene, rootUrl);
  19202. }
  19203. }
  19204. // Actions (scene)
  19205. if (parsedData.actions) {
  19206. parseActions(parsedData.actions, null, scene);
  19207. }
  19208. // Finish
  19209. return true;
  19210. }
  19211. });
  19212. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  19213. })(BABYLON || (BABYLON = {}));
  19214. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  19215. (function (BABYLON) {
  19216. // Unique ID when we import meshes from Babylon to CSG
  19217. var currentCSGMeshId = 0;
  19218. // # class Vertex
  19219. // Represents a vertex of a polygon. Use your own vertex class instead of this
  19220. // one to provide additional features like texture coordinates and vertex
  19221. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  19222. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  19223. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  19224. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  19225. // is not used anywhere else.
  19226. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  19227. var Vertex = (function () {
  19228. function Vertex(pos, normal, uv) {
  19229. this.pos = pos;
  19230. this.normal = normal;
  19231. this.uv = uv;
  19232. }
  19233. Vertex.prototype.clone = function () {
  19234. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  19235. };
  19236. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  19237. // orientation of a polygon is flipped.
  19238. Vertex.prototype.flip = function () {
  19239. this.normal = this.normal.scale(-1);
  19240. };
  19241. // Create a new vertex between this vertex and `other` by linearly
  19242. // interpolating all properties using a parameter of `t`. Subclasses should
  19243. // override this to interpolate additional properties.
  19244. Vertex.prototype.interpolate = function (other, t) {
  19245. 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));
  19246. };
  19247. return Vertex;
  19248. })();
  19249. // # class Plane
  19250. // Represents a plane in 3D space.
  19251. var Plane = (function () {
  19252. function Plane(normal, w) {
  19253. this.normal = normal;
  19254. this.w = w;
  19255. }
  19256. Plane.FromPoints = function (a, b, c) {
  19257. var v0 = c.subtract(a);
  19258. var v1 = b.subtract(a);
  19259. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  19260. return null;
  19261. }
  19262. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  19263. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  19264. };
  19265. Plane.prototype.clone = function () {
  19266. return new Plane(this.normal.clone(), this.w);
  19267. };
  19268. Plane.prototype.flip = function () {
  19269. this.normal.scaleInPlace(-1);
  19270. this.w = -this.w;
  19271. };
  19272. // Split `polygon` by this plane if needed, then put the polygon or polygon
  19273. // fragments in the appropriate lists. Coplanar polygons go into either
  19274. // `coplanarFront` or `coplanarBack` depending on their orientation with
  19275. // respect to this plane. Polygons in front or in back of this plane go into
  19276. // either `front` or `back`.
  19277. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  19278. var COPLANAR = 0;
  19279. var FRONT = 1;
  19280. var BACK = 2;
  19281. var SPANNING = 3;
  19282. // Classify each point as well as the entire polygon into one of the above
  19283. // four classes.
  19284. var polygonType = 0;
  19285. var types = [];
  19286. for (var i = 0; i < polygon.vertices.length; i++) {
  19287. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  19288. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  19289. polygonType |= type;
  19290. types.push(type);
  19291. }
  19292. switch (polygonType) {
  19293. case COPLANAR:
  19294. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  19295. break;
  19296. case FRONT:
  19297. front.push(polygon);
  19298. break;
  19299. case BACK:
  19300. back.push(polygon);
  19301. break;
  19302. case SPANNING:
  19303. var f = [], b = [];
  19304. for (i = 0; i < polygon.vertices.length; i++) {
  19305. var j = (i + 1) % polygon.vertices.length;
  19306. var ti = types[i], tj = types[j];
  19307. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  19308. if (ti != BACK)
  19309. f.push(vi);
  19310. if (ti != FRONT)
  19311. b.push(ti != BACK ? vi.clone() : vi);
  19312. if ((ti | tj) == SPANNING) {
  19313. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  19314. var v = vi.interpolate(vj, t);
  19315. f.push(v);
  19316. b.push(v.clone());
  19317. }
  19318. }
  19319. if (f.length >= 3) {
  19320. var poly = new Polygon(f, polygon.shared);
  19321. if (poly.plane)
  19322. front.push(poly);
  19323. }
  19324. if (b.length >= 3) {
  19325. poly = new Polygon(b, polygon.shared);
  19326. if (poly.plane)
  19327. back.push(poly);
  19328. }
  19329. break;
  19330. }
  19331. };
  19332. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  19333. // point is on the plane.
  19334. Plane.EPSILON = 1e-5;
  19335. return Plane;
  19336. })();
  19337. // # class Polygon
  19338. // Represents a convex polygon. The vertices used to initialize a polygon must
  19339. // be coplanar and form a convex loop.
  19340. //
  19341. // Each convex polygon has a `shared` property, which is shared between all
  19342. // polygons that are clones of each other or were split from the same polygon.
  19343. // This can be used to define per-polygon properties (such as surface color).
  19344. var Polygon = (function () {
  19345. function Polygon(vertices, shared) {
  19346. this.vertices = vertices;
  19347. this.shared = shared;
  19348. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  19349. }
  19350. Polygon.prototype.clone = function () {
  19351. var vertices = this.vertices.map(function (v) { return v.clone(); });
  19352. return new Polygon(vertices, this.shared);
  19353. };
  19354. Polygon.prototype.flip = function () {
  19355. this.vertices.reverse().map(function (v) {
  19356. v.flip();
  19357. });
  19358. this.plane.flip();
  19359. };
  19360. return Polygon;
  19361. })();
  19362. // # class Node
  19363. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  19364. // by picking a polygon to split along. That polygon (and all other coplanar
  19365. // polygons) are added directly to that node and the other polygons are added to
  19366. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  19367. // no distinction between internal and leaf nodes.
  19368. var Node = (function () {
  19369. function Node(polygons) {
  19370. this.plane = null;
  19371. this.front = null;
  19372. this.back = null;
  19373. this.polygons = [];
  19374. if (polygons) {
  19375. this.build(polygons);
  19376. }
  19377. }
  19378. Node.prototype.clone = function () {
  19379. var node = new Node();
  19380. node.plane = this.plane && this.plane.clone();
  19381. node.front = this.front && this.front.clone();
  19382. node.back = this.back && this.back.clone();
  19383. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  19384. return node;
  19385. };
  19386. // Convert solid space to empty space and empty space to solid space.
  19387. Node.prototype.invert = function () {
  19388. for (var i = 0; i < this.polygons.length; i++) {
  19389. this.polygons[i].flip();
  19390. }
  19391. if (this.plane) {
  19392. this.plane.flip();
  19393. }
  19394. if (this.front) {
  19395. this.front.invert();
  19396. }
  19397. if (this.back) {
  19398. this.back.invert();
  19399. }
  19400. var temp = this.front;
  19401. this.front = this.back;
  19402. this.back = temp;
  19403. };
  19404. // Recursively remove all polygons in `polygons` that are inside this BSP
  19405. // tree.
  19406. Node.prototype.clipPolygons = function (polygons) {
  19407. if (!this.plane)
  19408. return polygons.slice();
  19409. var front = [], back = [];
  19410. for (var i = 0; i < polygons.length; i++) {
  19411. this.plane.splitPolygon(polygons[i], front, back, front, back);
  19412. }
  19413. if (this.front) {
  19414. front = this.front.clipPolygons(front);
  19415. }
  19416. if (this.back) {
  19417. back = this.back.clipPolygons(back);
  19418. }
  19419. else {
  19420. back = [];
  19421. }
  19422. return front.concat(back);
  19423. };
  19424. // Remove all polygons in this BSP tree that are inside the other BSP tree
  19425. // `bsp`.
  19426. Node.prototype.clipTo = function (bsp) {
  19427. this.polygons = bsp.clipPolygons(this.polygons);
  19428. if (this.front)
  19429. this.front.clipTo(bsp);
  19430. if (this.back)
  19431. this.back.clipTo(bsp);
  19432. };
  19433. // Return a list of all polygons in this BSP tree.
  19434. Node.prototype.allPolygons = function () {
  19435. var polygons = this.polygons.slice();
  19436. if (this.front)
  19437. polygons = polygons.concat(this.front.allPolygons());
  19438. if (this.back)
  19439. polygons = polygons.concat(this.back.allPolygons());
  19440. return polygons;
  19441. };
  19442. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  19443. // new polygons are filtered down to the bottom of the tree and become new
  19444. // nodes there. Each set of polygons is partitioned using the first polygon
  19445. // (no heuristic is used to pick a good split).
  19446. Node.prototype.build = function (polygons) {
  19447. if (!polygons.length)
  19448. return;
  19449. if (!this.plane)
  19450. this.plane = polygons[0].plane.clone();
  19451. var front = [], back = [];
  19452. for (var i = 0; i < polygons.length; i++) {
  19453. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  19454. }
  19455. if (front.length) {
  19456. if (!this.front)
  19457. this.front = new Node();
  19458. this.front.build(front);
  19459. }
  19460. if (back.length) {
  19461. if (!this.back)
  19462. this.back = new Node();
  19463. this.back.build(back);
  19464. }
  19465. };
  19466. return Node;
  19467. })();
  19468. var CSG = (function () {
  19469. function CSG() {
  19470. this.polygons = new Array();
  19471. }
  19472. // Convert BABYLON.Mesh to BABYLON.CSG
  19473. CSG.FromMesh = function (mesh) {
  19474. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  19475. if (mesh instanceof BABYLON.Mesh) {
  19476. mesh.computeWorldMatrix(true);
  19477. var matrix = mesh.getWorldMatrix();
  19478. var meshPosition = mesh.position.clone();
  19479. var meshRotation = mesh.rotation.clone();
  19480. var meshScaling = mesh.scaling.clone();
  19481. }
  19482. else {
  19483. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  19484. }
  19485. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19486. var subMeshes = mesh.subMeshes;
  19487. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  19488. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  19489. vertices = [];
  19490. for (var j = 0; j < 3; j++) {
  19491. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  19492. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  19493. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  19494. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  19495. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  19496. vertex = new Vertex(position, normal, uv);
  19497. vertices.push(vertex);
  19498. }
  19499. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  19500. // To handle the case of degenerated triangle
  19501. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  19502. if (polygon.plane)
  19503. polygons.push(polygon);
  19504. }
  19505. }
  19506. var csg = CSG.FromPolygons(polygons);
  19507. csg.matrix = matrix;
  19508. csg.position = meshPosition;
  19509. csg.rotation = meshRotation;
  19510. csg.scaling = meshScaling;
  19511. currentCSGMeshId++;
  19512. return csg;
  19513. };
  19514. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  19515. CSG.FromPolygons = function (polygons) {
  19516. var csg = new BABYLON.CSG();
  19517. csg.polygons = polygons;
  19518. return csg;
  19519. };
  19520. CSG.prototype.clone = function () {
  19521. var csg = new BABYLON.CSG();
  19522. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  19523. csg.copyTransformAttributes(this);
  19524. return csg;
  19525. };
  19526. CSG.prototype.toPolygons = function () {
  19527. return this.polygons;
  19528. };
  19529. CSG.prototype.union = function (csg) {
  19530. var a = new Node(this.clone().polygons);
  19531. var b = new Node(csg.clone().polygons);
  19532. a.clipTo(b);
  19533. b.clipTo(a);
  19534. b.invert();
  19535. b.clipTo(a);
  19536. b.invert();
  19537. a.build(b.allPolygons());
  19538. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19539. };
  19540. CSG.prototype.unionInPlace = function (csg) {
  19541. var a = new Node(this.polygons);
  19542. var b = new Node(csg.polygons);
  19543. a.clipTo(b);
  19544. b.clipTo(a);
  19545. b.invert();
  19546. b.clipTo(a);
  19547. b.invert();
  19548. a.build(b.allPolygons());
  19549. this.polygons = a.allPolygons();
  19550. };
  19551. CSG.prototype.subtract = function (csg) {
  19552. var a = new Node(this.clone().polygons);
  19553. var b = new Node(csg.clone().polygons);
  19554. a.invert();
  19555. a.clipTo(b);
  19556. b.clipTo(a);
  19557. b.invert();
  19558. b.clipTo(a);
  19559. b.invert();
  19560. a.build(b.allPolygons());
  19561. a.invert();
  19562. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19563. };
  19564. CSG.prototype.subtractInPlace = function (csg) {
  19565. var a = new Node(this.polygons);
  19566. var b = new Node(csg.polygons);
  19567. a.invert();
  19568. a.clipTo(b);
  19569. b.clipTo(a);
  19570. b.invert();
  19571. b.clipTo(a);
  19572. b.invert();
  19573. a.build(b.allPolygons());
  19574. a.invert();
  19575. this.polygons = a.allPolygons();
  19576. };
  19577. CSG.prototype.intersect = function (csg) {
  19578. var a = new Node(this.clone().polygons);
  19579. var b = new Node(csg.clone().polygons);
  19580. a.invert();
  19581. b.clipTo(a);
  19582. b.invert();
  19583. a.clipTo(b);
  19584. b.clipTo(a);
  19585. a.build(b.allPolygons());
  19586. a.invert();
  19587. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19588. };
  19589. CSG.prototype.intersectInPlace = function (csg) {
  19590. var a = new Node(this.polygons);
  19591. var b = new Node(csg.polygons);
  19592. a.invert();
  19593. b.clipTo(a);
  19594. b.invert();
  19595. a.clipTo(b);
  19596. b.clipTo(a);
  19597. a.build(b.allPolygons());
  19598. a.invert();
  19599. this.polygons = a.allPolygons();
  19600. };
  19601. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  19602. // not modified.
  19603. CSG.prototype.inverse = function () {
  19604. var csg = this.clone();
  19605. csg.inverseInPlace();
  19606. return csg;
  19607. };
  19608. CSG.prototype.inverseInPlace = function () {
  19609. this.polygons.map(function (p) {
  19610. p.flip();
  19611. });
  19612. };
  19613. // This is used to keep meshes transformations so they can be restored
  19614. // when we build back a Babylon Mesh
  19615. // NB : All CSG operations are performed in world coordinates
  19616. CSG.prototype.copyTransformAttributes = function (csg) {
  19617. this.matrix = csg.matrix;
  19618. this.position = csg.position;
  19619. this.rotation = csg.rotation;
  19620. this.scaling = csg.scaling;
  19621. return this;
  19622. };
  19623. // Build Raw mesh from CSG
  19624. // Coordinates here are in world space
  19625. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  19626. var matrix = this.matrix.clone();
  19627. matrix.invert();
  19628. 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;
  19629. if (keepSubMeshes) {
  19630. // Sort Polygons, since subMeshes are indices range
  19631. polygons.sort(function (a, b) {
  19632. if (a.shared.meshId === b.shared.meshId) {
  19633. return a.shared.subMeshId - b.shared.subMeshId;
  19634. }
  19635. else {
  19636. return a.shared.meshId - b.shared.meshId;
  19637. }
  19638. });
  19639. }
  19640. for (var i = 0, il = polygons.length; i < il; i++) {
  19641. polygon = polygons[i];
  19642. // Building SubMeshes
  19643. if (!subMesh_dict[polygon.shared.meshId]) {
  19644. subMesh_dict[polygon.shared.meshId] = {};
  19645. }
  19646. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  19647. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  19648. indexStart: +Infinity,
  19649. indexEnd: -Infinity,
  19650. materialIndex: polygon.shared.materialIndex
  19651. };
  19652. }
  19653. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  19654. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  19655. polygonIndices[0] = 0;
  19656. polygonIndices[1] = j - 1;
  19657. polygonIndices[2] = j;
  19658. for (var k = 0; k < 3; k++) {
  19659. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  19660. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  19661. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  19662. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  19663. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  19664. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  19665. // Check if 2 points can be merged
  19666. 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)) {
  19667. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  19668. uvs.push(uv.x, uv.y);
  19669. normals.push(normal.x, normal.y, normal.z);
  19670. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  19671. }
  19672. indices.push(vertex_idx);
  19673. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  19674. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  19675. currentIndex++;
  19676. }
  19677. }
  19678. }
  19679. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  19680. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19681. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  19682. mesh.setIndices(indices);
  19683. if (keepSubMeshes) {
  19684. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  19685. var materialIndexOffset = 0, materialMaxIndex;
  19686. mesh.subMeshes.length = 0;
  19687. for (var m in subMesh_dict) {
  19688. materialMaxIndex = -1;
  19689. for (var sm in subMesh_dict[m]) {
  19690. subMesh_obj = subMesh_dict[m][sm];
  19691. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  19692. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  19693. }
  19694. materialIndexOffset += ++materialMaxIndex;
  19695. }
  19696. }
  19697. return mesh;
  19698. };
  19699. // Build Mesh from CSG taking material and transforms into account
  19700. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  19701. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  19702. mesh.material = material;
  19703. mesh.position.copyFrom(this.position);
  19704. mesh.rotation.copyFrom(this.rotation);
  19705. mesh.scaling.copyFrom(this.scaling);
  19706. mesh.computeWorldMatrix(true);
  19707. return mesh;
  19708. };
  19709. return CSG;
  19710. })();
  19711. BABYLON.CSG = CSG;
  19712. })(BABYLON || (BABYLON = {}));
  19713. //# sourceMappingURL=babylon.csg.js.map
  19714. var BABYLON;
  19715. (function (BABYLON) {
  19716. var OculusDistortionCorrectionPostProcess = (function (_super) {
  19717. __extends(OculusDistortionCorrectionPostProcess, _super);
  19718. //ANY
  19719. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  19720. var _this = this;
  19721. _super.call(this, name, "oculusDistortionCorrection", [
  19722. 'LensCenter',
  19723. 'Scale',
  19724. 'ScaleIn',
  19725. 'HmdWarpParam'
  19726. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  19727. this._isRightEye = isRightEye;
  19728. this._distortionFactors = cameraSettings.DistortionK;
  19729. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  19730. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  19731. this.onSizeChanged = function () {
  19732. _this.aspectRatio = _this.width * .5 / _this.height;
  19733. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  19734. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  19735. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  19736. };
  19737. this.onApply = function (effect) {
  19738. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  19739. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  19740. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  19741. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  19742. };
  19743. }
  19744. return OculusDistortionCorrectionPostProcess;
  19745. })(BABYLON.PostProcess);
  19746. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  19747. })(BABYLON || (BABYLON = {}));
  19748. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  19749. // 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
  19750. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  19751. var BABYLON;
  19752. (function (BABYLON) {
  19753. (function (JoystickAxis) {
  19754. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  19755. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  19756. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  19757. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  19758. var JoystickAxis = BABYLON.JoystickAxis;
  19759. var VirtualJoystick = (function () {
  19760. function VirtualJoystick(leftJoystick) {
  19761. var _this = this;
  19762. if (leftJoystick) {
  19763. this._leftJoystick = true;
  19764. }
  19765. else {
  19766. this._leftJoystick = false;
  19767. }
  19768. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  19769. VirtualJoystick._globalJoystickIndex++;
  19770. // By default left & right arrow keys are moving the X
  19771. // and up & down keys are moving the Y
  19772. this._axisTargetedByLeftAndRight = 0 /* X */;
  19773. this._axisTargetedByUpAndDown = 1 /* Y */;
  19774. this.reverseLeftRight = false;
  19775. this.reverseUpDown = false;
  19776. // collections of pointers
  19777. this._touches = new BABYLON.VirtualJoystick.Collection();
  19778. this.deltaPosition = BABYLON.Vector3.Zero();
  19779. this._joystickSensibility = 25;
  19780. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19781. this._rotationSpeed = 25;
  19782. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  19783. this._rotateOnAxisRelativeToMesh = false;
  19784. // injecting a canvas element on top of the canvas 3D game
  19785. if (!VirtualJoystick.vjCanvas) {
  19786. window.addEventListener("resize", function () {
  19787. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19788. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19789. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  19790. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  19791. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  19792. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  19793. }, false);
  19794. VirtualJoystick.vjCanvas = document.createElement("canvas");
  19795. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19796. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19797. VirtualJoystick.vjCanvas.width = window.innerWidth;
  19798. VirtualJoystick.vjCanvas.height = window.innerHeight;
  19799. VirtualJoystick.vjCanvas.style.width = "100%";
  19800. VirtualJoystick.vjCanvas.style.height = "100%";
  19801. VirtualJoystick.vjCanvas.style.position = "absolute";
  19802. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  19803. VirtualJoystick.vjCanvas.style.top = "0px";
  19804. VirtualJoystick.vjCanvas.style.left = "0px";
  19805. VirtualJoystick.vjCanvas.style.zIndex = "5";
  19806. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  19807. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  19808. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  19809. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19810. document.body.appendChild(VirtualJoystick.vjCanvas);
  19811. }
  19812. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  19813. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  19814. this.pressed = false;
  19815. // default joystick color
  19816. this._joystickColor = "cyan";
  19817. this._joystickPointerID = -1;
  19818. // current joystick position
  19819. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  19820. // origin joystick position
  19821. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  19822. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  19823. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  19824. _this._onPointerDown(evt);
  19825. }, false);
  19826. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  19827. _this._onPointerMove(evt);
  19828. }, false);
  19829. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  19830. _this._onPointerUp(evt);
  19831. }, false);
  19832. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  19833. _this._onPointerUp(evt);
  19834. }, false);
  19835. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  19836. evt.preventDefault(); // Disables system menu
  19837. }, false);
  19838. requestAnimationFrame(function () {
  19839. _this._drawVirtualJoystick();
  19840. });
  19841. }
  19842. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  19843. this._joystickSensibility = newJoystickSensibility;
  19844. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19845. };
  19846. VirtualJoystick.prototype._onPointerDown = function (e) {
  19847. var positionOnScreenCondition;
  19848. e.preventDefault();
  19849. if (this._leftJoystick === true) {
  19850. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  19851. }
  19852. else {
  19853. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  19854. }
  19855. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  19856. // First contact will be dedicated to the virtual joystick
  19857. this._joystickPointerID = e.pointerId;
  19858. this._joystickPointerStartPos.x = e.clientX;
  19859. this._joystickPointerStartPos.y = e.clientY;
  19860. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  19861. this._deltaJoystickVector.x = 0;
  19862. this._deltaJoystickVector.y = 0;
  19863. this.pressed = true;
  19864. this._touches.add(e.pointerId.toString(), e);
  19865. }
  19866. else {
  19867. // You can only trigger the action buttons with a joystick declared
  19868. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  19869. this._action();
  19870. this._touches.add(e.pointerId.toString(), e);
  19871. }
  19872. }
  19873. };
  19874. VirtualJoystick.prototype._onPointerMove = function (e) {
  19875. // If the current pointer is the one associated to the joystick (first touch contact)
  19876. if (this._joystickPointerID == e.pointerId) {
  19877. this._joystickPointerPos.x = e.clientX;
  19878. this._joystickPointerPos.y = e.clientY;
  19879. this._deltaJoystickVector = this._joystickPointerPos.clone();
  19880. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  19881. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  19882. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  19883. switch (this._axisTargetedByLeftAndRight) {
  19884. case 0 /* X */:
  19885. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  19886. break;
  19887. case 1 /* Y */:
  19888. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  19889. break;
  19890. case 2 /* Z */:
  19891. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  19892. break;
  19893. }
  19894. var directionUpDown = this.reverseUpDown ? 1 : -1;
  19895. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  19896. switch (this._axisTargetedByUpAndDown) {
  19897. case 0 /* X */:
  19898. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  19899. break;
  19900. case 1 /* Y */:
  19901. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  19902. break;
  19903. case 2 /* Z */:
  19904. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  19905. break;
  19906. }
  19907. }
  19908. else {
  19909. if (this._touches.item(e.pointerId.toString())) {
  19910. this._touches.item(e.pointerId.toString()).x = e.clientX;
  19911. this._touches.item(e.pointerId.toString()).y = e.clientY;
  19912. }
  19913. }
  19914. };
  19915. VirtualJoystick.prototype._onPointerUp = function (e) {
  19916. this._clearCanvas();
  19917. if (this._joystickPointerID == e.pointerId) {
  19918. this._joystickPointerID = -1;
  19919. this.pressed = false;
  19920. }
  19921. this._deltaJoystickVector.x = 0;
  19922. this._deltaJoystickVector.y = 0;
  19923. this._touches.remove(e.pointerId.toString());
  19924. };
  19925. /**
  19926. * Change the color of the virtual joystick
  19927. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  19928. */
  19929. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  19930. this._joystickColor = newColor;
  19931. };
  19932. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  19933. this._action = action;
  19934. };
  19935. // Define which axis you'd like to control for left & right
  19936. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  19937. switch (axis) {
  19938. case 0 /* X */:
  19939. case 1 /* Y */:
  19940. case 2 /* Z */:
  19941. this._axisTargetedByLeftAndRight = axis;
  19942. break;
  19943. default:
  19944. this._axisTargetedByLeftAndRight = 0 /* X */;
  19945. break;
  19946. }
  19947. };
  19948. // Define which axis you'd like to control for up & down
  19949. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  19950. switch (axis) {
  19951. case 0 /* X */:
  19952. case 1 /* Y */:
  19953. case 2 /* Z */:
  19954. this._axisTargetedByUpAndDown = axis;
  19955. break;
  19956. default:
  19957. this._axisTargetedByUpAndDown = 1 /* Y */;
  19958. break;
  19959. }
  19960. };
  19961. VirtualJoystick.prototype._clearCanvas = function () {
  19962. if (this._leftJoystick) {
  19963. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  19964. }
  19965. else {
  19966. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  19967. }
  19968. };
  19969. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  19970. var _this = this;
  19971. if (this.pressed) {
  19972. this._clearCanvas();
  19973. this._touches.forEach(function (touch) {
  19974. if (touch.pointerId === _this._joystickPointerID) {
  19975. VirtualJoystick.vjCanvasContext.beginPath();
  19976. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19977. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19978. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  19979. VirtualJoystick.vjCanvasContext.stroke();
  19980. VirtualJoystick.vjCanvasContext.beginPath();
  19981. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19982. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19983. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  19984. VirtualJoystick.vjCanvasContext.stroke();
  19985. VirtualJoystick.vjCanvasContext.beginPath();
  19986. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19987. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  19988. VirtualJoystick.vjCanvasContext.stroke();
  19989. }
  19990. else {
  19991. VirtualJoystick.vjCanvasContext.beginPath();
  19992. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  19993. VirtualJoystick.vjCanvasContext.beginPath();
  19994. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  19995. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19996. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  19997. VirtualJoystick.vjCanvasContext.stroke();
  19998. }
  19999. ;
  20000. });
  20001. }
  20002. requestAnimationFrame(function () {
  20003. _this._drawVirtualJoystick();
  20004. });
  20005. };
  20006. VirtualJoystick.prototype.releaseCanvas = function () {
  20007. if (VirtualJoystick.vjCanvas) {
  20008. document.body.removeChild(VirtualJoystick.vjCanvas);
  20009. VirtualJoystick.vjCanvas = null;
  20010. }
  20011. };
  20012. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  20013. VirtualJoystick._globalJoystickIndex = 0;
  20014. return VirtualJoystick;
  20015. })();
  20016. BABYLON.VirtualJoystick = VirtualJoystick;
  20017. })(BABYLON || (BABYLON = {}));
  20018. var BABYLON;
  20019. (function (BABYLON) {
  20020. var VirtualJoystick;
  20021. (function (VirtualJoystick) {
  20022. var Collection = (function () {
  20023. function Collection() {
  20024. this._count = 0;
  20025. this._collection = new Array();
  20026. }
  20027. Collection.prototype.Count = function () {
  20028. return this._count;
  20029. };
  20030. Collection.prototype.add = function (key, item) {
  20031. if (this._collection[key] != undefined) {
  20032. return undefined;
  20033. }
  20034. this._collection[key] = item;
  20035. return ++this._count;
  20036. };
  20037. Collection.prototype.remove = function (key) {
  20038. if (this._collection[key] == undefined) {
  20039. return undefined;
  20040. }
  20041. delete this._collection[key];
  20042. return --this._count;
  20043. };
  20044. Collection.prototype.item = function (key) {
  20045. return this._collection[key];
  20046. };
  20047. Collection.prototype.forEach = function (block) {
  20048. var key;
  20049. for (key in this._collection) {
  20050. if (this._collection.hasOwnProperty(key)) {
  20051. block(this._collection[key]);
  20052. }
  20053. }
  20054. };
  20055. return Collection;
  20056. })();
  20057. VirtualJoystick.Collection = Collection;
  20058. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20059. })(BABYLON || (BABYLON = {}));
  20060. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20061. var BABYLON;
  20062. (function (BABYLON) {
  20063. var OculusRiftDevKit2013_Metric = {
  20064. HResolution: 1280,
  20065. VResolution: 800,
  20066. HScreenSize: 0.149759993,
  20067. VScreenSize: 0.0935999975,
  20068. VScreenCenter: 0.0467999987,
  20069. EyeToScreenDistance: 0.0410000011,
  20070. LensSeparationDistance: 0.0635000020,
  20071. InterpupillaryDistance: 0.0640000030,
  20072. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20073. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20074. PostProcessScaleFactor: 1.714605507808412,
  20075. LensCenterOffset: 0.151976421
  20076. };
  20077. var _OculusInnerCamera = (function (_super) {
  20078. __extends(_OculusInnerCamera, _super);
  20079. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20080. _super.call(this, name, position, scene);
  20081. this._workMatrix = new BABYLON.Matrix();
  20082. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20083. // Constants
  20084. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20085. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20086. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20087. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20088. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20089. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20090. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20091. // Postprocess
  20092. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20093. }
  20094. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  20095. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20096. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20097. return this._projectionMatrix;
  20098. };
  20099. _OculusInnerCamera.prototype._getViewMatrix = function () {
  20100. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20101. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20102. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20103. // Computing target and final matrix
  20104. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20105. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20106. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20107. return this._viewMatrix;
  20108. };
  20109. return _OculusInnerCamera;
  20110. })(BABYLON.FreeCamera);
  20111. var OculusCamera = (function (_super) {
  20112. __extends(OculusCamera, _super);
  20113. function OculusCamera(name, position, scene) {
  20114. _super.call(this, name, position, scene);
  20115. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  20116. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  20117. this.subCameras.push(this._leftCamera);
  20118. this.subCameras.push(this._rightCamera);
  20119. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20120. }
  20121. OculusCamera.prototype._update = function () {
  20122. this._leftCamera.position.copyFrom(this.position);
  20123. this._rightCamera.position.copyFrom(this.position);
  20124. this._updateCamera(this._leftCamera);
  20125. this._updateCamera(this._rightCamera);
  20126. _super.prototype._update.call(this);
  20127. };
  20128. OculusCamera.prototype._updateCamera = function (camera) {
  20129. camera.minZ = this.minZ;
  20130. camera.maxZ = this.maxZ;
  20131. camera.rotation.x = this.rotation.x;
  20132. camera.rotation.y = this.rotation.y;
  20133. camera.rotation.z = this.rotation.z;
  20134. };
  20135. // Oculus events
  20136. OculusCamera.prototype._onOrientationEvent = function (evt) {
  20137. var yaw = evt.alpha / 180 * Math.PI;
  20138. var pitch = evt.beta / 180 * Math.PI;
  20139. var roll = evt.gamma / 180 * Math.PI;
  20140. if (!this._offsetOrientation) {
  20141. this._offsetOrientation = {
  20142. yaw: yaw,
  20143. pitch: pitch,
  20144. roll: roll
  20145. };
  20146. return;
  20147. }
  20148. else {
  20149. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20150. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20151. this.rotation.z += this._offsetOrientation.roll - roll;
  20152. this._offsetOrientation.yaw = yaw;
  20153. this._offsetOrientation.pitch = pitch;
  20154. this._offsetOrientation.roll = roll;
  20155. }
  20156. };
  20157. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  20158. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20159. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20160. };
  20161. OculusCamera.prototype.detachControl = function (element) {
  20162. _super.prototype.detachControl.call(this, element);
  20163. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20164. };
  20165. return OculusCamera;
  20166. })(BABYLON.FreeCamera);
  20167. BABYLON.OculusCamera = OculusCamera;
  20168. })(BABYLON || (BABYLON = {}));
  20169. //# sourceMappingURL=babylon.oculusCamera.js.map
  20170. var BABYLON;
  20171. (function (BABYLON) {
  20172. var OculusRiftDevKit2013_Metric = {
  20173. HResolution: 1280,
  20174. VResolution: 800,
  20175. HScreenSize: 0.149759993,
  20176. VScreenSize: 0.0935999975,
  20177. VScreenCenter: 0.0467999987,
  20178. EyeToScreenDistance: 0.0410000011,
  20179. LensSeparationDistance: 0.0635000020,
  20180. InterpupillaryDistance: 0.0640000030,
  20181. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20182. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20183. PostProcessScaleFactor: 1.714605507808412,
  20184. LensCenterOffset: 0.151976421
  20185. };
  20186. var _OculusInnerGamepadCamera = (function (_super) {
  20187. __extends(_OculusInnerGamepadCamera, _super);
  20188. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  20189. _super.call(this, name, position, scene);
  20190. this._workMatrix = new BABYLON.Matrix();
  20191. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20192. // Constants
  20193. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20194. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20195. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20196. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20197. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20198. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20199. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20200. // Postprocess
  20201. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20202. }
  20203. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  20204. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20205. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20206. return this._projectionMatrix;
  20207. };
  20208. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  20209. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20210. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20211. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20212. // Computing target and final matrix
  20213. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20214. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20215. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20216. return this._viewMatrix;
  20217. };
  20218. return _OculusInnerGamepadCamera;
  20219. })(BABYLON.FreeCamera);
  20220. var OculusGamepadCamera = (function (_super) {
  20221. __extends(OculusGamepadCamera, _super);
  20222. function OculusGamepadCamera(name, position, scene) {
  20223. var _this = this;
  20224. _super.call(this, name, position, scene);
  20225. this.angularSensibility = 200;
  20226. this.moveSensibility = 75;
  20227. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  20228. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  20229. this.subCameras.push(this._leftCamera);
  20230. this.subCameras.push(this._rightCamera);
  20231. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20232. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20233. _this._onNewGameConnected(gamepad);
  20234. });
  20235. }
  20236. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20237. // Only the first gamepad can control the camera
  20238. if (gamepad.index === 0) {
  20239. this._gamepad = gamepad;
  20240. }
  20241. };
  20242. OculusGamepadCamera.prototype._update = function () {
  20243. this._leftCamera.position.copyFrom(this.position);
  20244. this._rightCamera.position.copyFrom(this.position);
  20245. this._updateCamera(this._leftCamera);
  20246. this._updateCamera(this._rightCamera);
  20247. _super.prototype._update.call(this);
  20248. };
  20249. OculusGamepadCamera.prototype._checkInputs = function () {
  20250. if (!this._gamepad) {
  20251. return;
  20252. }
  20253. var LSValues = this._gamepad.leftStick;
  20254. var normalizedLX = LSValues.x / this.moveSensibility;
  20255. var normalizedLY = LSValues.y / this.moveSensibility;
  20256. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20257. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20258. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20259. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20260. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20261. };
  20262. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  20263. camera.minZ = this.minZ;
  20264. camera.maxZ = this.maxZ;
  20265. camera.rotation.x = this.rotation.x;
  20266. camera.rotation.y = this.rotation.y;
  20267. camera.rotation.z = this.rotation.z;
  20268. };
  20269. // Oculus events
  20270. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  20271. var yaw = evt.alpha / 180 * Math.PI;
  20272. var pitch = evt.beta / 180 * Math.PI;
  20273. var roll = evt.gamma / 180 * Math.PI;
  20274. if (!this._offsetOrientation) {
  20275. this._offsetOrientation = {
  20276. yaw: yaw,
  20277. pitch: pitch,
  20278. roll: roll
  20279. };
  20280. return;
  20281. }
  20282. else {
  20283. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20284. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20285. this.rotation.z += this._offsetOrientation.roll - roll;
  20286. this._offsetOrientation.yaw = yaw;
  20287. this._offsetOrientation.pitch = pitch;
  20288. this._offsetOrientation.roll = roll;
  20289. }
  20290. };
  20291. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  20292. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20293. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20294. };
  20295. OculusGamepadCamera.prototype.detachControl = function (element) {
  20296. _super.prototype.detachControl.call(this, element);
  20297. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20298. };
  20299. OculusGamepadCamera.prototype.dispose = function () {
  20300. this._gamepads.dispose();
  20301. _super.prototype.dispose.call(this);
  20302. };
  20303. return OculusGamepadCamera;
  20304. })(BABYLON.FreeCamera);
  20305. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  20306. })(BABYLON || (BABYLON = {}));
  20307. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  20308. var BABYLON;
  20309. (function (BABYLON) {
  20310. // We're mainly based on the logic defined into the FreeCamera code
  20311. var VirtualJoysticksCamera = (function (_super) {
  20312. __extends(VirtualJoysticksCamera, _super);
  20313. function VirtualJoysticksCamera(name, position, scene) {
  20314. _super.call(this, name, position, scene);
  20315. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  20316. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  20317. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  20318. this._leftjoystick.setJoystickSensibility(0.15);
  20319. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  20320. this._rightjoystick.setAxisForUpDown(0 /* X */);
  20321. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  20322. this._rightjoystick.reverseUpDown = true;
  20323. this._rightjoystick.setJoystickSensibility(0.05);
  20324. this._rightjoystick.setJoystickColor("yellow");
  20325. }
  20326. VirtualJoysticksCamera.prototype._checkInputs = function () {
  20327. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20328. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  20329. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20330. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  20331. if (!this._leftjoystick.pressed) {
  20332. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  20333. }
  20334. if (!this._rightjoystick.pressed) {
  20335. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  20336. }
  20337. };
  20338. VirtualJoysticksCamera.prototype.dispose = function () {
  20339. this._leftjoystick.releaseCanvas();
  20340. _super.prototype.dispose.call(this);
  20341. };
  20342. return VirtualJoysticksCamera;
  20343. })(BABYLON.FreeCamera);
  20344. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  20345. })(BABYLON || (BABYLON = {}));
  20346. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  20347. var BABYLON;
  20348. (function (BABYLON) {
  20349. var ShaderMaterial = (function (_super) {
  20350. __extends(ShaderMaterial, _super);
  20351. function ShaderMaterial(name, scene, shaderPath, options) {
  20352. _super.call(this, name, scene);
  20353. this._textures = new Array();
  20354. this._floats = new Array();
  20355. this._floatsArrays = {};
  20356. this._colors3 = new Array();
  20357. this._colors4 = new Array();
  20358. this._vectors2 = new Array();
  20359. this._vectors3 = new Array();
  20360. this._matrices = new Array();
  20361. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  20362. this._shaderPath = shaderPath;
  20363. options.needAlphaBlending = options.needAlphaBlending || false;
  20364. options.needAlphaTesting = options.needAlphaTesting || false;
  20365. options.attributes = options.attributes || ["position", "normal", "uv"];
  20366. options.uniforms = options.uniforms || ["worldViewProjection"];
  20367. options.samplers = options.samplers || [];
  20368. this._options = options;
  20369. }
  20370. ShaderMaterial.prototype.needAlphaBlending = function () {
  20371. return this._options.needAlphaBlending;
  20372. };
  20373. ShaderMaterial.prototype.needAlphaTesting = function () {
  20374. return this._options.needAlphaTesting;
  20375. };
  20376. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  20377. if (this._options.uniforms.indexOf(uniformName) === -1) {
  20378. this._options.uniforms.push(uniformName);
  20379. }
  20380. };
  20381. ShaderMaterial.prototype.setTexture = function (name, texture) {
  20382. if (this._options.samplers.indexOf(name) === -1) {
  20383. this._options.samplers.push(name);
  20384. }
  20385. this._textures[name] = texture;
  20386. return this;
  20387. };
  20388. ShaderMaterial.prototype.setFloat = function (name, value) {
  20389. this._checkUniform(name);
  20390. this._floats[name] = value;
  20391. return this;
  20392. };
  20393. ShaderMaterial.prototype.setFloats = function (name, value) {
  20394. this._checkUniform(name);
  20395. this._floatsArrays[name] = value;
  20396. return this;
  20397. };
  20398. ShaderMaterial.prototype.setColor3 = function (name, value) {
  20399. this._checkUniform(name);
  20400. this._colors3[name] = value;
  20401. return this;
  20402. };
  20403. ShaderMaterial.prototype.setColor4 = function (name, value) {
  20404. this._checkUniform(name);
  20405. this._colors4[name] = value;
  20406. return this;
  20407. };
  20408. ShaderMaterial.prototype.setVector2 = function (name, value) {
  20409. this._checkUniform(name);
  20410. this._vectors2[name] = value;
  20411. return this;
  20412. };
  20413. ShaderMaterial.prototype.setVector3 = function (name, value) {
  20414. this._checkUniform(name);
  20415. this._vectors3[name] = value;
  20416. return this;
  20417. };
  20418. ShaderMaterial.prototype.setMatrix = function (name, value) {
  20419. this._checkUniform(name);
  20420. this._matrices[name] = value;
  20421. return this;
  20422. };
  20423. ShaderMaterial.prototype.isReady = function () {
  20424. var scene = this.getScene();
  20425. var engine = scene.getEngine();
  20426. if (!this.checkReadyOnEveryCall) {
  20427. if (this._renderId === scene.getRenderId()) {
  20428. return true;
  20429. }
  20430. }
  20431. var previousEffect = this._effect;
  20432. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  20433. if (!this._effect.isReady()) {
  20434. return false;
  20435. }
  20436. if (previousEffect !== this._effect) {
  20437. scene.resetCachedMaterial();
  20438. }
  20439. this._renderId = scene.getRenderId();
  20440. return true;
  20441. };
  20442. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20443. var scene = this.getScene();
  20444. if (this._options.uniforms.indexOf("world") !== -1) {
  20445. this._effect.setMatrix("world", world);
  20446. }
  20447. if (this._options.uniforms.indexOf("worldView") !== -1) {
  20448. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  20449. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  20450. }
  20451. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  20452. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  20453. }
  20454. };
  20455. ShaderMaterial.prototype.bind = function (world) {
  20456. // Std values
  20457. this.bindOnlyWorldMatrix(world);
  20458. if (this.getScene().getCachedMaterial() !== this) {
  20459. if (this._options.uniforms.indexOf("view") !== -1) {
  20460. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  20461. }
  20462. if (this._options.uniforms.indexOf("projection") !== -1) {
  20463. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  20464. }
  20465. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  20466. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  20467. }
  20468. for (var name in this._textures) {
  20469. this._effect.setTexture(name, this._textures[name]);
  20470. }
  20471. for (name in this._floats) {
  20472. this._effect.setFloat(name, this._floats[name]);
  20473. }
  20474. for (name in this._floatsArrays) {
  20475. this._effect.setArray(name, this._floatsArrays[name]);
  20476. }
  20477. for (name in this._colors3) {
  20478. this._effect.setColor3(name, this._colors3[name]);
  20479. }
  20480. for (name in this._colors4) {
  20481. var color = this._colors4[name];
  20482. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  20483. }
  20484. for (name in this._vectors2) {
  20485. this._effect.setVector2(name, this._vectors2[name]);
  20486. }
  20487. for (name in this._vectors3) {
  20488. this._effect.setVector3(name, this._vectors3[name]);
  20489. }
  20490. for (name in this._matrices) {
  20491. this._effect.setMatrix(name, this._matrices[name]);
  20492. }
  20493. }
  20494. _super.prototype.bind.call(this, world, null);
  20495. };
  20496. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  20497. for (var name in this._textures) {
  20498. this._textures[name].dispose();
  20499. }
  20500. this._textures = [];
  20501. _super.prototype.dispose.call(this, forceDisposeEffect);
  20502. };
  20503. return ShaderMaterial;
  20504. })(BABYLON.Material);
  20505. BABYLON.ShaderMaterial = ShaderMaterial;
  20506. })(BABYLON || (BABYLON = {}));
  20507. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  20508. (function (BABYLON) {
  20509. var VertexData = (function () {
  20510. function VertexData() {
  20511. }
  20512. VertexData.prototype.set = function (data, kind) {
  20513. switch (kind) {
  20514. case BABYLON.VertexBuffer.PositionKind:
  20515. this.positions = data;
  20516. break;
  20517. case BABYLON.VertexBuffer.NormalKind:
  20518. this.normals = data;
  20519. break;
  20520. case BABYLON.VertexBuffer.UVKind:
  20521. this.uvs = data;
  20522. break;
  20523. case BABYLON.VertexBuffer.UV2Kind:
  20524. this.uv2s = data;
  20525. break;
  20526. case BABYLON.VertexBuffer.ColorKind:
  20527. this.colors = data;
  20528. break;
  20529. case BABYLON.VertexBuffer.MatricesIndicesKind:
  20530. this.matricesIndices = data;
  20531. break;
  20532. case BABYLON.VertexBuffer.MatricesWeightsKind:
  20533. this.matricesWeights = data;
  20534. break;
  20535. }
  20536. };
  20537. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  20538. this._applyTo(mesh, updatable);
  20539. };
  20540. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  20541. this._applyTo(geometry, updatable);
  20542. };
  20543. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  20544. this._update(mesh);
  20545. };
  20546. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  20547. this._update(geometry);
  20548. };
  20549. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  20550. if (this.positions) {
  20551. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  20552. }
  20553. if (this.normals) {
  20554. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  20555. }
  20556. if (this.uvs) {
  20557. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  20558. }
  20559. if (this.uv2s) {
  20560. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  20561. }
  20562. if (this.colors) {
  20563. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  20564. }
  20565. if (this.matricesIndices) {
  20566. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  20567. }
  20568. if (this.matricesWeights) {
  20569. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  20570. }
  20571. if (this.indices) {
  20572. meshOrGeometry.setIndices(this.indices);
  20573. }
  20574. };
  20575. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  20576. if (this.positions) {
  20577. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  20578. }
  20579. if (this.normals) {
  20580. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  20581. }
  20582. if (this.uvs) {
  20583. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  20584. }
  20585. if (this.uv2s) {
  20586. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  20587. }
  20588. if (this.colors) {
  20589. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  20590. }
  20591. if (this.matricesIndices) {
  20592. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  20593. }
  20594. if (this.matricesWeights) {
  20595. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  20596. }
  20597. if (this.indices) {
  20598. meshOrGeometry.setIndices(this.indices);
  20599. }
  20600. };
  20601. VertexData.prototype.transform = function (matrix) {
  20602. var transformed = BABYLON.Vector3.Zero();
  20603. if (this.positions) {
  20604. var position = BABYLON.Vector3.Zero();
  20605. for (var index = 0; index < this.positions.length; index += 3) {
  20606. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  20607. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  20608. this.positions[index] = transformed.x;
  20609. this.positions[index + 1] = transformed.y;
  20610. this.positions[index + 2] = transformed.z;
  20611. }
  20612. }
  20613. if (this.normals) {
  20614. var normal = BABYLON.Vector3.Zero();
  20615. for (index = 0; index < this.normals.length; index += 3) {
  20616. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  20617. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  20618. this.normals[index] = transformed.x;
  20619. this.normals[index + 1] = transformed.y;
  20620. this.normals[index + 2] = transformed.z;
  20621. }
  20622. }
  20623. };
  20624. VertexData.prototype.merge = function (other) {
  20625. if (other.indices) {
  20626. if (!this.indices) {
  20627. this.indices = [];
  20628. }
  20629. var offset = this.positions ? this.positions.length / 3 : 0;
  20630. for (var index = 0; index < other.indices.length; index++) {
  20631. this.indices.push(other.indices[index] + offset);
  20632. }
  20633. }
  20634. if (other.positions) {
  20635. if (!this.positions) {
  20636. this.positions = [];
  20637. }
  20638. for (index = 0; index < other.positions.length; index++) {
  20639. this.positions.push(other.positions[index]);
  20640. }
  20641. }
  20642. if (other.normals) {
  20643. if (!this.normals) {
  20644. this.normals = [];
  20645. }
  20646. for (index = 0; index < other.normals.length; index++) {
  20647. this.normals.push(other.normals[index]);
  20648. }
  20649. }
  20650. if (other.uvs) {
  20651. if (!this.uvs) {
  20652. this.uvs = [];
  20653. }
  20654. for (index = 0; index < other.uvs.length; index++) {
  20655. this.uvs.push(other.uvs[index]);
  20656. }
  20657. }
  20658. if (other.uv2s) {
  20659. if (!this.uv2s) {
  20660. this.uv2s = [];
  20661. }
  20662. for (index = 0; index < other.uv2s.length; index++) {
  20663. this.uv2s.push(other.uv2s[index]);
  20664. }
  20665. }
  20666. if (other.matricesIndices) {
  20667. if (!this.matricesIndices) {
  20668. this.matricesIndices = [];
  20669. }
  20670. for (index = 0; index < other.matricesIndices.length; index++) {
  20671. this.matricesIndices.push(other.matricesIndices[index]);
  20672. }
  20673. }
  20674. if (other.matricesWeights) {
  20675. if (!this.matricesWeights) {
  20676. this.matricesWeights = [];
  20677. }
  20678. for (index = 0; index < other.matricesWeights.length; index++) {
  20679. this.matricesWeights.push(other.matricesWeights[index]);
  20680. }
  20681. }
  20682. if (other.colors) {
  20683. if (!this.colors) {
  20684. this.colors = [];
  20685. }
  20686. for (index = 0; index < other.colors.length; index++) {
  20687. this.colors.push(other.colors[index]);
  20688. }
  20689. }
  20690. };
  20691. // Statics
  20692. VertexData.ExtractFromMesh = function (mesh) {
  20693. return VertexData._ExtractFrom(mesh);
  20694. };
  20695. VertexData.ExtractFromGeometry = function (geometry) {
  20696. return VertexData._ExtractFrom(geometry);
  20697. };
  20698. VertexData._ExtractFrom = function (meshOrGeometry) {
  20699. var result = new BABYLON.VertexData();
  20700. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20701. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20702. }
  20703. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20704. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20705. }
  20706. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20707. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20708. }
  20709. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20710. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  20711. }
  20712. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20713. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  20714. }
  20715. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20716. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20717. }
  20718. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20719. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20720. }
  20721. result.indices = meshOrGeometry.getIndices();
  20722. return result;
  20723. };
  20724. VertexData.CreateBox = function (size) {
  20725. var normalsSource = [
  20726. new BABYLON.Vector3(0, 0, 1),
  20727. new BABYLON.Vector3(0, 0, -1),
  20728. new BABYLON.Vector3(1, 0, 0),
  20729. new BABYLON.Vector3(-1, 0, 0),
  20730. new BABYLON.Vector3(0, 1, 0),
  20731. new BABYLON.Vector3(0, -1, 0)
  20732. ];
  20733. var indices = [];
  20734. var positions = [];
  20735. var normals = [];
  20736. var uvs = [];
  20737. size = size || 1;
  20738. for (var index = 0; index < normalsSource.length; index++) {
  20739. var normal = normalsSource[index];
  20740. // Get two vectors perpendicular to the face normal and to each other.
  20741. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  20742. var side2 = BABYLON.Vector3.Cross(normal, side1);
  20743. // Six indices (two triangles) per face.
  20744. var verticesLength = positions.length / 3;
  20745. indices.push(verticesLength);
  20746. indices.push(verticesLength + 1);
  20747. indices.push(verticesLength + 2);
  20748. indices.push(verticesLength);
  20749. indices.push(verticesLength + 2);
  20750. indices.push(verticesLength + 3);
  20751. // Four vertices per face.
  20752. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  20753. positions.push(vertex.x, vertex.y, vertex.z);
  20754. normals.push(normal.x, normal.y, normal.z);
  20755. uvs.push(1.0, 1.0);
  20756. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  20757. positions.push(vertex.x, vertex.y, vertex.z);
  20758. normals.push(normal.x, normal.y, normal.z);
  20759. uvs.push(0.0, 1.0);
  20760. vertex = normal.add(side1).add(side2).scale(size / 2);
  20761. positions.push(vertex.x, vertex.y, vertex.z);
  20762. normals.push(normal.x, normal.y, normal.z);
  20763. uvs.push(0.0, 0.0);
  20764. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  20765. positions.push(vertex.x, vertex.y, vertex.z);
  20766. normals.push(normal.x, normal.y, normal.z);
  20767. uvs.push(1.0, 0.0);
  20768. }
  20769. // Result
  20770. var vertexData = new BABYLON.VertexData();
  20771. vertexData.indices = indices;
  20772. vertexData.positions = positions;
  20773. vertexData.normals = normals;
  20774. vertexData.uvs = uvs;
  20775. return vertexData;
  20776. };
  20777. VertexData.CreateSphere = function (segments, diameter) {
  20778. segments = segments || 32;
  20779. diameter = diameter || 1;
  20780. var radius = diameter / 2;
  20781. var totalZRotationSteps = 2 + segments;
  20782. var totalYRotationSteps = 2 * totalZRotationSteps;
  20783. var indices = [];
  20784. var positions = [];
  20785. var normals = [];
  20786. var uvs = [];
  20787. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  20788. var normalizedZ = zRotationStep / totalZRotationSteps;
  20789. var angleZ = (normalizedZ * Math.PI);
  20790. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  20791. var normalizedY = yRotationStep / totalYRotationSteps;
  20792. var angleY = normalizedY * Math.PI * 2;
  20793. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  20794. var rotationY = BABYLON.Matrix.RotationY(angleY);
  20795. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  20796. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  20797. var vertex = complete.scale(radius);
  20798. var normal = BABYLON.Vector3.Normalize(vertex);
  20799. positions.push(vertex.x, vertex.y, vertex.z);
  20800. normals.push(normal.x, normal.y, normal.z);
  20801. uvs.push(normalizedZ, normalizedY);
  20802. }
  20803. if (zRotationStep > 0) {
  20804. var verticesCount = positions.length / 3;
  20805. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  20806. indices.push((firstIndex));
  20807. indices.push((firstIndex + 1));
  20808. indices.push(firstIndex + totalYRotationSteps + 1);
  20809. indices.push((firstIndex + totalYRotationSteps + 1));
  20810. indices.push((firstIndex + 1));
  20811. indices.push((firstIndex + totalYRotationSteps + 2));
  20812. }
  20813. }
  20814. }
  20815. // Result
  20816. var vertexData = new BABYLON.VertexData();
  20817. vertexData.indices = indices;
  20818. vertexData.positions = positions;
  20819. vertexData.normals = normals;
  20820. vertexData.uvs = uvs;
  20821. return vertexData;
  20822. };
  20823. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  20824. if (subdivisions === void 0) { subdivisions = 1; }
  20825. var radiusTop = diameterTop / 2;
  20826. var radiusBottom = diameterBottom / 2;
  20827. var indices = [];
  20828. var positions = [];
  20829. var normals = [];
  20830. var uvs = [];
  20831. height = height || 1;
  20832. diameterTop = diameterTop || 0.5;
  20833. diameterBottom = diameterBottom || 1;
  20834. tessellation = tessellation || 16;
  20835. subdivisions = subdivisions || 1;
  20836. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  20837. var getCircleVector = function (i) {
  20838. var angle = (i * 2.0 * Math.PI / tessellation);
  20839. var dx = Math.cos(angle);
  20840. var dz = Math.sin(angle);
  20841. return new BABYLON.Vector3(dx, 0, dz);
  20842. };
  20843. var createCylinderCap = function (isTop) {
  20844. var radius = isTop ? radiusTop : radiusBottom;
  20845. if (radius == 0) {
  20846. return;
  20847. }
  20848. var vbase = positions.length / 3;
  20849. var offset = new BABYLON.Vector3(0, height / 2, 0);
  20850. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  20851. if (!isTop) {
  20852. offset.scaleInPlace(-1);
  20853. textureScale.x = -textureScale.x;
  20854. }
  20855. for (i = 0; i < tessellation; i++) {
  20856. var circleVector = getCircleVector(i);
  20857. var position = circleVector.scale(radius).add(offset);
  20858. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  20859. positions.push(position.x, position.y, position.z);
  20860. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20861. }
  20862. for (var i = 0; i < tessellation - 2; i++) {
  20863. if (!isTop) {
  20864. indices.push(vbase);
  20865. indices.push(vbase + (i + 2) % tessellation);
  20866. indices.push(vbase + (i + 1) % tessellation);
  20867. }
  20868. else {
  20869. indices.push(vbase);
  20870. indices.push(vbase + (i + 1) % tessellation);
  20871. indices.push(vbase + (i + 2) % tessellation);
  20872. }
  20873. }
  20874. };
  20875. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  20876. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  20877. var stride = tessellation + 1;
  20878. for (var i = 0; i <= tessellation; i++) {
  20879. var circleVector = getCircleVector(i);
  20880. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  20881. var position, radius = radiusBottom;
  20882. for (var s = 0; s <= subdivisions; s++) {
  20883. // Update variables
  20884. position = circleVector.scale(radius);
  20885. position.addInPlace(base.add(offset.scale(s)));
  20886. textureCoordinate.y += 1 / subdivisions;
  20887. radius += (radiusTop - radiusBottom) / subdivisions;
  20888. // Push in arrays
  20889. positions.push(position.x, position.y, position.z);
  20890. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20891. }
  20892. }
  20893. subdivisions += 1;
  20894. for (var s = 0; s < subdivisions - 1; s++) {
  20895. for (var i = 0; i <= tessellation; i++) {
  20896. indices.push(i * subdivisions + s);
  20897. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20898. indices.push(i * subdivisions + (s + 1));
  20899. indices.push(i * subdivisions + (s + 1));
  20900. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20901. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  20902. }
  20903. }
  20904. // Create flat triangle fan caps to seal the top and bottom.
  20905. createCylinderCap(true);
  20906. createCylinderCap(false);
  20907. // Normals
  20908. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20909. // Result
  20910. var vertexData = new BABYLON.VertexData();
  20911. vertexData.indices = indices;
  20912. vertexData.positions = positions;
  20913. vertexData.normals = normals;
  20914. vertexData.uvs = uvs;
  20915. return vertexData;
  20916. };
  20917. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  20918. var indices = [];
  20919. var positions = [];
  20920. var normals = [];
  20921. var uvs = [];
  20922. diameter = diameter || 1;
  20923. thickness = thickness || 0.5;
  20924. tessellation = tessellation || 16;
  20925. var stride = tessellation + 1;
  20926. for (var i = 0; i <= tessellation; i++) {
  20927. var u = i / tessellation;
  20928. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  20929. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  20930. for (var j = 0; j <= tessellation; j++) {
  20931. var v = 1 - j / tessellation;
  20932. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  20933. var dx = Math.cos(innerAngle);
  20934. var dy = Math.sin(innerAngle);
  20935. // Create a vertex.
  20936. var normal = new BABYLON.Vector3(dx, dy, 0);
  20937. var position = normal.scale(thickness / 2);
  20938. var textureCoordinate = new BABYLON.Vector2(u, v);
  20939. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  20940. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  20941. positions.push(position.x, position.y, position.z);
  20942. normals.push(normal.x, normal.y, normal.z);
  20943. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20944. // And create indices for two triangles.
  20945. var nextI = (i + 1) % stride;
  20946. var nextJ = (j + 1) % stride;
  20947. indices.push(i * stride + j);
  20948. indices.push(i * stride + nextJ);
  20949. indices.push(nextI * stride + j);
  20950. indices.push(i * stride + nextJ);
  20951. indices.push(nextI * stride + nextJ);
  20952. indices.push(nextI * stride + j);
  20953. }
  20954. }
  20955. // Result
  20956. var vertexData = new BABYLON.VertexData();
  20957. vertexData.indices = indices;
  20958. vertexData.positions = positions;
  20959. vertexData.normals = normals;
  20960. vertexData.uvs = uvs;
  20961. return vertexData;
  20962. };
  20963. VertexData.CreateLines = function (points) {
  20964. var indices = [];
  20965. var positions = [];
  20966. for (var index = 0; index < points.length; index++) {
  20967. positions.push(points[index].x, points[index].y, points[index].z);
  20968. if (index > 0) {
  20969. indices.push(index - 1);
  20970. indices.push(index);
  20971. }
  20972. }
  20973. // Result
  20974. var vertexData = new BABYLON.VertexData();
  20975. vertexData.indices = indices;
  20976. vertexData.positions = positions;
  20977. return vertexData;
  20978. };
  20979. VertexData.CreateGround = function (width, height, subdivisions) {
  20980. var indices = [];
  20981. var positions = [];
  20982. var normals = [];
  20983. var uvs = [];
  20984. var row, col;
  20985. width = width || 1;
  20986. height = height || 1;
  20987. subdivisions = subdivisions || 1;
  20988. for (row = 0; row <= subdivisions; row++) {
  20989. for (col = 0; col <= subdivisions; col++) {
  20990. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  20991. var normal = new BABYLON.Vector3(0, 1.0, 0);
  20992. positions.push(position.x, position.y, position.z);
  20993. normals.push(normal.x, normal.y, normal.z);
  20994. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20995. }
  20996. }
  20997. for (row = 0; row < subdivisions; row++) {
  20998. for (col = 0; col < subdivisions; col++) {
  20999. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21000. indices.push(col + 1 + row * (subdivisions + 1));
  21001. indices.push(col + row * (subdivisions + 1));
  21002. indices.push(col + (row + 1) * (subdivisions + 1));
  21003. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21004. indices.push(col + row * (subdivisions + 1));
  21005. }
  21006. }
  21007. // Result
  21008. var vertexData = new BABYLON.VertexData();
  21009. vertexData.indices = indices;
  21010. vertexData.positions = positions;
  21011. vertexData.normals = normals;
  21012. vertexData.uvs = uvs;
  21013. return vertexData;
  21014. };
  21015. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  21016. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  21017. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  21018. var indices = [];
  21019. var positions = [];
  21020. var normals = [];
  21021. var uvs = [];
  21022. var row, col, tileRow, tileCol;
  21023. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  21024. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  21025. precision.w = (precision.w < 1) ? 1 : precision.w;
  21026. precision.h = (precision.h < 1) ? 1 : precision.h;
  21027. var tileSize = {
  21028. 'w': (xmax - xmin) / subdivisions.w,
  21029. 'h': (zmax - zmin) / subdivisions.h
  21030. };
  21031. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  21032. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  21033. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  21034. }
  21035. }
  21036. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  21037. // Indices
  21038. var base = positions.length / 3;
  21039. var rowLength = precision.w + 1;
  21040. for (row = 0; row < precision.h; row++) {
  21041. for (col = 0; col < precision.w; col++) {
  21042. var square = [
  21043. base + col + row * rowLength,
  21044. base + (col + 1) + row * rowLength,
  21045. base + (col + 1) + (row + 1) * rowLength,
  21046. base + col + (row + 1) * rowLength
  21047. ];
  21048. indices.push(square[1]);
  21049. indices.push(square[2]);
  21050. indices.push(square[3]);
  21051. indices.push(square[0]);
  21052. indices.push(square[1]);
  21053. indices.push(square[3]);
  21054. }
  21055. }
  21056. // Position, normals and uvs
  21057. var position = BABYLON.Vector3.Zero();
  21058. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21059. for (row = 0; row <= precision.h; row++) {
  21060. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  21061. for (col = 0; col <= precision.w; col++) {
  21062. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  21063. position.y = 0;
  21064. positions.push(position.x, position.y, position.z);
  21065. normals.push(normal.x, normal.y, normal.z);
  21066. uvs.push(col / precision.w, row / precision.h);
  21067. }
  21068. }
  21069. }
  21070. // Result
  21071. var vertexData = new BABYLON.VertexData();
  21072. vertexData.indices = indices;
  21073. vertexData.positions = positions;
  21074. vertexData.normals = normals;
  21075. vertexData.uvs = uvs;
  21076. return vertexData;
  21077. };
  21078. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  21079. var indices = [];
  21080. var positions = [];
  21081. var normals = [];
  21082. var uvs = [];
  21083. var row, col;
  21084. for (row = 0; row <= subdivisions; row++) {
  21085. for (col = 0; col <= subdivisions; col++) {
  21086. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21087. // Compute height
  21088. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  21089. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  21090. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  21091. var r = buffer[pos] / 255.0;
  21092. var g = buffer[pos + 1] / 255.0;
  21093. var b = buffer[pos + 2] / 255.0;
  21094. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21095. position.y = minHeight + (maxHeight - minHeight) * gradient;
  21096. // Add vertex
  21097. positions.push(position.x, position.y, position.z);
  21098. normals.push(0, 0, 0);
  21099. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21100. }
  21101. }
  21102. for (row = 0; row < subdivisions; row++) {
  21103. for (col = 0; col < subdivisions; col++) {
  21104. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21105. indices.push(col + 1 + row * (subdivisions + 1));
  21106. indices.push(col + row * (subdivisions + 1));
  21107. indices.push(col + (row + 1) * (subdivisions + 1));
  21108. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21109. indices.push(col + row * (subdivisions + 1));
  21110. }
  21111. }
  21112. // Normals
  21113. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21114. // Result
  21115. var vertexData = new BABYLON.VertexData();
  21116. vertexData.indices = indices;
  21117. vertexData.positions = positions;
  21118. vertexData.normals = normals;
  21119. vertexData.uvs = uvs;
  21120. return vertexData;
  21121. };
  21122. VertexData.CreatePlane = function (size) {
  21123. var indices = [];
  21124. var positions = [];
  21125. var normals = [];
  21126. var uvs = [];
  21127. size = size || 1;
  21128. // Vertices
  21129. var halfSize = size / 2.0;
  21130. positions.push(-halfSize, -halfSize, 0);
  21131. normals.push(0, 0, -1.0);
  21132. uvs.push(0.0, 0.0);
  21133. positions.push(halfSize, -halfSize, 0);
  21134. normals.push(0, 0, -1.0);
  21135. uvs.push(1.0, 0.0);
  21136. positions.push(halfSize, halfSize, 0);
  21137. normals.push(0, 0, -1.0);
  21138. uvs.push(1.0, 1.0);
  21139. positions.push(-halfSize, halfSize, 0);
  21140. normals.push(0, 0, -1.0);
  21141. uvs.push(0.0, 1.0);
  21142. // Indices
  21143. indices.push(0);
  21144. indices.push(1);
  21145. indices.push(2);
  21146. indices.push(0);
  21147. indices.push(2);
  21148. indices.push(3);
  21149. // Result
  21150. var vertexData = new BABYLON.VertexData();
  21151. vertexData.indices = indices;
  21152. vertexData.positions = positions;
  21153. vertexData.normals = normals;
  21154. vertexData.uvs = uvs;
  21155. return vertexData;
  21156. };
  21157. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  21158. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  21159. var indices = [];
  21160. var positions = [];
  21161. var normals = [];
  21162. var uvs = [];
  21163. radius = radius || 2;
  21164. tube = tube || 0.5;
  21165. radialSegments = radialSegments || 32;
  21166. tubularSegments = tubularSegments || 32;
  21167. p = p || 2;
  21168. q = q || 3;
  21169. // Helper
  21170. var getPos = function (angle) {
  21171. var cu = Math.cos(angle);
  21172. var su = Math.sin(angle);
  21173. var quOverP = q / p * angle;
  21174. var cs = Math.cos(quOverP);
  21175. var tx = radius * (2 + cs) * 0.5 * cu;
  21176. var ty = radius * (2 + cs) * su * 0.5;
  21177. var tz = radius * Math.sin(quOverP) * 0.5;
  21178. return new BABYLON.Vector3(tx, ty, tz);
  21179. };
  21180. for (var i = 0; i <= radialSegments; i++) {
  21181. var modI = i % radialSegments;
  21182. var u = modI / radialSegments * 2 * p * Math.PI;
  21183. var p1 = getPos(u);
  21184. var p2 = getPos(u + 0.01);
  21185. var tang = p2.subtract(p1);
  21186. var n = p2.add(p1);
  21187. var bitan = BABYLON.Vector3.Cross(tang, n);
  21188. n = BABYLON.Vector3.Cross(bitan, tang);
  21189. bitan.normalize();
  21190. n.normalize();
  21191. for (var j = 0; j < tubularSegments; j++) {
  21192. var modJ = j % tubularSegments;
  21193. var v = modJ / tubularSegments * 2 * Math.PI;
  21194. var cx = -tube * Math.cos(v);
  21195. var cy = tube * Math.sin(v);
  21196. positions.push(p1.x + cx * n.x + cy * bitan.x);
  21197. positions.push(p1.y + cx * n.y + cy * bitan.y);
  21198. positions.push(p1.z + cx * n.z + cy * bitan.z);
  21199. uvs.push(i / radialSegments);
  21200. uvs.push(j / tubularSegments);
  21201. }
  21202. }
  21203. for (i = 0; i < radialSegments; i++) {
  21204. for (j = 0; j < tubularSegments; j++) {
  21205. var jNext = (j + 1) % tubularSegments;
  21206. var a = i * tubularSegments + j;
  21207. var b = (i + 1) * tubularSegments + j;
  21208. var c = (i + 1) * tubularSegments + jNext;
  21209. var d = i * tubularSegments + jNext;
  21210. indices.push(d);
  21211. indices.push(b);
  21212. indices.push(a);
  21213. indices.push(d);
  21214. indices.push(c);
  21215. indices.push(b);
  21216. }
  21217. }
  21218. // Normals
  21219. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21220. // Result
  21221. var vertexData = new BABYLON.VertexData();
  21222. vertexData.indices = indices;
  21223. vertexData.positions = positions;
  21224. vertexData.normals = normals;
  21225. vertexData.uvs = uvs;
  21226. return vertexData;
  21227. };
  21228. // Tools
  21229. VertexData.ComputeNormals = function (positions, indices, normals) {
  21230. var positionVectors = [];
  21231. var facesOfVertices = [];
  21232. var index;
  21233. for (index = 0; index < positions.length; index += 3) {
  21234. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  21235. positionVectors.push(vector3);
  21236. facesOfVertices.push([]);
  21237. }
  21238. // Compute normals
  21239. var facesNormals = [];
  21240. for (index = 0; index < indices.length / 3; index++) {
  21241. var i1 = indices[index * 3];
  21242. var i2 = indices[index * 3 + 1];
  21243. var i3 = indices[index * 3 + 2];
  21244. var p1 = positionVectors[i1];
  21245. var p2 = positionVectors[i2];
  21246. var p3 = positionVectors[i3];
  21247. var p1p2 = p1.subtract(p2);
  21248. var p3p2 = p3.subtract(p2);
  21249. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21250. facesOfVertices[i1].push(index);
  21251. facesOfVertices[i2].push(index);
  21252. facesOfVertices[i3].push(index);
  21253. }
  21254. for (index = 0; index < positionVectors.length; index++) {
  21255. var faces = facesOfVertices[index];
  21256. var normal = BABYLON.Vector3.Zero();
  21257. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  21258. normal.addInPlace(facesNormals[faces[faceIndex]]);
  21259. }
  21260. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  21261. normals[index * 3] = normal.x;
  21262. normals[index * 3 + 1] = normal.y;
  21263. normals[index * 3 + 2] = normal.z;
  21264. }
  21265. };
  21266. return VertexData;
  21267. })();
  21268. BABYLON.VertexData = VertexData;
  21269. })(BABYLON || (BABYLON = {}));
  21270. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  21271. var BABYLON;
  21272. (function (BABYLON) {
  21273. var buildCamera = function (that, name) {
  21274. that._leftCamera.isIntermediate = true;
  21275. that.subCameras.push(that._leftCamera);
  21276. that.subCameras.push(that._rightCamera);
  21277. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  21278. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  21279. that._anaglyphPostProcess.onApply = function (effect) {
  21280. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  21281. };
  21282. that._update();
  21283. };
  21284. var AnaglyphArcRotateCamera = (function (_super) {
  21285. __extends(AnaglyphArcRotateCamera, _super);
  21286. // ANY
  21287. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  21288. _super.call(this, name, alpha, beta, radius, target, scene);
  21289. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21290. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  21291. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  21292. buildCamera(this, name);
  21293. }
  21294. AnaglyphArcRotateCamera.prototype._update = function () {
  21295. this._updateCamera(this._leftCamera);
  21296. this._updateCamera(this._rightCamera);
  21297. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  21298. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  21299. _super.prototype._update.call(this);
  21300. };
  21301. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  21302. camera.beta = this.beta;
  21303. camera.radius = this.radius;
  21304. camera.minZ = this.minZ;
  21305. camera.maxZ = this.maxZ;
  21306. camera.fov = this.fov;
  21307. camera.target = this.target;
  21308. };
  21309. return AnaglyphArcRotateCamera;
  21310. })(BABYLON.ArcRotateCamera);
  21311. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  21312. var AnaglyphFreeCamera = (function (_super) {
  21313. __extends(AnaglyphFreeCamera, _super);
  21314. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  21315. _super.call(this, name, position, scene);
  21316. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21317. this._transformMatrix = new BABYLON.Matrix();
  21318. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  21319. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  21320. buildCamera(this, name);
  21321. }
  21322. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  21323. var target = this.getTarget();
  21324. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  21325. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  21326. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  21327. };
  21328. AnaglyphFreeCamera.prototype._update = function () {
  21329. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  21330. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  21331. this._updateCamera(this._leftCamera);
  21332. this._updateCamera(this._rightCamera);
  21333. _super.prototype._update.call(this);
  21334. };
  21335. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  21336. camera.minZ = this.minZ;
  21337. camera.maxZ = this.maxZ;
  21338. camera.fov = this.fov;
  21339. camera.viewport = this.viewport;
  21340. camera.setTarget(this.getTarget());
  21341. };
  21342. return AnaglyphFreeCamera;
  21343. })(BABYLON.FreeCamera);
  21344. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  21345. })(BABYLON || (BABYLON = {}));
  21346. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  21347. var BABYLON;
  21348. (function (BABYLON) {
  21349. var AnaglyphPostProcess = (function (_super) {
  21350. __extends(AnaglyphPostProcess, _super);
  21351. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21352. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  21353. }
  21354. return AnaglyphPostProcess;
  21355. })(BABYLON.PostProcess);
  21356. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  21357. })(BABYLON || (BABYLON = {}));
  21358. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  21359. (function (BABYLON) {
  21360. var Tags = (function () {
  21361. function Tags() {
  21362. }
  21363. Tags.EnableFor = function (obj) {
  21364. obj._tags = obj._tags || {};
  21365. obj.hasTags = function () {
  21366. return Tags.HasTags(obj);
  21367. };
  21368. obj.addTags = function (tagsString) {
  21369. return Tags.AddTagsTo(obj, tagsString);
  21370. };
  21371. obj.removeTags = function (tagsString) {
  21372. return Tags.RemoveTagsFrom(obj, tagsString);
  21373. };
  21374. obj.matchesTagsQuery = function (tagsQuery) {
  21375. return Tags.MatchesQuery(obj, tagsQuery);
  21376. };
  21377. };
  21378. Tags.DisableFor = function (obj) {
  21379. delete obj._tags;
  21380. delete obj.hasTags;
  21381. delete obj.addTags;
  21382. delete obj.removeTags;
  21383. delete obj.matchesTagsQuery;
  21384. };
  21385. Tags.HasTags = function (obj) {
  21386. if (!obj._tags) {
  21387. return false;
  21388. }
  21389. return !BABYLON.Tools.IsEmpty(obj._tags);
  21390. };
  21391. Tags.GetTags = function (obj) {
  21392. if (!obj._tags) {
  21393. return null;
  21394. }
  21395. return obj._tags;
  21396. };
  21397. // the tags 'true' and 'false' are reserved and cannot be used as tags
  21398. // a tag cannot start with '||', '&&', and '!'
  21399. // it cannot contain whitespaces
  21400. Tags.AddTagsTo = function (obj, tagsString) {
  21401. if (!tagsString) {
  21402. return;
  21403. }
  21404. var tags = tagsString.split(" ");
  21405. for (var t in tags) {
  21406. Tags._AddTagTo(obj, tags[t]);
  21407. }
  21408. };
  21409. Tags._AddTagTo = function (obj, tag) {
  21410. tag = tag.trim();
  21411. if (tag === "" || tag === "true" || tag === "false") {
  21412. return;
  21413. }
  21414. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  21415. return;
  21416. }
  21417. Tags.EnableFor(obj);
  21418. obj._tags[tag] = true;
  21419. };
  21420. Tags.RemoveTagsFrom = function (obj, tagsString) {
  21421. if (!Tags.HasTags(obj)) {
  21422. return;
  21423. }
  21424. var tags = tagsString.split(" ");
  21425. for (var t in tags) {
  21426. Tags._RemoveTagFrom(obj, tags[t]);
  21427. }
  21428. };
  21429. Tags._RemoveTagFrom = function (obj, tag) {
  21430. delete obj._tags[tag];
  21431. };
  21432. Tags.MatchesQuery = function (obj, tagsQuery) {
  21433. if (tagsQuery === undefined) {
  21434. return true;
  21435. }
  21436. if (tagsQuery === "") {
  21437. return Tags.HasTags(obj);
  21438. }
  21439. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  21440. };
  21441. return Tags;
  21442. })();
  21443. BABYLON.Tags = Tags;
  21444. })(BABYLON || (BABYLON = {}));
  21445. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  21446. (function (BABYLON) {
  21447. var Internals;
  21448. (function (Internals) {
  21449. var AndOrNotEvaluator = (function () {
  21450. function AndOrNotEvaluator() {
  21451. }
  21452. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  21453. if (!query.match(/\([^\(\)]*\)/g)) {
  21454. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  21455. }
  21456. else {
  21457. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  21458. // remove parenthesis
  21459. r = r.slice(1, r.length - 1);
  21460. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  21461. });
  21462. }
  21463. if (query === "true") {
  21464. return true;
  21465. }
  21466. if (query === "false") {
  21467. return false;
  21468. }
  21469. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  21470. };
  21471. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  21472. evaluateCallback = evaluateCallback || (function (r) {
  21473. return r === "true" ? true : false;
  21474. });
  21475. var result;
  21476. var or = parenthesisContent.split("||");
  21477. for (var i in or) {
  21478. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  21479. var and = ori.split("&&");
  21480. if (and.length > 1) {
  21481. for (var j = 0; j < and.length; ++j) {
  21482. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  21483. if (andj !== "true" && andj !== "false") {
  21484. if (andj[0] === "!") {
  21485. result = !evaluateCallback(andj.substring(1));
  21486. }
  21487. else {
  21488. result = evaluateCallback(andj);
  21489. }
  21490. }
  21491. else {
  21492. result = andj === "true" ? true : false;
  21493. }
  21494. if (!result) {
  21495. ori = "false";
  21496. break;
  21497. }
  21498. }
  21499. }
  21500. if (result || ori === "true") {
  21501. result = true;
  21502. break;
  21503. }
  21504. // result equals false (or undefined)
  21505. if (ori !== "true" && ori !== "false") {
  21506. if (ori[0] === "!") {
  21507. result = !evaluateCallback(ori.substring(1));
  21508. }
  21509. else {
  21510. result = evaluateCallback(ori);
  21511. }
  21512. }
  21513. else {
  21514. result = ori === "true" ? true : false;
  21515. }
  21516. }
  21517. // the whole parenthesis scope is replaced by 'true' or 'false'
  21518. return result ? "true" : "false";
  21519. };
  21520. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  21521. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  21522. // remove whitespaces
  21523. r = r.replace(/[\s]/g, function () { return ""; });
  21524. return r.length % 2 ? "!" : "";
  21525. });
  21526. booleanString = booleanString.trim();
  21527. if (booleanString === "!true") {
  21528. booleanString = "false";
  21529. }
  21530. else if (booleanString === "!false") {
  21531. booleanString = "true";
  21532. }
  21533. return booleanString;
  21534. };
  21535. return AndOrNotEvaluator;
  21536. })();
  21537. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  21538. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21539. })(BABYLON || (BABYLON = {}));
  21540. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  21541. (function (BABYLON) {
  21542. var PostProcessRenderPass = (function () {
  21543. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  21544. this._enabled = true;
  21545. this._refCount = 0;
  21546. this._name = name;
  21547. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  21548. this.setRenderList(renderList);
  21549. this._renderTexture.onBeforeRender = beforeRender;
  21550. this._renderTexture.onAfterRender = afterRender;
  21551. this._scene = scene;
  21552. this._renderList = renderList;
  21553. }
  21554. // private
  21555. PostProcessRenderPass.prototype._incRefCount = function () {
  21556. if (this._refCount === 0) {
  21557. this._scene.customRenderTargets.push(this._renderTexture);
  21558. }
  21559. return ++this._refCount;
  21560. };
  21561. PostProcessRenderPass.prototype._decRefCount = function () {
  21562. this._refCount--;
  21563. if (this._refCount <= 0) {
  21564. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  21565. }
  21566. return this._refCount;
  21567. };
  21568. PostProcessRenderPass.prototype._update = function () {
  21569. this.setRenderList(this._renderList);
  21570. };
  21571. // public
  21572. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  21573. this._renderTexture.renderList = renderList;
  21574. };
  21575. PostProcessRenderPass.prototype.getRenderTexture = function () {
  21576. return this._renderTexture;
  21577. };
  21578. return PostProcessRenderPass;
  21579. })();
  21580. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  21581. })(BABYLON || (BABYLON = {}));
  21582. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  21583. (function (BABYLON) {
  21584. var PostProcessRenderEffect = (function () {
  21585. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  21586. this._engine = engine;
  21587. this._name = name;
  21588. this._singleInstance = singleInstance || true;
  21589. this._getPostProcess = getPostProcess;
  21590. this._cameras = [];
  21591. this._indicesForCamera = [];
  21592. this._postProcesses = {};
  21593. this._renderPasses = {};
  21594. this._renderEffectAsPasses = {};
  21595. }
  21596. PostProcessRenderEffect.prototype._update = function () {
  21597. for (var renderPassName in this._renderPasses) {
  21598. this._renderPasses[renderPassName]._update();
  21599. }
  21600. };
  21601. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  21602. this._renderPasses[renderPass._name] = renderPass;
  21603. this._linkParameters();
  21604. };
  21605. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  21606. delete this._renderPasses[renderPass._name];
  21607. this._linkParameters();
  21608. };
  21609. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  21610. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  21611. this._linkParameters();
  21612. };
  21613. PostProcessRenderEffect.prototype.getPass = function (passName) {
  21614. for (var renderPassName in this._renderPasses) {
  21615. if (renderPassName === passName) {
  21616. return this._renderPasses[passName];
  21617. }
  21618. }
  21619. };
  21620. PostProcessRenderEffect.prototype.emptyPasses = function () {
  21621. this._renderPasses = {};
  21622. this._linkParameters();
  21623. };
  21624. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  21625. var cameraKey;
  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. if (this._singleInstance) {
  21631. cameraKey = 0;
  21632. }
  21633. else {
  21634. cameraKey = cameraName;
  21635. }
  21636. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  21637. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  21638. if (!this._indicesForCamera[cameraName]) {
  21639. this._indicesForCamera[cameraName] = [];
  21640. }
  21641. this._indicesForCamera[cameraName].push(index);
  21642. if (this._cameras.indexOf(camera) === -1) {
  21643. this._cameras[cameraName] = camera;
  21644. }
  21645. for (var passName in this._renderPasses) {
  21646. this._renderPasses[passName]._incRefCount();
  21647. }
  21648. }
  21649. this._linkParameters();
  21650. };
  21651. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  21652. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21653. for (var i = 0; i < _cam.length; i++) {
  21654. var camera = _cam[i];
  21655. var cameraName = camera.name;
  21656. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21657. var index = this._cameras.indexOf(cameraName);
  21658. this._indicesForCamera.splice(index, 1);
  21659. this._cameras.splice(index, 1);
  21660. for (var passName in this._renderPasses) {
  21661. this._renderPasses[passName]._decRefCount();
  21662. }
  21663. }
  21664. };
  21665. PostProcessRenderEffect.prototype._enable = function (cameras) {
  21666. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21667. for (var i = 0; i < _cam.length; i++) {
  21668. var camera = _cam[i];
  21669. var cameraName = camera.name;
  21670. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  21671. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  21672. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  21673. }
  21674. }
  21675. for (var passName in this._renderPasses) {
  21676. this._renderPasses[passName]._incRefCount();
  21677. }
  21678. }
  21679. };
  21680. PostProcessRenderEffect.prototype._disable = function (cameras) {
  21681. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21682. for (var i = 0; i < _cam.length; i++) {
  21683. var camera = _cam[i];
  21684. var cameraName = camera.Name;
  21685. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21686. for (var passName in this._renderPasses) {
  21687. this._renderPasses[passName]._decRefCount();
  21688. }
  21689. }
  21690. };
  21691. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  21692. if (this._singleInstance) {
  21693. return this._postProcesses[0];
  21694. }
  21695. else {
  21696. return this._postProcesses[camera.name];
  21697. }
  21698. };
  21699. PostProcessRenderEffect.prototype._linkParameters = function () {
  21700. var _this = this;
  21701. for (var index in this._postProcesses) {
  21702. if (this.applyParameters) {
  21703. this.applyParameters(this._postProcesses[index]);
  21704. }
  21705. this._postProcesses[index].onBeforeRender = function (effect) {
  21706. _this._linkTextures(effect);
  21707. };
  21708. }
  21709. };
  21710. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  21711. for (var renderPassName in this._renderPasses) {
  21712. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  21713. }
  21714. for (var renderEffectName in this._renderEffectAsPasses) {
  21715. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  21716. }
  21717. };
  21718. return PostProcessRenderEffect;
  21719. })();
  21720. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  21721. })(BABYLON || (BABYLON = {}));
  21722. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  21723. (function (BABYLON) {
  21724. var PostProcessRenderPipeline = (function () {
  21725. function PostProcessRenderPipeline(engine, name) {
  21726. this._engine = engine;
  21727. this._name = name;
  21728. this._renderEffects = {};
  21729. this._renderEffectsForIsolatedPass = {};
  21730. this._cameras = [];
  21731. }
  21732. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  21733. this._renderEffects[renderEffect._name] = renderEffect;
  21734. };
  21735. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  21736. var renderEffects = this._renderEffects[renderEffectName];
  21737. if (!renderEffects) {
  21738. return;
  21739. }
  21740. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21741. };
  21742. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  21743. var renderEffects = this._renderEffects[renderEffectName];
  21744. if (!renderEffects) {
  21745. return;
  21746. }
  21747. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21748. };
  21749. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  21750. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21751. var indicesToDelete = [];
  21752. for (var i = 0; i < _cam.length; i++) {
  21753. var camera = _cam[i];
  21754. var cameraName = camera.name;
  21755. if (this._cameras.indexOf(camera) === -1) {
  21756. this._cameras[cameraName] = camera;
  21757. }
  21758. else if (unique) {
  21759. indicesToDelete.push(i);
  21760. }
  21761. }
  21762. for (var i = 0; i < indicesToDelete.length; i++) {
  21763. cameras.splice(indicesToDelete[i], 1);
  21764. }
  21765. for (var renderEffectName in this._renderEffects) {
  21766. this._renderEffects[renderEffectName]._attachCameras(_cam);
  21767. }
  21768. };
  21769. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  21770. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21771. for (var renderEffectName in this._renderEffects) {
  21772. this._renderEffects[renderEffectName]._detachCameras(_cam);
  21773. }
  21774. for (var i = 0; i < _cam.length; i++) {
  21775. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  21776. }
  21777. };
  21778. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  21779. var _this = this;
  21780. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21781. var pass = null;
  21782. for (var renderEffectName in this._renderEffects) {
  21783. pass = this._renderEffects[renderEffectName].getPass(passName);
  21784. if (pass != null) {
  21785. break;
  21786. }
  21787. }
  21788. if (pass === null) {
  21789. return;
  21790. }
  21791. for (var renderEffectName in this._renderEffects) {
  21792. this._renderEffects[renderEffectName]._disable(_cam);
  21793. }
  21794. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  21795. for (var i = 0; i < _cam.length; i++) {
  21796. var camera = _cam[i];
  21797. var cameraName = camera.name;
  21798. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21799. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21800. });
  21801. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  21802. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  21803. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  21804. }
  21805. };
  21806. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  21807. var _this = this;
  21808. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21809. for (var i = 0; i < _cam.length; i++) {
  21810. var camera = _cam[i];
  21811. var cameraName = camera.name;
  21812. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21813. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21814. });
  21815. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  21816. }
  21817. for (var renderEffectName in this._renderEffects) {
  21818. this._renderEffects[renderEffectName]._enable(_cam);
  21819. }
  21820. };
  21821. PostProcessRenderPipeline.prototype._update = function () {
  21822. for (var renderEffectName in this._renderEffects) {
  21823. this._renderEffects[renderEffectName]._update();
  21824. }
  21825. for (var i = 0; i < this._cameras.length; i++) {
  21826. var cameraName = this._cameras[i].name;
  21827. if (this._renderEffectsForIsolatedPass[cameraName]) {
  21828. this._renderEffectsForIsolatedPass[cameraName]._update();
  21829. }
  21830. }
  21831. };
  21832. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  21833. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  21834. return PostProcessRenderPipeline;
  21835. })();
  21836. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  21837. })(BABYLON || (BABYLON = {}));
  21838. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  21839. (function (BABYLON) {
  21840. var PostProcessRenderPipelineManager = (function () {
  21841. function PostProcessRenderPipelineManager() {
  21842. this._renderPipelines = {};
  21843. }
  21844. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  21845. this._renderPipelines[renderPipeline._name] = renderPipeline;
  21846. };
  21847. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  21848. var renderPipeline = this._renderPipelines[renderPipelineName];
  21849. if (!renderPipeline) {
  21850. return;
  21851. }
  21852. renderPipeline._attachCameras(cameras, unique);
  21853. };
  21854. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  21855. var renderPipeline = this._renderPipelines[renderPipelineName];
  21856. if (!renderPipeline) {
  21857. return;
  21858. }
  21859. renderPipeline._detachCameras(cameras);
  21860. };
  21861. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21862. var renderPipeline = this._renderPipelines[renderPipelineName];
  21863. if (!renderPipeline) {
  21864. return;
  21865. }
  21866. renderPipeline._enableEffect(renderEffectName, cameras);
  21867. };
  21868. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21869. var renderPipeline = this._renderPipelines[renderPipelineName];
  21870. if (!renderPipeline) {
  21871. return;
  21872. }
  21873. renderPipeline._disableEffect(renderEffectName, cameras);
  21874. };
  21875. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  21876. var renderPipeline = this._renderPipelines[renderPipelineName];
  21877. if (!renderPipeline) {
  21878. return;
  21879. }
  21880. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  21881. };
  21882. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  21883. var renderPipeline = this._renderPipelines[renderPipelineName];
  21884. if (!renderPipeline) {
  21885. return;
  21886. }
  21887. renderPipeline._disableDisplayOnlyPass(cameras);
  21888. };
  21889. PostProcessRenderPipelineManager.prototype.update = function () {
  21890. for (var renderPipelineName in this._renderPipelines) {
  21891. this._renderPipelines[renderPipelineName]._update();
  21892. }
  21893. };
  21894. return PostProcessRenderPipelineManager;
  21895. })();
  21896. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  21897. })(BABYLON || (BABYLON = {}));
  21898. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  21899. var BABYLON;
  21900. (function (BABYLON) {
  21901. var DisplayPassPostProcess = (function (_super) {
  21902. __extends(DisplayPassPostProcess, _super);
  21903. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21904. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  21905. }
  21906. return DisplayPassPostProcess;
  21907. })(BABYLON.PostProcess);
  21908. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  21909. })(BABYLON || (BABYLON = {}));
  21910. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  21911. (function (BABYLON) {
  21912. var BoundingBoxRenderer = (function () {
  21913. function BoundingBoxRenderer(scene) {
  21914. this.frontColor = new BABYLON.Color3(1, 1, 1);
  21915. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  21916. this.showBackLines = true;
  21917. this.renderList = new BABYLON.SmartArray(32);
  21918. this._scene = scene;
  21919. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  21920. attributes: ["position"],
  21921. uniforms: ["worldViewProjection", "color"]
  21922. });
  21923. var engine = this._scene.getEngine();
  21924. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  21925. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  21926. 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]);
  21927. }
  21928. BoundingBoxRenderer.prototype.reset = function () {
  21929. this.renderList.reset();
  21930. };
  21931. BoundingBoxRenderer.prototype.render = function () {
  21932. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  21933. return;
  21934. }
  21935. var engine = this._scene.getEngine();
  21936. engine.setDepthWrite(false);
  21937. this._colorShader._preBind();
  21938. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  21939. var boundingBox = this.renderList.data[boundingBoxIndex];
  21940. var min = boundingBox.minimum;
  21941. var max = boundingBox.maximum;
  21942. var diff = max.subtract(min);
  21943. var median = min.add(diff.scale(0.5));
  21944. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  21945. // VBOs
  21946. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  21947. if (this.showBackLines) {
  21948. // Back
  21949. engine.setDepthFunctionToGreaterOrEqual();
  21950. this._scene.resetCachedMaterial();
  21951. this._colorShader.setColor4("color", this.backColor.toColor4());
  21952. this._colorShader.bind(worldMatrix);
  21953. // Draw order
  21954. engine.draw(false, 0, 24);
  21955. }
  21956. // Front
  21957. engine.setDepthFunctionToLess();
  21958. this._scene.resetCachedMaterial();
  21959. this._colorShader.setColor4("color", this.frontColor.toColor4());
  21960. this._colorShader.bind(worldMatrix);
  21961. // Draw order
  21962. engine.draw(false, 0, 24);
  21963. }
  21964. this._colorShader.unbind();
  21965. engine.setDepthFunctionToLessOrEqual();
  21966. engine.setDepthWrite(true);
  21967. };
  21968. BoundingBoxRenderer.prototype.dispose = function () {
  21969. this._colorShader.dispose();
  21970. this._vb.dispose();
  21971. this._scene.getEngine()._releaseBuffer(this._ib);
  21972. };
  21973. return BoundingBoxRenderer;
  21974. })();
  21975. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  21976. })(BABYLON || (BABYLON = {}));
  21977. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  21978. (function (BABYLON) {
  21979. var Internals;
  21980. (function (Internals) {
  21981. /*
  21982. * Based on jsTGALoader - Javascript loader for TGA file
  21983. * By Vincent Thibault
  21984. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  21985. */
  21986. var TGATools = (function () {
  21987. function TGATools() {
  21988. }
  21989. TGATools.GetTGAHeader = function (data) {
  21990. var offset = 0;
  21991. var header = {
  21992. id_length: data[offset++],
  21993. colormap_type: data[offset++],
  21994. image_type: data[offset++],
  21995. colormap_index: data[offset++] | data[offset++] << 8,
  21996. colormap_length: data[offset++] | data[offset++] << 8,
  21997. colormap_size: data[offset++],
  21998. origin: [
  21999. data[offset++] | data[offset++] << 8,
  22000. data[offset++] | data[offset++] << 8
  22001. ],
  22002. width: data[offset++] | data[offset++] << 8,
  22003. height: data[offset++] | data[offset++] << 8,
  22004. pixel_size: data[offset++],
  22005. flags: data[offset++]
  22006. };
  22007. return header;
  22008. };
  22009. TGATools.UploadContent = function (gl, data) {
  22010. // Not enough data to contain header ?
  22011. if (data.length < 19) {
  22012. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  22013. return;
  22014. }
  22015. // Read Header
  22016. var offset = 18;
  22017. var header = TGATools.GetTGAHeader(data);
  22018. // Assume it's a valid Targa file.
  22019. if (header.id_length + offset > data.length) {
  22020. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  22021. return;
  22022. }
  22023. // Skip not needed data
  22024. offset += header.id_length;
  22025. var use_rle = false;
  22026. var use_pal = false;
  22027. var use_rgb = false;
  22028. var use_grey = false;
  22029. switch (header.image_type) {
  22030. case TGATools._TYPE_RLE_INDEXED:
  22031. use_rle = true;
  22032. case TGATools._TYPE_INDEXED:
  22033. use_pal = true;
  22034. break;
  22035. case TGATools._TYPE_RLE_RGB:
  22036. use_rle = true;
  22037. case TGATools._TYPE_RGB:
  22038. use_rgb = true;
  22039. break;
  22040. case TGATools._TYPE_RLE_GREY:
  22041. use_rle = true;
  22042. case TGATools._TYPE_GREY:
  22043. use_grey = true;
  22044. break;
  22045. }
  22046. var pixel_data;
  22047. var numAlphaBits = header.flags & 0xf;
  22048. var pixel_size = header.pixel_size >> 3;
  22049. var pixel_total = header.width * header.height * pixel_size;
  22050. // Read palettes
  22051. var palettes;
  22052. if (use_pal) {
  22053. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  22054. }
  22055. // Read LRE
  22056. if (use_rle) {
  22057. pixel_data = new Uint8Array(pixel_total);
  22058. var c, count, i;
  22059. var localOffset = 0;
  22060. var pixels = new Uint8Array(pixel_size);
  22061. while (offset < pixel_total && localOffset < pixel_total) {
  22062. c = data[offset++];
  22063. count = (c & 0x7f) + 1;
  22064. // RLE pixels
  22065. if (c & 0x80) {
  22066. for (i = 0; i < pixel_size; ++i) {
  22067. pixels[i] = data[offset++];
  22068. }
  22069. for (i = 0; i < count; ++i) {
  22070. pixel_data.set(pixels, localOffset + i * pixel_size);
  22071. }
  22072. localOffset += pixel_size * count;
  22073. }
  22074. else {
  22075. count *= pixel_size;
  22076. for (i = 0; i < count; ++i) {
  22077. pixel_data[localOffset + i] = data[offset++];
  22078. }
  22079. localOffset += count;
  22080. }
  22081. }
  22082. }
  22083. else {
  22084. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  22085. }
  22086. // Load to texture
  22087. var x_start, y_start, x_step, y_step, y_end, x_end;
  22088. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  22089. default:
  22090. case TGATools._ORIGIN_UL:
  22091. x_start = 0;
  22092. x_step = 1;
  22093. x_end = header.width;
  22094. y_start = 0;
  22095. y_step = 1;
  22096. y_end = header.height;
  22097. break;
  22098. case TGATools._ORIGIN_BL:
  22099. x_start = 0;
  22100. x_step = 1;
  22101. x_end = header.width;
  22102. y_start = header.height - 1;
  22103. y_step = -1;
  22104. y_end = -1;
  22105. break;
  22106. case TGATools._ORIGIN_UR:
  22107. x_start = header.width - 1;
  22108. x_step = -1;
  22109. x_end = -1;
  22110. y_start = 0;
  22111. y_step = 1;
  22112. y_end = header.height;
  22113. break;
  22114. case TGATools._ORIGIN_BR:
  22115. x_start = header.width - 1;
  22116. x_step = -1;
  22117. x_end = -1;
  22118. y_start = header.height - 1;
  22119. y_step = -1;
  22120. y_end = -1;
  22121. break;
  22122. }
  22123. // Load the specify method
  22124. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  22125. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  22126. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  22127. };
  22128. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22129. var image = pixel_data, colormap = palettes;
  22130. var width = header.width, height = header.height;
  22131. var color, i = 0, x, y;
  22132. var imageData = new Uint8Array(width * height * 4);
  22133. for (y = y_start; y !== y_end; y += y_step) {
  22134. for (x = x_start; x !== x_end; x += x_step, i++) {
  22135. color = image[i];
  22136. imageData[(x + width * y) * 4 + 3] = 255;
  22137. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  22138. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  22139. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  22140. }
  22141. }
  22142. return imageData;
  22143. };
  22144. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22145. var image = pixel_data;
  22146. var width = header.width, height = header.height;
  22147. var color, i = 0, x, y;
  22148. var imageData = new Uint8Array(width * height * 4);
  22149. for (y = y_start; y !== y_end; y += y_step) {
  22150. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22151. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  22152. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  22153. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  22154. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  22155. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  22156. }
  22157. }
  22158. return imageData;
  22159. };
  22160. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22161. var image = pixel_data;
  22162. var width = header.width, height = header.height;
  22163. var i = 0, x, y;
  22164. var imageData = new Uint8Array(width * height * 4);
  22165. for (y = y_start; y !== y_end; y += y_step) {
  22166. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  22167. imageData[(x + width * y) * 4 + 3] = 255;
  22168. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22169. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22170. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22171. }
  22172. }
  22173. return imageData;
  22174. };
  22175. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22176. var image = pixel_data;
  22177. var width = header.width, height = header.height;
  22178. var i = 0, x, y;
  22179. var imageData = new Uint8Array(width * height * 4);
  22180. for (y = y_start; y !== y_end; y += y_step) {
  22181. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  22182. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22183. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22184. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22185. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  22186. }
  22187. }
  22188. return imageData;
  22189. };
  22190. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22191. var image = pixel_data;
  22192. var width = header.width, height = header.height;
  22193. var color, i = 0, x, y;
  22194. var imageData = new Uint8Array(width * height * 4);
  22195. for (y = y_start; y !== y_end; y += y_step) {
  22196. for (x = x_start; x !== x_end; x += x_step, i++) {
  22197. color = image[i];
  22198. imageData[(x + width * y) * 4 + 0] = color;
  22199. imageData[(x + width * y) * 4 + 1] = color;
  22200. imageData[(x + width * y) * 4 + 2] = color;
  22201. imageData[(x + width * y) * 4 + 3] = 255;
  22202. }
  22203. }
  22204. return imageData;
  22205. };
  22206. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22207. var image = pixel_data;
  22208. var width = header.width, height = header.height;
  22209. var i = 0, x, y;
  22210. var imageData = new Uint8Array(width * height * 4);
  22211. for (y = y_start; y !== y_end; y += y_step) {
  22212. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22213. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  22214. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  22215. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22216. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  22217. }
  22218. }
  22219. return imageData;
  22220. };
  22221. TGATools._TYPE_NO_DATA = 0;
  22222. TGATools._TYPE_INDEXED = 1;
  22223. TGATools._TYPE_RGB = 2;
  22224. TGATools._TYPE_GREY = 3;
  22225. TGATools._TYPE_RLE_INDEXED = 9;
  22226. TGATools._TYPE_RLE_RGB = 10;
  22227. TGATools._TYPE_RLE_GREY = 11;
  22228. TGATools._ORIGIN_MASK = 0x30;
  22229. TGATools._ORIGIN_SHIFT = 0x04;
  22230. TGATools._ORIGIN_BL = 0x00;
  22231. TGATools._ORIGIN_BR = 0x01;
  22232. TGATools._ORIGIN_UL = 0x02;
  22233. TGATools._ORIGIN_UR = 0x03;
  22234. return TGATools;
  22235. })();
  22236. Internals.TGATools = TGATools;
  22237. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22238. })(BABYLON || (BABYLON = {}));
  22239. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  22240. (function (BABYLON) {
  22241. var Internals;
  22242. (function (Internals) {
  22243. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  22244. // All values and structures referenced from:
  22245. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  22246. var DDS_MAGIC = 0x20534444;
  22247. 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;
  22248. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  22249. 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;
  22250. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  22251. function FourCCToInt32(value) {
  22252. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  22253. }
  22254. function Int32ToFourCC(value) {
  22255. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  22256. }
  22257. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  22258. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  22259. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  22260. var headerLengthInt = 31; // The header length in 32 bit ints
  22261. // Offsets into the header array
  22262. var off_magic = 0;
  22263. var off_size = 1;
  22264. var off_flags = 2;
  22265. var off_height = 3;
  22266. var off_width = 4;
  22267. var off_mipmapCount = 7;
  22268. var off_pfFlags = 20;
  22269. var off_pfFourCC = 21;
  22270. var off_RGBbpp = 22;
  22271. var off_RMask = 23;
  22272. var off_GMask = 24;
  22273. var off_BMask = 25;
  22274. var off_AMask = 26;
  22275. var off_caps1 = 27;
  22276. var off_caps2 = 28;
  22277. ;
  22278. var DDSTools = (function () {
  22279. function DDSTools() {
  22280. }
  22281. DDSTools.GetDDSInfo = function (arrayBuffer) {
  22282. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  22283. var mipmapCount = 1;
  22284. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  22285. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22286. }
  22287. return {
  22288. width: header[off_width],
  22289. height: header[off_height],
  22290. mipmapCount: mipmapCount,
  22291. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  22292. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  22293. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  22294. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  22295. };
  22296. };
  22297. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22298. var byteArray = new Uint8Array(dataLength);
  22299. var srcData = new Uint8Array(arrayBuffer);
  22300. var index = 0;
  22301. for (var y = height - 1; y >= 0; y--) {
  22302. for (var x = 0; x < width; x++) {
  22303. var srcPos = dataOffset + (x + y * width) * 4;
  22304. byteArray[index + 2] = srcData[srcPos];
  22305. byteArray[index + 1] = srcData[srcPos + 1];
  22306. byteArray[index] = srcData[srcPos + 2];
  22307. byteArray[index + 3] = srcData[srcPos + 3];
  22308. index += 4;
  22309. }
  22310. }
  22311. return byteArray;
  22312. };
  22313. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22314. var byteArray = new Uint8Array(dataLength);
  22315. var srcData = new Uint8Array(arrayBuffer);
  22316. var index = 0;
  22317. for (var y = height - 1; y >= 0; y--) {
  22318. for (var x = 0; x < width; x++) {
  22319. var srcPos = dataOffset + (x + y * width) * 3;
  22320. byteArray[index + 2] = srcData[srcPos];
  22321. byteArray[index + 1] = srcData[srcPos + 1];
  22322. byteArray[index] = srcData[srcPos + 2];
  22323. index += 3;
  22324. }
  22325. }
  22326. return byteArray;
  22327. };
  22328. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22329. var byteArray = new Uint8Array(dataLength);
  22330. var srcData = new Uint8Array(arrayBuffer);
  22331. var index = 0;
  22332. for (var y = height - 1; y >= 0; y--) {
  22333. for (var x = 0; x < width; x++) {
  22334. var srcPos = dataOffset + (x + y * width);
  22335. byteArray[index] = srcData[srcPos];
  22336. index++;
  22337. }
  22338. }
  22339. return byteArray;
  22340. };
  22341. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  22342. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  22343. if (header[off_magic] != DDS_MAGIC) {
  22344. BABYLON.Tools.Error("Invalid magic number in DDS header");
  22345. return;
  22346. }
  22347. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  22348. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  22349. return;
  22350. }
  22351. if (info.isFourCC) {
  22352. fourCC = header[off_pfFourCC];
  22353. switch (fourCC) {
  22354. case FOURCC_DXT1:
  22355. blockBytes = 8;
  22356. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  22357. break;
  22358. case FOURCC_DXT3:
  22359. blockBytes = 16;
  22360. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  22361. break;
  22362. case FOURCC_DXT5:
  22363. blockBytes = 16;
  22364. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  22365. break;
  22366. default:
  22367. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  22368. return;
  22369. }
  22370. }
  22371. mipmapCount = 1;
  22372. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  22373. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22374. }
  22375. var bpp = header[off_RGBbpp];
  22376. for (var face = 0; face < faces; face++) {
  22377. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  22378. width = header[off_width];
  22379. height = header[off_height];
  22380. dataOffset = header[off_size] + 4;
  22381. for (i = 0; i < mipmapCount; ++i) {
  22382. if (info.isRGB) {
  22383. if (bpp == 24) {
  22384. dataLength = width * height * 3;
  22385. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22386. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  22387. }
  22388. else {
  22389. dataLength = width * height * 4;
  22390. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22391. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  22392. }
  22393. }
  22394. else if (info.isLuminance) {
  22395. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  22396. var unpaddedRowSize = width;
  22397. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  22398. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  22399. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22400. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  22401. }
  22402. else {
  22403. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  22404. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  22405. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  22406. }
  22407. dataOffset += dataLength;
  22408. width *= 0.5;
  22409. height *= 0.5;
  22410. width = Math.max(1.0, width);
  22411. height = Math.max(1.0, height);
  22412. }
  22413. }
  22414. };
  22415. return DDSTools;
  22416. })();
  22417. Internals.DDSTools = DDSTools;
  22418. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22419. })(BABYLON || (BABYLON = {}));
  22420. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  22421. (function (BABYLON) {
  22422. var SmartArray = (function () {
  22423. function SmartArray(capacity) {
  22424. this.length = 0;
  22425. this._duplicateId = 0;
  22426. this.data = new Array(capacity);
  22427. this._id = SmartArray._GlobalId++;
  22428. }
  22429. SmartArray.prototype.push = function (value) {
  22430. this.data[this.length++] = value;
  22431. if (this.length > this.data.length) {
  22432. this.data.length *= 2;
  22433. }
  22434. if (!value.__smartArrayFlags) {
  22435. value.__smartArrayFlags = {};
  22436. }
  22437. value.__smartArrayFlags[this._id] = this._duplicateId;
  22438. };
  22439. SmartArray.prototype.pushNoDuplicate = function (value) {
  22440. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  22441. return;
  22442. }
  22443. this.push(value);
  22444. };
  22445. SmartArray.prototype.sort = function (compareFn) {
  22446. this.data.sort(compareFn);
  22447. };
  22448. SmartArray.prototype.reset = function () {
  22449. this.length = 0;
  22450. this._duplicateId++;
  22451. };
  22452. SmartArray.prototype.concat = function (array) {
  22453. if (array.length === 0) {
  22454. return;
  22455. }
  22456. if (this.length + array.length > this.data.length) {
  22457. this.data.length = (this.length + array.length) * 2;
  22458. }
  22459. for (var index = 0; index < array.length; index++) {
  22460. this.data[this.length++] = (array.data || array)[index];
  22461. }
  22462. };
  22463. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  22464. if (array.length === 0) {
  22465. return;
  22466. }
  22467. if (this.length + array.length > this.data.length) {
  22468. this.data.length = (this.length + array.length) * 2;
  22469. }
  22470. for (var index = 0; index < array.length; index++) {
  22471. var item = (array.data || array)[index];
  22472. this.pushNoDuplicate(item);
  22473. }
  22474. };
  22475. SmartArray.prototype.indexOf = function (value) {
  22476. var position = this.data.indexOf(value);
  22477. if (position >= this.length) {
  22478. return -1;
  22479. }
  22480. return position;
  22481. };
  22482. // Statics
  22483. SmartArray._GlobalId = 0;
  22484. return SmartArray;
  22485. })();
  22486. BABYLON.SmartArray = SmartArray;
  22487. })(BABYLON || (BABYLON = {}));
  22488. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  22489. (function (BABYLON) {
  22490. var CannonJSPlugin = (function () {
  22491. function CannonJSPlugin() {
  22492. this._registeredMeshes = [];
  22493. this._physicsMaterials = [];
  22494. this.updateBodyPosition = function (mesh) {
  22495. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22496. var registeredMesh = this._registeredMeshes[index];
  22497. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22498. var body = registeredMesh.body;
  22499. var center = mesh.getBoundingInfo().boundingBox.center;
  22500. body.position.set(center.x, center.z, center.y);
  22501. body.quaternion.x = mesh.rotationQuaternion.x;
  22502. body.quaternion.z = mesh.rotationQuaternion.y;
  22503. body.quaternion.y = mesh.rotationQuaternion.z;
  22504. body.quaternion.w = -mesh.rotationQuaternion.w;
  22505. return;
  22506. }
  22507. }
  22508. };
  22509. }
  22510. CannonJSPlugin.prototype.initialize = function (iterations) {
  22511. if (iterations === void 0) { iterations = 10; }
  22512. this._world = new CANNON.World();
  22513. this._world.broadphase = new CANNON.NaiveBroadphase();
  22514. this._world.solver.iterations = iterations;
  22515. };
  22516. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22517. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22518. };
  22519. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22520. this._world.step(delta);
  22521. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22522. var registeredMesh = this._registeredMeshes[index];
  22523. if (registeredMesh.isChild) {
  22524. continue;
  22525. }
  22526. // Body position
  22527. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22528. var deltaPos = registeredMesh.delta;
  22529. if (deltaPos) {
  22530. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22531. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22532. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22533. }
  22534. else {
  22535. registeredMesh.mesh.position.x = bodyX;
  22536. registeredMesh.mesh.position.y = bodyZ;
  22537. registeredMesh.mesh.position.z = bodyY;
  22538. }
  22539. if (!registeredMesh.mesh.rotationQuaternion) {
  22540. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22541. }
  22542. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22543. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22544. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22545. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22546. }
  22547. };
  22548. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22549. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22550. };
  22551. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22552. this.unregisterMesh(mesh);
  22553. mesh.computeWorldMatrix(true);
  22554. switch (impostor) {
  22555. case BABYLON.PhysicsEngine.SphereImpostor:
  22556. var bbox = mesh.getBoundingInfo().boundingBox;
  22557. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22558. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22559. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22560. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22561. case BABYLON.PhysicsEngine.BoxImpostor:
  22562. bbox = mesh.getBoundingInfo().boundingBox;
  22563. var min = bbox.minimumWorld;
  22564. var max = bbox.maximumWorld;
  22565. var box = max.subtract(min).scale(0.5);
  22566. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22567. case BABYLON.PhysicsEngine.PlaneImpostor:
  22568. return this._createPlane(mesh, options);
  22569. case BABYLON.PhysicsEngine.MeshImpostor:
  22570. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22571. var rawFaces = mesh.getIndices();
  22572. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22573. }
  22574. return null;
  22575. };
  22576. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22577. var shape = new CANNON.Sphere(radius);
  22578. if (!options) {
  22579. return shape;
  22580. }
  22581. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22582. };
  22583. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22584. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22585. if (!options) {
  22586. return shape;
  22587. }
  22588. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22589. };
  22590. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22591. var shape = new CANNON.Plane();
  22592. if (!options) {
  22593. return shape;
  22594. }
  22595. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22596. };
  22597. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22598. var verts = [], faces = [];
  22599. mesh.computeWorldMatrix(true);
  22600. for (var i = 0; i < rawVerts.length; i += 3) {
  22601. var transformed = BABYLON.Vector3.Zero();
  22602. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22603. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22604. }
  22605. for (var j = 0; j < rawFaces.length; j += 3) {
  22606. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22607. }
  22608. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22609. if (!options) {
  22610. return shape;
  22611. }
  22612. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22613. };
  22614. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22615. var index;
  22616. var mat;
  22617. for (index = 0; index < this._physicsMaterials.length; index++) {
  22618. mat = this._physicsMaterials[index];
  22619. if (mat.friction === friction && mat.restitution === restitution) {
  22620. return mat;
  22621. }
  22622. }
  22623. var currentMat = new CANNON.Material();
  22624. currentMat.friction = friction;
  22625. currentMat.restitution = restitution;
  22626. this._physicsMaterials.push(currentMat);
  22627. for (index = 0; index < this._physicsMaterials.length; index++) {
  22628. mat = this._physicsMaterials[index];
  22629. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22630. contactMaterial.contactEquationStiffness = 1e10;
  22631. contactMaterial.contactEquationRegularizationTime = 10;
  22632. this._world.addContactMaterial(contactMaterial);
  22633. }
  22634. return currentMat;
  22635. };
  22636. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22637. var initialRotation = null;
  22638. if (mesh.rotationQuaternion) {
  22639. initialRotation = mesh.rotationQuaternion.clone();
  22640. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22641. }
  22642. // The delta between the mesh position and the mesh bounding box center
  22643. var bbox = mesh.getBoundingInfo().boundingBox;
  22644. var deltaPosition = mesh.position.subtract(bbox.center);
  22645. var material = this._addMaterial(friction, restitution);
  22646. var body = new CANNON.RigidBody(mass, shape, material);
  22647. if (initialRotation) {
  22648. body.quaternion.x = initialRotation.x;
  22649. body.quaternion.z = initialRotation.y;
  22650. body.quaternion.y = initialRotation.z;
  22651. body.quaternion.w = -initialRotation.w;
  22652. }
  22653. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22654. this._world.add(body);
  22655. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22656. return body;
  22657. };
  22658. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22659. var compoundShape = new CANNON.Compound();
  22660. for (var index = 0; index < parts.length; index++) {
  22661. var mesh = parts[index].mesh;
  22662. var shape = this.registerMesh(mesh, parts[index].impostor);
  22663. if (index == 0) {
  22664. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22665. }
  22666. else {
  22667. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22668. }
  22669. }
  22670. var initialMesh = parts[0].mesh;
  22671. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22672. body.parts = parts;
  22673. return body;
  22674. };
  22675. CannonJSPlugin.prototype._unbindBody = function (body) {
  22676. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22677. var registeredMesh = this._registeredMeshes[index];
  22678. if (registeredMesh.body === body) {
  22679. registeredMesh.body = null;
  22680. registeredMesh.delta = 0;
  22681. }
  22682. }
  22683. };
  22684. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22685. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22686. var registeredMesh = this._registeredMeshes[index];
  22687. if (registeredMesh.mesh === mesh) {
  22688. // Remove body
  22689. if (registeredMesh.body) {
  22690. this._world.remove(registeredMesh.body);
  22691. this._unbindBody(registeredMesh.body);
  22692. }
  22693. this._registeredMeshes.splice(index, 1);
  22694. return;
  22695. }
  22696. }
  22697. };
  22698. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22699. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22700. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22701. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22702. var registeredMesh = this._registeredMeshes[index];
  22703. if (registeredMesh.mesh === mesh) {
  22704. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22705. return;
  22706. }
  22707. }
  22708. };
  22709. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22710. var body1 = null, body2 = null;
  22711. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22712. var registeredMesh = this._registeredMeshes[index];
  22713. if (registeredMesh.mesh === mesh1) {
  22714. body1 = registeredMesh.body;
  22715. }
  22716. else if (registeredMesh.mesh === mesh2) {
  22717. body2 = registeredMesh.body;
  22718. }
  22719. }
  22720. if (!body1 || !body2) {
  22721. return false;
  22722. }
  22723. 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));
  22724. this._world.addConstraint(constraint);
  22725. return true;
  22726. };
  22727. CannonJSPlugin.prototype.dispose = function () {
  22728. while (this._registeredMeshes.length) {
  22729. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22730. }
  22731. };
  22732. CannonJSPlugin.prototype.isSupported = function () {
  22733. return window.CANNON !== undefined;
  22734. };
  22735. return CannonJSPlugin;
  22736. })();
  22737. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22738. })(BABYLON || (BABYLON = {}));
  22739. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22740. var BABYLON;
  22741. (function (BABYLON) {
  22742. var Condition = (function () {
  22743. function Condition(actionManager) {
  22744. this._actionManager = actionManager;
  22745. }
  22746. Condition.prototype.isValid = function () {
  22747. return true;
  22748. };
  22749. Condition.prototype._getProperty = function (propertyPath) {
  22750. return this._actionManager._getProperty(propertyPath);
  22751. };
  22752. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  22753. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22754. };
  22755. return Condition;
  22756. })();
  22757. BABYLON.Condition = Condition;
  22758. var ValueCondition = (function (_super) {
  22759. __extends(ValueCondition, _super);
  22760. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  22761. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  22762. _super.call(this, actionManager);
  22763. this.propertyPath = propertyPath;
  22764. this.value = value;
  22765. this.operator = operator;
  22766. this._target = this._getEffectiveTarget(target, this.propertyPath);
  22767. this._property = this._getProperty(this.propertyPath);
  22768. }
  22769. Object.defineProperty(ValueCondition, "IsEqual", {
  22770. get: function () {
  22771. return ValueCondition._IsEqual;
  22772. },
  22773. enumerable: true,
  22774. configurable: true
  22775. });
  22776. Object.defineProperty(ValueCondition, "IsDifferent", {
  22777. get: function () {
  22778. return ValueCondition._IsDifferent;
  22779. },
  22780. enumerable: true,
  22781. configurable: true
  22782. });
  22783. Object.defineProperty(ValueCondition, "IsGreater", {
  22784. get: function () {
  22785. return ValueCondition._IsGreater;
  22786. },
  22787. enumerable: true,
  22788. configurable: true
  22789. });
  22790. Object.defineProperty(ValueCondition, "IsLesser", {
  22791. get: function () {
  22792. return ValueCondition._IsLesser;
  22793. },
  22794. enumerable: true,
  22795. configurable: true
  22796. });
  22797. // Methods
  22798. ValueCondition.prototype.isValid = function () {
  22799. switch (this.operator) {
  22800. case ValueCondition.IsGreater:
  22801. return this._target[this._property] > this.value;
  22802. case ValueCondition.IsLesser:
  22803. return this._target[this._property] < this.value;
  22804. case ValueCondition.IsEqual:
  22805. case ValueCondition.IsDifferent:
  22806. var check;
  22807. if (this.value.equals) {
  22808. check = this.value.equals(this._target[this._property]);
  22809. }
  22810. else {
  22811. check = this.value === this._target[this._property];
  22812. }
  22813. return this.operator === ValueCondition.IsEqual ? check : !check;
  22814. }
  22815. return false;
  22816. };
  22817. // Statics
  22818. ValueCondition._IsEqual = 0;
  22819. ValueCondition._IsDifferent = 1;
  22820. ValueCondition._IsGreater = 2;
  22821. ValueCondition._IsLesser = 3;
  22822. return ValueCondition;
  22823. })(Condition);
  22824. BABYLON.ValueCondition = ValueCondition;
  22825. var PredicateCondition = (function (_super) {
  22826. __extends(PredicateCondition, _super);
  22827. function PredicateCondition(actionManager, predicate) {
  22828. _super.call(this, actionManager);
  22829. this.predicate = predicate;
  22830. }
  22831. PredicateCondition.prototype.isValid = function () {
  22832. return this.predicate();
  22833. };
  22834. return PredicateCondition;
  22835. })(Condition);
  22836. BABYLON.PredicateCondition = PredicateCondition;
  22837. var StateCondition = (function (_super) {
  22838. __extends(StateCondition, _super);
  22839. function StateCondition(actionManager, target, value) {
  22840. _super.call(this, actionManager);
  22841. this.value = value;
  22842. this._target = target;
  22843. }
  22844. // Methods
  22845. StateCondition.prototype.isValid = function () {
  22846. return this._target.state === this.value;
  22847. };
  22848. return StateCondition;
  22849. })(Condition);
  22850. BABYLON.StateCondition = StateCondition;
  22851. })(BABYLON || (BABYLON = {}));
  22852. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  22853. (function (BABYLON) {
  22854. var Action = (function () {
  22855. function Action(triggerOptions, condition) {
  22856. this.triggerOptions = triggerOptions;
  22857. if (triggerOptions.parameter) {
  22858. this.trigger = triggerOptions.trigger;
  22859. this._triggerParameter = triggerOptions.parameter;
  22860. }
  22861. else {
  22862. this.trigger = triggerOptions;
  22863. }
  22864. this._nextActiveAction = this;
  22865. this._condition = condition;
  22866. }
  22867. // Methods
  22868. Action.prototype._prepare = function () {
  22869. };
  22870. Action.prototype.getTriggerParameter = function () {
  22871. return this._triggerParameter;
  22872. };
  22873. Action.prototype._executeCurrent = function (evt) {
  22874. if (this._condition) {
  22875. var currentRenderId = this._actionManager.getScene().getRenderId();
  22876. // We cache the current evaluation for the current frame
  22877. if (this._condition._evaluationId === currentRenderId) {
  22878. if (!this._condition._currentResult) {
  22879. return;
  22880. }
  22881. }
  22882. else {
  22883. this._condition._evaluationId = currentRenderId;
  22884. if (!this._condition.isValid()) {
  22885. this._condition._currentResult = false;
  22886. return;
  22887. }
  22888. this._condition._currentResult = true;
  22889. }
  22890. }
  22891. this._nextActiveAction.execute(evt);
  22892. if (this._nextActiveAction._child) {
  22893. if (!this._nextActiveAction._child._actionManager) {
  22894. this._nextActiveAction._child._actionManager = this._actionManager;
  22895. }
  22896. this._nextActiveAction = this._nextActiveAction._child;
  22897. }
  22898. else {
  22899. this._nextActiveAction = this;
  22900. }
  22901. };
  22902. Action.prototype.execute = function (evt) {
  22903. };
  22904. Action.prototype.then = function (action) {
  22905. this._child = action;
  22906. action._actionManager = this._actionManager;
  22907. action._prepare();
  22908. return action;
  22909. };
  22910. Action.prototype._getProperty = function (propertyPath) {
  22911. return this._actionManager._getProperty(propertyPath);
  22912. };
  22913. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  22914. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22915. };
  22916. return Action;
  22917. })();
  22918. BABYLON.Action = Action;
  22919. })(BABYLON || (BABYLON = {}));
  22920. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  22921. (function (BABYLON) {
  22922. /**
  22923. * ActionEvent is the event beint sent when an action is triggered.
  22924. */
  22925. var ActionEvent = (function () {
  22926. /**
  22927. * @constructor
  22928. * @param source The mesh that triggered the action.
  22929. * @param pointerX the X mouse cursor position at the time of the event
  22930. * @param pointerY the Y mouse cursor position at the time of the event
  22931. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  22932. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  22933. */
  22934. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  22935. this.source = source;
  22936. this.pointerX = pointerX;
  22937. this.pointerY = pointerY;
  22938. this.meshUnderPointer = meshUnderPointer;
  22939. this.sourceEvent = sourceEvent;
  22940. }
  22941. /**
  22942. * Helper function to auto-create an ActionEvent from a source mesh.
  22943. * @param source the source mesh that triggered the event
  22944. * @param evt {Event} The original (browser) event
  22945. */
  22946. ActionEvent.CreateNew = function (source, evt) {
  22947. var scene = source.getScene();
  22948. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22949. };
  22950. /**
  22951. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  22952. * @param scene the scene where the event occurred
  22953. * @param evt {Event} The original (browser) event
  22954. */
  22955. ActionEvent.CreateNewFromScene = function (scene, evt) {
  22956. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22957. };
  22958. return ActionEvent;
  22959. })();
  22960. BABYLON.ActionEvent = ActionEvent;
  22961. /**
  22962. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  22963. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  22964. */
  22965. var ActionManager = (function () {
  22966. function ActionManager(scene) {
  22967. // Members
  22968. this.actions = new Array();
  22969. this._scene = scene;
  22970. scene._actionManagers.push(this);
  22971. }
  22972. Object.defineProperty(ActionManager, "NothingTrigger", {
  22973. get: function () {
  22974. return ActionManager._NothingTrigger;
  22975. },
  22976. enumerable: true,
  22977. configurable: true
  22978. });
  22979. Object.defineProperty(ActionManager, "OnPickTrigger", {
  22980. get: function () {
  22981. return ActionManager._OnPickTrigger;
  22982. },
  22983. enumerable: true,
  22984. configurable: true
  22985. });
  22986. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  22987. get: function () {
  22988. return ActionManager._OnLeftPickTrigger;
  22989. },
  22990. enumerable: true,
  22991. configurable: true
  22992. });
  22993. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  22994. get: function () {
  22995. return ActionManager._OnRightPickTrigger;
  22996. },
  22997. enumerable: true,
  22998. configurable: true
  22999. });
  23000. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  23001. get: function () {
  23002. return ActionManager._OnCenterPickTrigger;
  23003. },
  23004. enumerable: true,
  23005. configurable: true
  23006. });
  23007. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  23008. get: function () {
  23009. return ActionManager._OnPointerOverTrigger;
  23010. },
  23011. enumerable: true,
  23012. configurable: true
  23013. });
  23014. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  23015. get: function () {
  23016. return ActionManager._OnPointerOutTrigger;
  23017. },
  23018. enumerable: true,
  23019. configurable: true
  23020. });
  23021. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  23022. get: function () {
  23023. return ActionManager._OnEveryFrameTrigger;
  23024. },
  23025. enumerable: true,
  23026. configurable: true
  23027. });
  23028. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  23029. get: function () {
  23030. return ActionManager._OnIntersectionEnterTrigger;
  23031. },
  23032. enumerable: true,
  23033. configurable: true
  23034. });
  23035. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  23036. get: function () {
  23037. return ActionManager._OnIntersectionExitTrigger;
  23038. },
  23039. enumerable: true,
  23040. configurable: true
  23041. });
  23042. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  23043. get: function () {
  23044. return ActionManager._OnKeyDownTrigger;
  23045. },
  23046. enumerable: true,
  23047. configurable: true
  23048. });
  23049. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  23050. get: function () {
  23051. return ActionManager._OnKeyUpTrigger;
  23052. },
  23053. enumerable: true,
  23054. configurable: true
  23055. });
  23056. // Methods
  23057. ActionManager.prototype.dispose = function () {
  23058. var index = this._scene._actionManagers.indexOf(this);
  23059. if (index > -1) {
  23060. this._scene._actionManagers.splice(index, 1);
  23061. }
  23062. };
  23063. ActionManager.prototype.getScene = function () {
  23064. return this._scene;
  23065. };
  23066. /**
  23067. * Does this action manager handles actions of any of the given triggers
  23068. * @param {number[]} triggers - the triggers to be tested
  23069. * @return {boolean} whether one (or more) of the triggers is handeled
  23070. */
  23071. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  23072. for (var index = 0; index < this.actions.length; index++) {
  23073. var action = this.actions[index];
  23074. if (triggers.indexOf(action.trigger) > -1) {
  23075. return true;
  23076. }
  23077. }
  23078. return false;
  23079. };
  23080. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  23081. /**
  23082. * Does this action manager has pointer triggers
  23083. * @return {boolean} whether or not it has pointer triggers
  23084. */
  23085. get: function () {
  23086. for (var index = 0; index < this.actions.length; index++) {
  23087. var action = this.actions[index];
  23088. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  23089. return true;
  23090. }
  23091. }
  23092. return false;
  23093. },
  23094. enumerable: true,
  23095. configurable: true
  23096. });
  23097. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  23098. /**
  23099. * Does this action manager has pick triggers
  23100. * @return {boolean} whether or not it has pick triggers
  23101. */
  23102. get: function () {
  23103. for (var index = 0; index < this.actions.length; index++) {
  23104. var action = this.actions[index];
  23105. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  23106. return true;
  23107. }
  23108. }
  23109. return false;
  23110. },
  23111. enumerable: true,
  23112. configurable: true
  23113. });
  23114. /**
  23115. * Registers an action to this action manager
  23116. * @param {BABYLON.Action} action - the action to be registered
  23117. * @return {BABYLON.Action} the action amended (prepared) after registration
  23118. */
  23119. ActionManager.prototype.registerAction = function (action) {
  23120. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  23121. if (this.getScene().actionManager !== this) {
  23122. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  23123. return null;
  23124. }
  23125. }
  23126. this.actions.push(action);
  23127. action._actionManager = this;
  23128. action._prepare();
  23129. return action;
  23130. };
  23131. /**
  23132. * Process a specific trigger
  23133. * @param {number} trigger - the trigger to process
  23134. * @param evt {BABYLON.ActionEvent} the event details to be processed
  23135. */
  23136. ActionManager.prototype.processTrigger = function (trigger, evt) {
  23137. for (var index = 0; index < this.actions.length; index++) {
  23138. var action = this.actions[index];
  23139. if (action.trigger === trigger) {
  23140. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  23141. var parameter = action.getTriggerParameter();
  23142. if (parameter) {
  23143. if (evt.sourceEvent.key !== parameter) {
  23144. continue;
  23145. }
  23146. }
  23147. }
  23148. action._executeCurrent(evt);
  23149. }
  23150. }
  23151. };
  23152. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  23153. var properties = propertyPath.split(".");
  23154. for (var index = 0; index < properties.length - 1; index++) {
  23155. target = target[properties[index]];
  23156. }
  23157. return target;
  23158. };
  23159. ActionManager.prototype._getProperty = function (propertyPath) {
  23160. var properties = propertyPath.split(".");
  23161. return properties[properties.length - 1];
  23162. };
  23163. // Statics
  23164. ActionManager._NothingTrigger = 0;
  23165. ActionManager._OnPickTrigger = 1;
  23166. ActionManager._OnLeftPickTrigger = 2;
  23167. ActionManager._OnRightPickTrigger = 3;
  23168. ActionManager._OnCenterPickTrigger = 4;
  23169. ActionManager._OnPointerOverTrigger = 5;
  23170. ActionManager._OnPointerOutTrigger = 6;
  23171. ActionManager._OnEveryFrameTrigger = 7;
  23172. ActionManager._OnIntersectionEnterTrigger = 8;
  23173. ActionManager._OnIntersectionExitTrigger = 9;
  23174. ActionManager._OnKeyDownTrigger = 10;
  23175. ActionManager._OnKeyUpTrigger = 11;
  23176. return ActionManager;
  23177. })();
  23178. BABYLON.ActionManager = ActionManager;
  23179. })(BABYLON || (BABYLON = {}));
  23180. //# sourceMappingURL=babylon.actionManager.js.map
  23181. var BABYLON;
  23182. (function (BABYLON) {
  23183. var InterpolateValueAction = (function (_super) {
  23184. __extends(InterpolateValueAction, _super);
  23185. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  23186. if (duration === void 0) { duration = 1000; }
  23187. _super.call(this, triggerOptions, condition);
  23188. this.propertyPath = propertyPath;
  23189. this.value = value;
  23190. this.duration = duration;
  23191. this.stopOtherAnimations = stopOtherAnimations;
  23192. this._target = target;
  23193. }
  23194. InterpolateValueAction.prototype._prepare = function () {
  23195. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23196. this._property = this._getProperty(this.propertyPath);
  23197. };
  23198. InterpolateValueAction.prototype.execute = function () {
  23199. var scene = this._actionManager.getScene();
  23200. var keys = [
  23201. {
  23202. frame: 0,
  23203. value: this._target[this._property]
  23204. },
  23205. {
  23206. frame: 100,
  23207. value: this.value
  23208. }
  23209. ];
  23210. var dataType;
  23211. if (typeof this.value === "number") {
  23212. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  23213. }
  23214. else if (this.value instanceof BABYLON.Color3) {
  23215. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  23216. }
  23217. else if (this.value instanceof BABYLON.Vector3) {
  23218. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  23219. }
  23220. else if (this.value instanceof BABYLON.Matrix) {
  23221. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  23222. }
  23223. else if (this.value instanceof BABYLON.Quaternion) {
  23224. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  23225. }
  23226. else {
  23227. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  23228. return;
  23229. }
  23230. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  23231. animation.setKeys(keys);
  23232. if (this.stopOtherAnimations) {
  23233. scene.stopAnimation(this._target);
  23234. }
  23235. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  23236. };
  23237. return InterpolateValueAction;
  23238. })(BABYLON.Action);
  23239. BABYLON.InterpolateValueAction = InterpolateValueAction;
  23240. })(BABYLON || (BABYLON = {}));
  23241. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  23242. var BABYLON;
  23243. (function (BABYLON) {
  23244. var SwitchBooleanAction = (function (_super) {
  23245. __extends(SwitchBooleanAction, _super);
  23246. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  23247. _super.call(this, triggerOptions, condition);
  23248. this.propertyPath = propertyPath;
  23249. this._target = target;
  23250. }
  23251. SwitchBooleanAction.prototype._prepare = function () {
  23252. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23253. this._property = this._getProperty(this.propertyPath);
  23254. };
  23255. SwitchBooleanAction.prototype.execute = function () {
  23256. this._target[this._property] = !this._target[this._property];
  23257. };
  23258. return SwitchBooleanAction;
  23259. })(BABYLON.Action);
  23260. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  23261. var SetStateAction = (function (_super) {
  23262. __extends(SetStateAction, _super);
  23263. function SetStateAction(triggerOptions, target, value, condition) {
  23264. _super.call(this, triggerOptions, condition);
  23265. this.value = value;
  23266. this._target = target;
  23267. }
  23268. SetStateAction.prototype.execute = function () {
  23269. this._target.state = this.value;
  23270. };
  23271. return SetStateAction;
  23272. })(BABYLON.Action);
  23273. BABYLON.SetStateAction = SetStateAction;
  23274. var SetValueAction = (function (_super) {
  23275. __extends(SetValueAction, _super);
  23276. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  23277. _super.call(this, triggerOptions, condition);
  23278. this.propertyPath = propertyPath;
  23279. this.value = value;
  23280. this._target = target;
  23281. }
  23282. SetValueAction.prototype._prepare = function () {
  23283. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23284. this._property = this._getProperty(this.propertyPath);
  23285. };
  23286. SetValueAction.prototype.execute = function () {
  23287. this._target[this._property] = this.value;
  23288. };
  23289. return SetValueAction;
  23290. })(BABYLON.Action);
  23291. BABYLON.SetValueAction = SetValueAction;
  23292. var IncrementValueAction = (function (_super) {
  23293. __extends(IncrementValueAction, _super);
  23294. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  23295. _super.call(this, triggerOptions, condition);
  23296. this.propertyPath = propertyPath;
  23297. this.value = value;
  23298. this._target = target;
  23299. }
  23300. IncrementValueAction.prototype._prepare = function () {
  23301. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23302. this._property = this._getProperty(this.propertyPath);
  23303. if (typeof this._target[this._property] !== "number") {
  23304. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  23305. }
  23306. };
  23307. IncrementValueAction.prototype.execute = function () {
  23308. this._target[this._property] += this.value;
  23309. };
  23310. return IncrementValueAction;
  23311. })(BABYLON.Action);
  23312. BABYLON.IncrementValueAction = IncrementValueAction;
  23313. var PlayAnimationAction = (function (_super) {
  23314. __extends(PlayAnimationAction, _super);
  23315. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  23316. _super.call(this, triggerOptions, condition);
  23317. this.from = from;
  23318. this.to = to;
  23319. this.loop = loop;
  23320. this._target = target;
  23321. }
  23322. PlayAnimationAction.prototype._prepare = function () {
  23323. };
  23324. PlayAnimationAction.prototype.execute = function () {
  23325. var scene = this._actionManager.getScene();
  23326. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  23327. };
  23328. return PlayAnimationAction;
  23329. })(BABYLON.Action);
  23330. BABYLON.PlayAnimationAction = PlayAnimationAction;
  23331. var StopAnimationAction = (function (_super) {
  23332. __extends(StopAnimationAction, _super);
  23333. function StopAnimationAction(triggerOptions, target, condition) {
  23334. _super.call(this, triggerOptions, condition);
  23335. this._target = target;
  23336. }
  23337. StopAnimationAction.prototype._prepare = function () {
  23338. };
  23339. StopAnimationAction.prototype.execute = function () {
  23340. var scene = this._actionManager.getScene();
  23341. scene.stopAnimation(this._target);
  23342. };
  23343. return StopAnimationAction;
  23344. })(BABYLON.Action);
  23345. BABYLON.StopAnimationAction = StopAnimationAction;
  23346. var DoNothingAction = (function (_super) {
  23347. __extends(DoNothingAction, _super);
  23348. function DoNothingAction(triggerOptions, condition) {
  23349. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  23350. _super.call(this, triggerOptions, condition);
  23351. }
  23352. DoNothingAction.prototype.execute = function () {
  23353. };
  23354. return DoNothingAction;
  23355. })(BABYLON.Action);
  23356. BABYLON.DoNothingAction = DoNothingAction;
  23357. var CombineAction = (function (_super) {
  23358. __extends(CombineAction, _super);
  23359. function CombineAction(triggerOptions, children, condition) {
  23360. _super.call(this, triggerOptions, condition);
  23361. this.children = children;
  23362. }
  23363. CombineAction.prototype._prepare = function () {
  23364. for (var index = 0; index < this.children.length; index++) {
  23365. this.children[index]._actionManager = this._actionManager;
  23366. this.children[index]._prepare();
  23367. }
  23368. };
  23369. CombineAction.prototype.execute = function (evt) {
  23370. for (var index = 0; index < this.children.length; index++) {
  23371. this.children[index].execute(evt);
  23372. }
  23373. };
  23374. return CombineAction;
  23375. })(BABYLON.Action);
  23376. BABYLON.CombineAction = CombineAction;
  23377. var ExecuteCodeAction = (function (_super) {
  23378. __extends(ExecuteCodeAction, _super);
  23379. function ExecuteCodeAction(triggerOptions, func, condition) {
  23380. _super.call(this, triggerOptions, condition);
  23381. this.func = func;
  23382. }
  23383. ExecuteCodeAction.prototype.execute = function (evt) {
  23384. this.func(evt);
  23385. };
  23386. return ExecuteCodeAction;
  23387. })(BABYLON.Action);
  23388. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  23389. var SetParentAction = (function (_super) {
  23390. __extends(SetParentAction, _super);
  23391. function SetParentAction(triggerOptions, target, parent, condition) {
  23392. _super.call(this, triggerOptions, condition);
  23393. this._target = target;
  23394. this._parent = parent;
  23395. }
  23396. SetParentAction.prototype._prepare = function () {
  23397. };
  23398. SetParentAction.prototype.execute = function () {
  23399. if (this._target.parent === this._parent) {
  23400. return;
  23401. }
  23402. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  23403. invertParentWorldMatrix.invert();
  23404. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  23405. this._target.parent = this._parent;
  23406. };
  23407. return SetParentAction;
  23408. })(BABYLON.Action);
  23409. BABYLON.SetParentAction = SetParentAction;
  23410. })(BABYLON || (BABYLON = {}));
  23411. //# sourceMappingURL=babylon.directActions.js.map
  23412. var BABYLON;
  23413. (function (BABYLON) {
  23414. var Geometry = (function () {
  23415. function Geometry(id, scene, vertexData, updatable, mesh) {
  23416. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23417. this._totalVertices = 0;
  23418. this._indices = [];
  23419. this.id = id;
  23420. this._engine = scene.getEngine();
  23421. this._meshes = [];
  23422. this._scene = scene;
  23423. // vertexData
  23424. if (vertexData) {
  23425. this.setAllVerticesData(vertexData, updatable);
  23426. }
  23427. else {
  23428. this._totalVertices = 0;
  23429. this._indices = [];
  23430. }
  23431. // applyToMesh
  23432. if (mesh) {
  23433. this.applyToMesh(mesh);
  23434. }
  23435. }
  23436. Geometry.prototype.getScene = function () {
  23437. return this._scene;
  23438. };
  23439. Geometry.prototype.getEngine = function () {
  23440. return this._engine;
  23441. };
  23442. Geometry.prototype.isReady = function () {
  23443. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  23444. };
  23445. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  23446. vertexData.applyToGeometry(this, updatable);
  23447. };
  23448. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23449. this._vertexBuffers = this._vertexBuffers || {};
  23450. if (this._vertexBuffers[kind]) {
  23451. this._vertexBuffers[kind].dispose();
  23452. }
  23453. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  23454. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23455. stride = this._vertexBuffers[kind].getStrideSize();
  23456. this._totalVertices = data.length / stride;
  23457. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23458. var meshes = this._meshes;
  23459. var numOfMeshes = meshes.length;
  23460. for (var index = 0; index < numOfMeshes; index++) {
  23461. var mesh = meshes[index];
  23462. mesh._resetPointsArrayCache();
  23463. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23464. mesh._createGlobalSubMesh();
  23465. mesh.computeWorldMatrix(true);
  23466. }
  23467. }
  23468. };
  23469. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  23470. var vertexBuffer = this.getVertexBuffer(kind);
  23471. if (!vertexBuffer) {
  23472. return;
  23473. }
  23474. vertexBuffer.updateDirectly(data, offset);
  23475. };
  23476. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  23477. var vertexBuffer = this.getVertexBuffer(kind);
  23478. if (!vertexBuffer) {
  23479. return;
  23480. }
  23481. vertexBuffer.update(data);
  23482. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23483. var extend;
  23484. var stride = vertexBuffer.getStrideSize();
  23485. this._totalVertices = data.length / stride;
  23486. if (updateExtends) {
  23487. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23488. }
  23489. var meshes = this._meshes;
  23490. var numOfMeshes = meshes.length;
  23491. for (var index = 0; index < numOfMeshes; index++) {
  23492. var mesh = meshes[index];
  23493. mesh._resetPointsArrayCache();
  23494. if (updateExtends) {
  23495. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23496. }
  23497. }
  23498. }
  23499. };
  23500. Geometry.prototype.getTotalVertices = function () {
  23501. if (!this.isReady()) {
  23502. return 0;
  23503. }
  23504. return this._totalVertices;
  23505. };
  23506. Geometry.prototype.getVerticesData = function (kind) {
  23507. var vertexBuffer = this.getVertexBuffer(kind);
  23508. if (!vertexBuffer) {
  23509. return null;
  23510. }
  23511. return vertexBuffer.getData();
  23512. };
  23513. Geometry.prototype.getVertexBuffer = function (kind) {
  23514. if (!this.isReady()) {
  23515. return null;
  23516. }
  23517. return this._vertexBuffers[kind];
  23518. };
  23519. Geometry.prototype.getVertexBuffers = function () {
  23520. if (!this.isReady()) {
  23521. return null;
  23522. }
  23523. return this._vertexBuffers;
  23524. };
  23525. Geometry.prototype.isVerticesDataPresent = function (kind) {
  23526. if (!this._vertexBuffers) {
  23527. if (this._delayInfo) {
  23528. return this._delayInfo.indexOf(kind) !== -1;
  23529. }
  23530. return false;
  23531. }
  23532. return this._vertexBuffers[kind] !== undefined;
  23533. };
  23534. Geometry.prototype.getVerticesDataKinds = function () {
  23535. var result = [];
  23536. if (!this._vertexBuffers && this._delayInfo) {
  23537. for (var kind in this._delayInfo) {
  23538. result.push(kind);
  23539. }
  23540. }
  23541. else {
  23542. for (kind in this._vertexBuffers) {
  23543. result.push(kind);
  23544. }
  23545. }
  23546. return result;
  23547. };
  23548. Geometry.prototype.setIndices = function (indices, totalVertices) {
  23549. if (this._indexBuffer) {
  23550. this._engine._releaseBuffer(this._indexBuffer);
  23551. }
  23552. this._indices = indices;
  23553. if (this._meshes.length !== 0 && this._indices) {
  23554. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23555. }
  23556. if (totalVertices !== undefined) {
  23557. this._totalVertices = totalVertices;
  23558. }
  23559. var meshes = this._meshes;
  23560. var numOfMeshes = meshes.length;
  23561. for (var index = 0; index < numOfMeshes; index++) {
  23562. meshes[index]._createGlobalSubMesh();
  23563. }
  23564. };
  23565. Geometry.prototype.getTotalIndices = function () {
  23566. if (!this.isReady()) {
  23567. return 0;
  23568. }
  23569. return this._indices.length;
  23570. };
  23571. Geometry.prototype.getIndices = function () {
  23572. if (!this.isReady()) {
  23573. return null;
  23574. }
  23575. return this._indices;
  23576. };
  23577. Geometry.prototype.getIndexBuffer = function () {
  23578. if (!this.isReady()) {
  23579. return null;
  23580. }
  23581. return this._indexBuffer;
  23582. };
  23583. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  23584. var meshes = this._meshes;
  23585. var index = meshes.indexOf(mesh);
  23586. if (index === -1) {
  23587. return;
  23588. }
  23589. for (var kind in this._vertexBuffers) {
  23590. this._vertexBuffers[kind].dispose();
  23591. }
  23592. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  23593. this._indexBuffer = null;
  23594. }
  23595. meshes.splice(index, 1);
  23596. mesh._geometry = null;
  23597. if (meshes.length === 0 && shouldDispose) {
  23598. this.dispose();
  23599. }
  23600. };
  23601. Geometry.prototype.applyToMesh = function (mesh) {
  23602. if (mesh._geometry === this) {
  23603. return;
  23604. }
  23605. var previousGeometry = mesh._geometry;
  23606. if (previousGeometry) {
  23607. previousGeometry.releaseForMesh(mesh);
  23608. }
  23609. var meshes = this._meshes;
  23610. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  23611. mesh._geometry = this;
  23612. this._scene.pushGeometry(this);
  23613. meshes.push(mesh);
  23614. if (this.isReady()) {
  23615. this._applyToMesh(mesh);
  23616. }
  23617. else {
  23618. mesh._boundingInfo = this._boundingInfo;
  23619. }
  23620. };
  23621. Geometry.prototype._applyToMesh = function (mesh) {
  23622. var numOfMeshes = this._meshes.length;
  23623. for (var kind in this._vertexBuffers) {
  23624. if (numOfMeshes === 1) {
  23625. this._vertexBuffers[kind].create();
  23626. }
  23627. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  23628. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23629. mesh._resetPointsArrayCache();
  23630. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  23631. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23632. mesh._createGlobalSubMesh();
  23633. //bounding info was just created again, world matrix should be applied again.
  23634. mesh._updateBoundingInfo();
  23635. }
  23636. }
  23637. // indexBuffer
  23638. if (numOfMeshes === 1 && this._indices) {
  23639. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23640. }
  23641. if (this._indexBuffer) {
  23642. this._indexBuffer.references = numOfMeshes;
  23643. }
  23644. };
  23645. Geometry.prototype.load = function (scene, onLoaded) {
  23646. var _this = this;
  23647. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23648. return;
  23649. }
  23650. if (this.isReady()) {
  23651. if (onLoaded) {
  23652. onLoaded();
  23653. }
  23654. return;
  23655. }
  23656. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23657. scene._addPendingData(this);
  23658. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23659. _this._delayLoadingFunction(JSON.parse(data), _this);
  23660. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23661. _this._delayInfo = [];
  23662. scene._removePendingData(_this);
  23663. var meshes = _this._meshes;
  23664. var numOfMeshes = meshes.length;
  23665. for (var index = 0; index < numOfMeshes; index++) {
  23666. _this._applyToMesh(meshes[index]);
  23667. }
  23668. if (onLoaded) {
  23669. onLoaded();
  23670. }
  23671. }, function () {
  23672. }, scene.database);
  23673. };
  23674. Geometry.prototype.dispose = function () {
  23675. var meshes = this._meshes;
  23676. var numOfMeshes = meshes.length;
  23677. var index;
  23678. for (index = 0; index < numOfMeshes; index++) {
  23679. this.releaseForMesh(meshes[index]);
  23680. }
  23681. this._meshes = [];
  23682. for (var kind in this._vertexBuffers) {
  23683. this._vertexBuffers[kind].dispose();
  23684. }
  23685. this._vertexBuffers = [];
  23686. this._totalVertices = 0;
  23687. if (this._indexBuffer) {
  23688. this._engine._releaseBuffer(this._indexBuffer);
  23689. }
  23690. this._indexBuffer = null;
  23691. this._indices = [];
  23692. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23693. this.delayLoadingFile = null;
  23694. this._delayLoadingFunction = null;
  23695. this._delayInfo = [];
  23696. this._boundingInfo = null; // todo: .dispose()
  23697. var geometries = this._scene.getGeometries();
  23698. index = geometries.indexOf(this);
  23699. if (index > -1) {
  23700. geometries.splice(index, 1);
  23701. }
  23702. };
  23703. Geometry.prototype.copy = function (id) {
  23704. var vertexData = new BABYLON.VertexData();
  23705. vertexData.indices = [];
  23706. var indices = this.getIndices();
  23707. for (var index = 0; index < indices.length; index++) {
  23708. vertexData.indices.push(indices[index]);
  23709. }
  23710. var updatable = false;
  23711. var stopChecking = false;
  23712. for (var kind in this._vertexBuffers) {
  23713. vertexData.set(this.getVerticesData(kind), kind);
  23714. if (!stopChecking) {
  23715. updatable = this.getVertexBuffer(kind).isUpdatable();
  23716. stopChecking = !updatable;
  23717. }
  23718. }
  23719. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  23720. geometry.delayLoadState = this.delayLoadState;
  23721. geometry.delayLoadingFile = this.delayLoadingFile;
  23722. geometry._delayLoadingFunction = this._delayLoadingFunction;
  23723. for (kind in this._delayInfo) {
  23724. geometry._delayInfo = geometry._delayInfo || [];
  23725. geometry._delayInfo.push(kind);
  23726. }
  23727. // Bounding info
  23728. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  23729. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23730. return geometry;
  23731. };
  23732. // Statics
  23733. Geometry.ExtractFromMesh = function (mesh, id) {
  23734. var geometry = mesh._geometry;
  23735. if (!geometry) {
  23736. return null;
  23737. }
  23738. return geometry.copy(id);
  23739. };
  23740. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  23741. // be aware Math.random() could cause collisions
  23742. Geometry.RandomId = function () {
  23743. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  23744. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  23745. return v.toString(16);
  23746. });
  23747. };
  23748. return Geometry;
  23749. })();
  23750. BABYLON.Geometry = Geometry;
  23751. /////// Primitives //////////////////////////////////////////////
  23752. var Geometry;
  23753. (function (Geometry) {
  23754. var Primitives;
  23755. (function (Primitives) {
  23756. /// Abstract class
  23757. var _Primitive = (function (_super) {
  23758. __extends(_Primitive, _super);
  23759. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  23760. this._beingRegenerated = true;
  23761. this._canBeRegenerated = canBeRegenerated;
  23762. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  23763. this._beingRegenerated = false;
  23764. }
  23765. _Primitive.prototype.canBeRegenerated = function () {
  23766. return this._canBeRegenerated;
  23767. };
  23768. _Primitive.prototype.regenerate = function () {
  23769. if (!this._canBeRegenerated) {
  23770. return;
  23771. }
  23772. this._beingRegenerated = true;
  23773. this.setAllVerticesData(this._regenerateVertexData(), false);
  23774. this._beingRegenerated = false;
  23775. };
  23776. _Primitive.prototype.asNewGeometry = function (id) {
  23777. return _super.prototype.copy.call(this, id);
  23778. };
  23779. // overrides
  23780. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  23781. if (!this._beingRegenerated) {
  23782. return;
  23783. }
  23784. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  23785. };
  23786. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  23787. if (!this._beingRegenerated) {
  23788. return;
  23789. }
  23790. _super.prototype.setVerticesData.call(this, kind, data, false);
  23791. };
  23792. // to override
  23793. // protected
  23794. _Primitive.prototype._regenerateVertexData = function () {
  23795. throw new Error("Abstract method");
  23796. };
  23797. _Primitive.prototype.copy = function (id) {
  23798. throw new Error("Must be overriden in sub-classes.");
  23799. };
  23800. return _Primitive;
  23801. })(Geometry);
  23802. Primitives._Primitive = _Primitive;
  23803. var Box = (function (_super) {
  23804. __extends(Box, _super);
  23805. function Box(id, scene, size, canBeRegenerated, mesh) {
  23806. this.size = size;
  23807. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23808. }
  23809. Box.prototype._regenerateVertexData = function () {
  23810. return BABYLON.VertexData.CreateBox(this.size);
  23811. };
  23812. Box.prototype.copy = function (id) {
  23813. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23814. };
  23815. return Box;
  23816. })(_Primitive);
  23817. Primitives.Box = Box;
  23818. var Sphere = (function (_super) {
  23819. __extends(Sphere, _super);
  23820. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  23821. this.segments = segments;
  23822. this.diameter = diameter;
  23823. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23824. }
  23825. Sphere.prototype._regenerateVertexData = function () {
  23826. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  23827. };
  23828. Sphere.prototype.copy = function (id) {
  23829. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  23830. };
  23831. return Sphere;
  23832. })(_Primitive);
  23833. Primitives.Sphere = Sphere;
  23834. var Cylinder = (function (_super) {
  23835. __extends(Cylinder, _super);
  23836. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  23837. if (subdivisions === void 0) { subdivisions = 1; }
  23838. this.height = height;
  23839. this.diameterTop = diameterTop;
  23840. this.diameterBottom = diameterBottom;
  23841. this.tessellation = tessellation;
  23842. this.subdivisions = subdivisions;
  23843. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23844. }
  23845. Cylinder.prototype._regenerateVertexData = function () {
  23846. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  23847. };
  23848. Cylinder.prototype.copy = function (id) {
  23849. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  23850. };
  23851. return Cylinder;
  23852. })(_Primitive);
  23853. Primitives.Cylinder = Cylinder;
  23854. var Torus = (function (_super) {
  23855. __extends(Torus, _super);
  23856. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  23857. this.diameter = diameter;
  23858. this.thickness = thickness;
  23859. this.tessellation = tessellation;
  23860. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23861. }
  23862. Torus.prototype._regenerateVertexData = function () {
  23863. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  23864. };
  23865. Torus.prototype.copy = function (id) {
  23866. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  23867. };
  23868. return Torus;
  23869. })(_Primitive);
  23870. Primitives.Torus = Torus;
  23871. var Ground = (function (_super) {
  23872. __extends(Ground, _super);
  23873. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  23874. this.width = width;
  23875. this.height = height;
  23876. this.subdivisions = subdivisions;
  23877. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23878. }
  23879. Ground.prototype._regenerateVertexData = function () {
  23880. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  23881. };
  23882. Ground.prototype.copy = function (id) {
  23883. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  23884. };
  23885. return Ground;
  23886. })(_Primitive);
  23887. Primitives.Ground = Ground;
  23888. var TiledGround = (function (_super) {
  23889. __extends(TiledGround, _super);
  23890. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  23891. this.xmin = xmin;
  23892. this.zmin = zmin;
  23893. this.xmax = xmax;
  23894. this.zmax = zmax;
  23895. this.subdivisions = subdivisions;
  23896. this.precision = precision;
  23897. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23898. }
  23899. TiledGround.prototype._regenerateVertexData = function () {
  23900. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  23901. };
  23902. TiledGround.prototype.copy = function (id) {
  23903. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  23904. };
  23905. return TiledGround;
  23906. })(_Primitive);
  23907. Primitives.TiledGround = TiledGround;
  23908. var Plane = (function (_super) {
  23909. __extends(Plane, _super);
  23910. function Plane(id, scene, size, canBeRegenerated, mesh) {
  23911. this.size = size;
  23912. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23913. }
  23914. Plane.prototype._regenerateVertexData = function () {
  23915. return BABYLON.VertexData.CreatePlane(this.size);
  23916. };
  23917. Plane.prototype.copy = function (id) {
  23918. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23919. };
  23920. return Plane;
  23921. })(_Primitive);
  23922. Primitives.Plane = Plane;
  23923. var TorusKnot = (function (_super) {
  23924. __extends(TorusKnot, _super);
  23925. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  23926. this.radius = radius;
  23927. this.tube = tube;
  23928. this.radialSegments = radialSegments;
  23929. this.tubularSegments = tubularSegments;
  23930. this.p = p;
  23931. this.q = q;
  23932. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23933. }
  23934. TorusKnot.prototype._regenerateVertexData = function () {
  23935. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  23936. };
  23937. TorusKnot.prototype.copy = function (id) {
  23938. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  23939. };
  23940. return TorusKnot;
  23941. })(_Primitive);
  23942. Primitives.TorusKnot = TorusKnot;
  23943. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  23944. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  23945. })(BABYLON || (BABYLON = {}));
  23946. //# sourceMappingURL=babylon.geometry.js.map
  23947. var BABYLON;
  23948. (function (BABYLON) {
  23949. var Gamepads = (function () {
  23950. function Gamepads(ongamedpadconnected) {
  23951. var _this = this;
  23952. this.babylonGamepads = [];
  23953. this.oneGamepadConnected = false;
  23954. this.isMonitoring = false;
  23955. this.gamepadEventSupported = 'GamepadEvent' in window;
  23956. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  23957. 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=";
  23958. this._callbackGamepadConnected = ongamedpadconnected;
  23959. if (this.gamepadSupportAvailable) {
  23960. // Checking if the gamepad connected event is supported (like in Firefox)
  23961. if (this.gamepadEventSupported) {
  23962. window.addEventListener('gamepadconnected', function (evt) {
  23963. _this._onGamepadConnected(evt);
  23964. }, false);
  23965. window.addEventListener('gamepaddisconnected', function (evt) {
  23966. _this._onGamepadDisconnected(evt);
  23967. }, false);
  23968. }
  23969. else {
  23970. this._startMonitoringGamepads();
  23971. }
  23972. if (!this.oneGamepadConnected) {
  23973. this._insertGamepadDOMInstructions();
  23974. }
  23975. }
  23976. else {
  23977. this._insertGamepadDOMNotSupported();
  23978. }
  23979. }
  23980. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  23981. Gamepads.gamepadDOMInfo = document.createElement("div");
  23982. var buttonAImage = document.createElement("img");
  23983. buttonAImage.src = this.buttonADataURL;
  23984. var spanMessage = document.createElement("span");
  23985. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  23986. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  23987. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23988. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23989. Gamepads.gamepadDOMInfo.style.width = "100%";
  23990. Gamepads.gamepadDOMInfo.style.height = "48px";
  23991. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23992. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23993. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23994. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23995. buttonAImage.style.position = "relative";
  23996. buttonAImage.style.bottom = "8px";
  23997. spanMessage.style.position = "relative";
  23998. spanMessage.style.fontSize = "32px";
  23999. spanMessage.style.bottom = "32px";
  24000. spanMessage.style.color = "green";
  24001. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24002. };
  24003. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  24004. Gamepads.gamepadDOMInfo = document.createElement("div");
  24005. var spanMessage = document.createElement("span");
  24006. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  24007. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24008. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24009. Gamepads.gamepadDOMInfo.style.width = "100%";
  24010. Gamepads.gamepadDOMInfo.style.height = "40px";
  24011. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24012. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24013. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24014. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24015. spanMessage.style.position = "relative";
  24016. spanMessage.style.fontSize = "32px";
  24017. spanMessage.style.color = "red";
  24018. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24019. };
  24020. Gamepads.prototype.dispose = function () {
  24021. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24022. };
  24023. Gamepads.prototype._onGamepadConnected = function (evt) {
  24024. var newGamepad = this._addNewGamepad(evt.gamepad);
  24025. if (this._callbackGamepadConnected)
  24026. this._callbackGamepadConnected(newGamepad);
  24027. this._startMonitoringGamepads();
  24028. };
  24029. Gamepads.prototype._addNewGamepad = function (gamepad) {
  24030. if (!this.oneGamepadConnected) {
  24031. this.oneGamepadConnected = true;
  24032. if (Gamepads.gamepadDOMInfo) {
  24033. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24034. Gamepads.gamepadDOMInfo = null;
  24035. }
  24036. }
  24037. var newGamepad;
  24038. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  24039. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  24040. }
  24041. else {
  24042. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  24043. }
  24044. this.babylonGamepads.push(newGamepad);
  24045. return newGamepad;
  24046. };
  24047. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  24048. for (var i in this.babylonGamepads) {
  24049. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  24050. this.babylonGamepads.splice(i, 1);
  24051. break;
  24052. }
  24053. }
  24054. // If no gamepads are left, stop the polling loop.
  24055. if (this.babylonGamepads.length == 0) {
  24056. this._stopMonitoringGamepads();
  24057. }
  24058. };
  24059. Gamepads.prototype._startMonitoringGamepads = function () {
  24060. if (!this.isMonitoring) {
  24061. this.isMonitoring = true;
  24062. this._checkGamepadsStatus();
  24063. }
  24064. };
  24065. Gamepads.prototype._stopMonitoringGamepads = function () {
  24066. this.isMonitoring = false;
  24067. };
  24068. Gamepads.prototype._checkGamepadsStatus = function () {
  24069. var _this = this;
  24070. // updating gamepad objects
  24071. this._updateGamepadObjects();
  24072. for (var i in this.babylonGamepads) {
  24073. this.babylonGamepads[i].update();
  24074. }
  24075. if (this.isMonitoring) {
  24076. if (window.requestAnimationFrame) {
  24077. window.requestAnimationFrame(function () {
  24078. _this._checkGamepadsStatus();
  24079. });
  24080. }
  24081. else if (window.mozRequestAnimationFrame) {
  24082. window.mozRequestAnimationFrame(function () {
  24083. _this._checkGamepadsStatus();
  24084. });
  24085. }
  24086. else if (window.webkitRequestAnimationFrame) {
  24087. window.webkitRequestAnimationFrame(function () {
  24088. _this._checkGamepadsStatus();
  24089. });
  24090. }
  24091. }
  24092. };
  24093. // This function is called only on Chrome, which does not yet support
  24094. // connection/disconnection events, but requires you to monitor
  24095. // an array for changes.
  24096. Gamepads.prototype._updateGamepadObjects = function () {
  24097. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  24098. for (var i = 0; i < gamepads.length; i++) {
  24099. if (gamepads[i]) {
  24100. if (!(gamepads[i].index in this.babylonGamepads)) {
  24101. var newGamepad = this._addNewGamepad(gamepads[i]);
  24102. if (this._callbackGamepadConnected) {
  24103. this._callbackGamepadConnected(newGamepad);
  24104. }
  24105. }
  24106. else {
  24107. this.babylonGamepads[i].browserGamepad = gamepads[i];
  24108. }
  24109. }
  24110. }
  24111. };
  24112. return Gamepads;
  24113. })();
  24114. BABYLON.Gamepads = Gamepads;
  24115. var StickValues = (function () {
  24116. function StickValues(x, y) {
  24117. this.x = x;
  24118. this.y = y;
  24119. }
  24120. return StickValues;
  24121. })();
  24122. BABYLON.StickValues = StickValues;
  24123. var Gamepad = (function () {
  24124. function Gamepad(id, index, browserGamepad) {
  24125. this.id = id;
  24126. this.index = index;
  24127. this.browserGamepad = browserGamepad;
  24128. if (this.browserGamepad.axes.length >= 2) {
  24129. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24130. }
  24131. if (this.browserGamepad.axes.length >= 4) {
  24132. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24133. }
  24134. }
  24135. Gamepad.prototype.onleftstickchanged = function (callback) {
  24136. this._onleftstickchanged = callback;
  24137. };
  24138. Gamepad.prototype.onrightstickchanged = function (callback) {
  24139. this._onrightstickchanged = callback;
  24140. };
  24141. Object.defineProperty(Gamepad.prototype, "leftStick", {
  24142. get: function () {
  24143. return this._leftStick;
  24144. },
  24145. set: function (newValues) {
  24146. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  24147. this._onleftstickchanged(newValues);
  24148. }
  24149. this._leftStick = newValues;
  24150. },
  24151. enumerable: true,
  24152. configurable: true
  24153. });
  24154. Object.defineProperty(Gamepad.prototype, "rightStick", {
  24155. get: function () {
  24156. return this._rightStick;
  24157. },
  24158. set: function (newValues) {
  24159. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  24160. this._onrightstickchanged(newValues);
  24161. }
  24162. this._rightStick = newValues;
  24163. },
  24164. enumerable: true,
  24165. configurable: true
  24166. });
  24167. Gamepad.prototype.update = function () {
  24168. if (this._leftStick) {
  24169. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24170. }
  24171. if (this._rightStick) {
  24172. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24173. }
  24174. };
  24175. return Gamepad;
  24176. })();
  24177. BABYLON.Gamepad = Gamepad;
  24178. var GenericPad = (function (_super) {
  24179. __extends(GenericPad, _super);
  24180. function GenericPad(id, index, gamepad) {
  24181. _super.call(this, id, index, gamepad);
  24182. this.id = id;
  24183. this.index = index;
  24184. this.gamepad = gamepad;
  24185. this._buttons = new Array(gamepad.buttons.length);
  24186. }
  24187. GenericPad.prototype.onbuttondown = function (callback) {
  24188. this._onbuttondown = callback;
  24189. };
  24190. GenericPad.prototype.onbuttonup = function (callback) {
  24191. this._onbuttonup = callback;
  24192. };
  24193. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  24194. if (newValue !== currentValue) {
  24195. if (this._onbuttondown && newValue === 1) {
  24196. this._onbuttondown(buttonIndex);
  24197. }
  24198. if (this._onbuttonup && newValue === 0) {
  24199. this._onbuttonup(buttonIndex);
  24200. }
  24201. }
  24202. return newValue;
  24203. };
  24204. GenericPad.prototype.update = function () {
  24205. _super.prototype.update.call(this);
  24206. for (var index = 0; index < this._buttons.length; index++) {
  24207. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  24208. }
  24209. };
  24210. return GenericPad;
  24211. })(Gamepad);
  24212. BABYLON.GenericPad = GenericPad;
  24213. (function (Xbox360Button) {
  24214. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  24215. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  24216. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  24217. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  24218. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  24219. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  24220. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  24221. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  24222. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  24223. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  24224. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  24225. var Xbox360Button = BABYLON.Xbox360Button;
  24226. (function (Xbox360Dpad) {
  24227. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  24228. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  24229. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  24230. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  24231. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  24232. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  24233. var Xbox360Pad = (function (_super) {
  24234. __extends(Xbox360Pad, _super);
  24235. function Xbox360Pad() {
  24236. _super.apply(this, arguments);
  24237. this._leftTrigger = 0;
  24238. this._rightTrigger = 0;
  24239. this._buttonA = 0;
  24240. this._buttonB = 0;
  24241. this._buttonX = 0;
  24242. this._buttonY = 0;
  24243. this._buttonBack = 0;
  24244. this._buttonStart = 0;
  24245. this._buttonLB = 0;
  24246. this._buttonRB = 0;
  24247. this._buttonLeftStick = 0;
  24248. this._buttonRightStick = 0;
  24249. this._dPadUp = 0;
  24250. this._dPadDown = 0;
  24251. this._dPadLeft = 0;
  24252. this._dPadRight = 0;
  24253. }
  24254. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  24255. this._onlefttriggerchanged = callback;
  24256. };
  24257. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  24258. this._onrighttriggerchanged = callback;
  24259. };
  24260. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  24261. get: function () {
  24262. return this._leftTrigger;
  24263. },
  24264. set: function (newValue) {
  24265. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  24266. this._onlefttriggerchanged(newValue);
  24267. }
  24268. this._leftTrigger = newValue;
  24269. },
  24270. enumerable: true,
  24271. configurable: true
  24272. });
  24273. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  24274. get: function () {
  24275. return this._rightTrigger;
  24276. },
  24277. set: function (newValue) {
  24278. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  24279. this._onrighttriggerchanged(newValue);
  24280. }
  24281. this._rightTrigger = newValue;
  24282. },
  24283. enumerable: true,
  24284. configurable: true
  24285. });
  24286. Xbox360Pad.prototype.onbuttondown = function (callback) {
  24287. this._onbuttondown = callback;
  24288. };
  24289. Xbox360Pad.prototype.onbuttonup = function (callback) {
  24290. this._onbuttonup = callback;
  24291. };
  24292. Xbox360Pad.prototype.ondpaddown = function (callback) {
  24293. this._ondpaddown = callback;
  24294. };
  24295. Xbox360Pad.prototype.ondpadup = function (callback) {
  24296. this._ondpadup = callback;
  24297. };
  24298. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  24299. if (newValue !== currentValue) {
  24300. if (this._onbuttondown && newValue === 1) {
  24301. this._onbuttondown(buttonType);
  24302. }
  24303. if (this._onbuttonup && newValue === 0) {
  24304. this._onbuttonup(buttonType);
  24305. }
  24306. }
  24307. return newValue;
  24308. };
  24309. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  24310. if (newValue !== currentValue) {
  24311. if (this._ondpaddown && newValue === 1) {
  24312. this._ondpaddown(buttonType);
  24313. }
  24314. if (this._ondpadup && newValue === 0) {
  24315. this._ondpadup(buttonType);
  24316. }
  24317. }
  24318. return newValue;
  24319. };
  24320. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  24321. get: function () {
  24322. return this._buttonA;
  24323. },
  24324. set: function (value) {
  24325. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  24326. },
  24327. enumerable: true,
  24328. configurable: true
  24329. });
  24330. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  24331. get: function () {
  24332. return this._buttonB;
  24333. },
  24334. set: function (value) {
  24335. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  24336. },
  24337. enumerable: true,
  24338. configurable: true
  24339. });
  24340. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  24341. get: function () {
  24342. return this._buttonX;
  24343. },
  24344. set: function (value) {
  24345. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  24346. },
  24347. enumerable: true,
  24348. configurable: true
  24349. });
  24350. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  24351. get: function () {
  24352. return this._buttonY;
  24353. },
  24354. set: function (value) {
  24355. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  24356. },
  24357. enumerable: true,
  24358. configurable: true
  24359. });
  24360. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  24361. get: function () {
  24362. return this._buttonStart;
  24363. },
  24364. set: function (value) {
  24365. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  24366. },
  24367. enumerable: true,
  24368. configurable: true
  24369. });
  24370. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  24371. get: function () {
  24372. return this._buttonBack;
  24373. },
  24374. set: function (value) {
  24375. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  24376. },
  24377. enumerable: true,
  24378. configurable: true
  24379. });
  24380. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  24381. get: function () {
  24382. return this._buttonLB;
  24383. },
  24384. set: function (value) {
  24385. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  24386. },
  24387. enumerable: true,
  24388. configurable: true
  24389. });
  24390. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  24391. get: function () {
  24392. return this._buttonRB;
  24393. },
  24394. set: function (value) {
  24395. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  24396. },
  24397. enumerable: true,
  24398. configurable: true
  24399. });
  24400. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  24401. get: function () {
  24402. return this._buttonLeftStick;
  24403. },
  24404. set: function (value) {
  24405. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  24406. },
  24407. enumerable: true,
  24408. configurable: true
  24409. });
  24410. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  24411. get: function () {
  24412. return this._buttonRightStick;
  24413. },
  24414. set: function (value) {
  24415. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  24416. },
  24417. enumerable: true,
  24418. configurable: true
  24419. });
  24420. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  24421. get: function () {
  24422. return this._dPadUp;
  24423. },
  24424. set: function (value) {
  24425. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  24426. },
  24427. enumerable: true,
  24428. configurable: true
  24429. });
  24430. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  24431. get: function () {
  24432. return this._dPadDown;
  24433. },
  24434. set: function (value) {
  24435. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  24436. },
  24437. enumerable: true,
  24438. configurable: true
  24439. });
  24440. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  24441. get: function () {
  24442. return this._dPadLeft;
  24443. },
  24444. set: function (value) {
  24445. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  24446. },
  24447. enumerable: true,
  24448. configurable: true
  24449. });
  24450. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  24451. get: function () {
  24452. return this._dPadRight;
  24453. },
  24454. set: function (value) {
  24455. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  24456. },
  24457. enumerable: true,
  24458. configurable: true
  24459. });
  24460. Xbox360Pad.prototype.update = function () {
  24461. _super.prototype.update.call(this);
  24462. this.buttonA = this.browserGamepad.buttons[0].value;
  24463. this.buttonB = this.browserGamepad.buttons[1].value;
  24464. this.buttonX = this.browserGamepad.buttons[2].value;
  24465. this.buttonY = this.browserGamepad.buttons[3].value;
  24466. this.buttonLB = this.browserGamepad.buttons[4].value;
  24467. this.buttonRB = this.browserGamepad.buttons[5].value;
  24468. this.leftTrigger = this.browserGamepad.buttons[6].value;
  24469. this.rightTrigger = this.browserGamepad.buttons[7].value;
  24470. this.buttonBack = this.browserGamepad.buttons[8].value;
  24471. this.buttonStart = this.browserGamepad.buttons[9].value;
  24472. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  24473. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  24474. this.dPadUp = this.browserGamepad.buttons[12].value;
  24475. this.dPadDown = this.browserGamepad.buttons[13].value;
  24476. this.dPadLeft = this.browserGamepad.buttons[14].value;
  24477. this.dPadRight = this.browserGamepad.buttons[15].value;
  24478. };
  24479. return Xbox360Pad;
  24480. })(Gamepad);
  24481. BABYLON.Xbox360Pad = Xbox360Pad;
  24482. })(BABYLON || (BABYLON = {}));
  24483. //# sourceMappingURL=babylon.gamepads.js.map
  24484. var BABYLON;
  24485. (function (BABYLON) {
  24486. // We're mainly based on the logic defined into the FreeCamera code
  24487. var GamepadCamera = (function (_super) {
  24488. __extends(GamepadCamera, _super);
  24489. function GamepadCamera(name, position, scene) {
  24490. var _this = this;
  24491. _super.call(this, name, position, scene);
  24492. this.angularSensibility = 200;
  24493. this.moveSensibility = 75;
  24494. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  24495. _this._onNewGameConnected(gamepad);
  24496. });
  24497. }
  24498. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  24499. // Only the first gamepad can control the camera
  24500. if (gamepad.index === 0) {
  24501. this._gamepad = gamepad;
  24502. }
  24503. };
  24504. GamepadCamera.prototype._checkInputs = function () {
  24505. if (!this._gamepad) {
  24506. return;
  24507. }
  24508. var LSValues = this._gamepad.leftStick;
  24509. var normalizedLX = LSValues.x / this.moveSensibility;
  24510. var normalizedLY = LSValues.y / this.moveSensibility;
  24511. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  24512. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  24513. var RSValues = this._gamepad.rightStick;
  24514. var normalizedRX = RSValues.x / this.angularSensibility;
  24515. var normalizedRY = RSValues.y / this.angularSensibility;
  24516. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  24517. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  24518. ;
  24519. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24520. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  24521. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24522. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  24523. };
  24524. GamepadCamera.prototype.dispose = function () {
  24525. this._gamepads.dispose();
  24526. _super.prototype.dispose.call(this);
  24527. };
  24528. return GamepadCamera;
  24529. })(BABYLON.FreeCamera);
  24530. BABYLON.GamepadCamera = GamepadCamera;
  24531. })(BABYLON || (BABYLON = {}));
  24532. //# sourceMappingURL=babylon.gamepadCamera.js.map
  24533. var BABYLON;
  24534. (function (BABYLON) {
  24535. var LinesMesh = (function (_super) {
  24536. __extends(LinesMesh, _super);
  24537. function LinesMesh(name, scene, updatable) {
  24538. if (updatable === void 0) { updatable = false; }
  24539. _super.call(this, name, scene);
  24540. this.color = new BABYLON.Color3(1, 1, 1);
  24541. this.alpha = 1;
  24542. this._indices = new Array();
  24543. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  24544. attributes: ["position"],
  24545. uniforms: ["worldViewProjection", "color"],
  24546. needAlphaBlending: true
  24547. });
  24548. }
  24549. Object.defineProperty(LinesMesh.prototype, "material", {
  24550. get: function () {
  24551. return this._colorShader;
  24552. },
  24553. enumerable: true,
  24554. configurable: true
  24555. });
  24556. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  24557. get: function () {
  24558. return false;
  24559. },
  24560. enumerable: true,
  24561. configurable: true
  24562. });
  24563. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  24564. get: function () {
  24565. return false;
  24566. },
  24567. enumerable: true,
  24568. configurable: true
  24569. });
  24570. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  24571. var engine = this.getScene().getEngine();
  24572. var indexToBind = this._geometry.getIndexBuffer();
  24573. // VBOs
  24574. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  24575. // Color
  24576. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  24577. };
  24578. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  24579. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24580. return;
  24581. }
  24582. var engine = this.getScene().getEngine();
  24583. // Draw order
  24584. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  24585. };
  24586. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  24587. return null;
  24588. };
  24589. LinesMesh.prototype.dispose = function (doNotRecurse) {
  24590. this._colorShader.dispose();
  24591. _super.prototype.dispose.call(this, doNotRecurse);
  24592. };
  24593. return LinesMesh;
  24594. })(BABYLON.Mesh);
  24595. BABYLON.LinesMesh = LinesMesh;
  24596. })(BABYLON || (BABYLON = {}));
  24597. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  24598. (function (BABYLON) {
  24599. var OutlineRenderer = (function () {
  24600. function OutlineRenderer(scene) {
  24601. this._scene = scene;
  24602. }
  24603. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  24604. if (useOverlay === void 0) { useOverlay = false; }
  24605. var scene = this._scene;
  24606. var engine = this._scene.getEngine();
  24607. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24608. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  24609. return;
  24610. }
  24611. var mesh = subMesh.getRenderingMesh();
  24612. var material = subMesh.getMaterial();
  24613. engine.enableEffect(this._effect);
  24614. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  24615. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  24616. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24617. // Bones
  24618. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  24619. if (useBones) {
  24620. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24621. }
  24622. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  24623. // Alpha test
  24624. if (material && material.needAlphaTesting()) {
  24625. var alphaTexture = material.getAlphaTestTexture();
  24626. this._effect.setTexture("diffuseSampler", alphaTexture);
  24627. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  24628. }
  24629. if (hardwareInstancedRendering) {
  24630. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  24631. }
  24632. else {
  24633. if (batch.renderSelf[subMesh._id]) {
  24634. this._effect.setMatrix("world", mesh.getWorldMatrix());
  24635. // Draw
  24636. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  24637. }
  24638. if (batch.visibleInstances[subMesh._id]) {
  24639. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  24640. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  24641. this._effect.setMatrix("world", instance.getWorldMatrix());
  24642. // Draw
  24643. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  24644. }
  24645. }
  24646. }
  24647. };
  24648. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  24649. var defines = [];
  24650. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  24651. var mesh = subMesh.getMesh();
  24652. var material = subMesh.getMaterial();
  24653. // Alpha test
  24654. if (material && material.needAlphaTesting()) {
  24655. defines.push("#define ALPHATEST");
  24656. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24657. attribs.push(BABYLON.VertexBuffer.UVKind);
  24658. defines.push("#define UV1");
  24659. }
  24660. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24661. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  24662. defines.push("#define UV2");
  24663. }
  24664. }
  24665. // Bones
  24666. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24667. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24668. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24669. defines.push("#define BONES");
  24670. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24671. }
  24672. // Instances
  24673. if (useInstances) {
  24674. defines.push("#define INSTANCES");
  24675. attribs.push("world0");
  24676. attribs.push("world1");
  24677. attribs.push("world2");
  24678. attribs.push("world3");
  24679. }
  24680. // Get correct effect
  24681. var join = defines.join("\n");
  24682. if (this._cachedDefines != join) {
  24683. this._cachedDefines = join;
  24684. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  24685. }
  24686. return this._effect.isReady();
  24687. };
  24688. return OutlineRenderer;
  24689. })();
  24690. BABYLON.OutlineRenderer = OutlineRenderer;
  24691. })(BABYLON || (BABYLON = {}));
  24692. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  24693. (function (BABYLON) {
  24694. var MeshAssetTask = (function () {
  24695. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  24696. this.name = name;
  24697. this.meshesNames = meshesNames;
  24698. this.rootUrl = rootUrl;
  24699. this.sceneFilename = sceneFilename;
  24700. this.isCompleted = false;
  24701. }
  24702. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24703. var _this = this;
  24704. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  24705. _this.loadedMeshes = meshes;
  24706. _this.loadedParticleSystems = particleSystems;
  24707. _this.loadedSkeletons = skeletons;
  24708. _this.isCompleted = true;
  24709. if (_this.onSuccess) {
  24710. _this.onSuccess(_this);
  24711. }
  24712. onSuccess();
  24713. }, null, function () {
  24714. if (_this.onError) {
  24715. _this.onError(_this);
  24716. }
  24717. onError();
  24718. });
  24719. };
  24720. return MeshAssetTask;
  24721. })();
  24722. BABYLON.MeshAssetTask = MeshAssetTask;
  24723. var TextFileAssetTask = (function () {
  24724. function TextFileAssetTask(name, url) {
  24725. this.name = name;
  24726. this.url = url;
  24727. this.isCompleted = false;
  24728. }
  24729. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24730. var _this = this;
  24731. BABYLON.Tools.LoadFile(this.url, function (data) {
  24732. _this.text = data;
  24733. _this.isCompleted = true;
  24734. if (_this.onSuccess) {
  24735. _this.onSuccess(_this);
  24736. }
  24737. onSuccess();
  24738. }, null, scene.database, false, function () {
  24739. if (_this.onError) {
  24740. _this.onError(_this);
  24741. }
  24742. onError();
  24743. });
  24744. };
  24745. return TextFileAssetTask;
  24746. })();
  24747. BABYLON.TextFileAssetTask = TextFileAssetTask;
  24748. var BinaryFileAssetTask = (function () {
  24749. function BinaryFileAssetTask(name, url) {
  24750. this.name = name;
  24751. this.url = url;
  24752. this.isCompleted = false;
  24753. }
  24754. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24755. var _this = this;
  24756. BABYLON.Tools.LoadFile(this.url, function (data) {
  24757. _this.data = data;
  24758. _this.isCompleted = true;
  24759. if (_this.onSuccess) {
  24760. _this.onSuccess(_this);
  24761. }
  24762. onSuccess();
  24763. }, null, scene.database, true, function () {
  24764. if (_this.onError) {
  24765. _this.onError(_this);
  24766. }
  24767. onError();
  24768. });
  24769. };
  24770. return BinaryFileAssetTask;
  24771. })();
  24772. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  24773. var ImageAssetTask = (function () {
  24774. function ImageAssetTask(name, url) {
  24775. this.name = name;
  24776. this.url = url;
  24777. this.isCompleted = false;
  24778. }
  24779. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24780. var _this = this;
  24781. var img = new Image();
  24782. img.onload = function () {
  24783. _this.image = img;
  24784. _this.isCompleted = true;
  24785. if (_this.onSuccess) {
  24786. _this.onSuccess(_this);
  24787. }
  24788. onSuccess();
  24789. };
  24790. img.onerror = function () {
  24791. if (_this.onError) {
  24792. _this.onError(_this);
  24793. }
  24794. onError();
  24795. };
  24796. img.src = this.url;
  24797. };
  24798. return ImageAssetTask;
  24799. })();
  24800. BABYLON.ImageAssetTask = ImageAssetTask;
  24801. var TextureAssetTask = (function () {
  24802. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  24803. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24804. this.name = name;
  24805. this.url = url;
  24806. this.noMipmap = noMipmap;
  24807. this.invertY = invertY;
  24808. this.samplingMode = samplingMode;
  24809. this.isCompleted = false;
  24810. }
  24811. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24812. var _this = this;
  24813. var onload = function () {
  24814. _this.isCompleted = true;
  24815. if (_this.onSuccess) {
  24816. _this.onSuccess(_this);
  24817. }
  24818. onSuccess();
  24819. };
  24820. var onerror = function () {
  24821. if (_this.onError) {
  24822. _this.onError(_this);
  24823. }
  24824. onError();
  24825. };
  24826. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  24827. };
  24828. return TextureAssetTask;
  24829. })();
  24830. BABYLON.TextureAssetTask = TextureAssetTask;
  24831. var AssetsManager = (function () {
  24832. function AssetsManager(scene) {
  24833. this._tasks = new Array();
  24834. this._waitingTasksCount = 0;
  24835. this.useDefaultLoadingScreen = true;
  24836. this._scene = scene;
  24837. }
  24838. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  24839. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  24840. this._tasks.push(task);
  24841. return task;
  24842. };
  24843. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  24844. var task = new TextFileAssetTask(taskName, url);
  24845. this._tasks.push(task);
  24846. return task;
  24847. };
  24848. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  24849. var task = new BinaryFileAssetTask(taskName, url);
  24850. this._tasks.push(task);
  24851. return task;
  24852. };
  24853. AssetsManager.prototype.addImageTask = function (taskName, url) {
  24854. var task = new ImageAssetTask(taskName, url);
  24855. this._tasks.push(task);
  24856. return task;
  24857. };
  24858. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  24859. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24860. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  24861. this._tasks.push(task);
  24862. return task;
  24863. };
  24864. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  24865. this._waitingTasksCount--;
  24866. if (this._waitingTasksCount === 0) {
  24867. if (this.onFinish) {
  24868. this.onFinish(this._tasks);
  24869. }
  24870. this._scene.getEngine().hideLoadingUI();
  24871. }
  24872. };
  24873. AssetsManager.prototype._runTask = function (task) {
  24874. var _this = this;
  24875. task.run(this._scene, function () {
  24876. if (_this.onTaskSuccess) {
  24877. _this.onTaskSuccess(task);
  24878. }
  24879. _this._decreaseWaitingTasksCount();
  24880. }, function () {
  24881. if (_this.onTaskError) {
  24882. _this.onTaskError(task);
  24883. }
  24884. _this._decreaseWaitingTasksCount();
  24885. });
  24886. };
  24887. AssetsManager.prototype.reset = function () {
  24888. this._tasks = new Array();
  24889. return this;
  24890. };
  24891. AssetsManager.prototype.load = function () {
  24892. this._waitingTasksCount = this._tasks.length;
  24893. if (this._waitingTasksCount === 0) {
  24894. if (this.onFinish) {
  24895. this.onFinish(this._tasks);
  24896. }
  24897. return this;
  24898. }
  24899. if (this.useDefaultLoadingScreen) {
  24900. this._scene.getEngine().displayLoadingUI();
  24901. }
  24902. for (var index = 0; index < this._tasks.length; index++) {
  24903. var task = this._tasks[index];
  24904. this._runTask(task);
  24905. }
  24906. return this;
  24907. };
  24908. return AssetsManager;
  24909. })();
  24910. BABYLON.AssetsManager = AssetsManager;
  24911. })(BABYLON || (BABYLON = {}));
  24912. //# sourceMappingURL=babylon.assetsManager.js.map
  24913. var BABYLON;
  24914. (function (BABYLON) {
  24915. var VRDeviceOrientationCamera = (function (_super) {
  24916. __extends(VRDeviceOrientationCamera, _super);
  24917. function VRDeviceOrientationCamera(name, position, scene) {
  24918. _super.call(this, name, position, scene);
  24919. this._alpha = 0;
  24920. this._beta = 0;
  24921. this._gamma = 0;
  24922. }
  24923. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  24924. this._alpha = +evt.alpha | 0;
  24925. this._beta = +evt.beta | 0;
  24926. this._gamma = +evt.gamma | 0;
  24927. if (this._gamma < 0) {
  24928. this._gamma = 90 + this._gamma;
  24929. }
  24930. else {
  24931. // Incline it in the correct angle.
  24932. this._gamma = 270 - this._gamma;
  24933. }
  24934. this.rotation.x = this._gamma / 180.0 * Math.PI;
  24935. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  24936. this.rotation.z = this._beta / 180.0 * Math.PI;
  24937. };
  24938. return VRDeviceOrientationCamera;
  24939. })(BABYLON.OculusCamera);
  24940. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  24941. })(BABYLON || (BABYLON = {}));
  24942. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  24943. var BABYLON;
  24944. (function (BABYLON) {
  24945. var WebVRCamera = (function (_super) {
  24946. __extends(WebVRCamera, _super);
  24947. function WebVRCamera(name, position, scene) {
  24948. _super.call(this, name, position, scene);
  24949. this._hmdDevice = null;
  24950. this._sensorDevice = null;
  24951. this._cacheState = null;
  24952. this._cacheQuaternion = new BABYLON.Quaternion();
  24953. this._cacheRotation = BABYLON.Vector3.Zero();
  24954. this._vrEnabled = false;
  24955. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  24956. }
  24957. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  24958. var size = devices.length;
  24959. var i = 0;
  24960. // Reset devices.
  24961. this._sensorDevice = null;
  24962. this._hmdDevice = null;
  24963. while (i < size && this._hmdDevice === null) {
  24964. if (devices[i] instanceof HMDVRDevice) {
  24965. this._hmdDevice = devices[i];
  24966. }
  24967. i++;
  24968. }
  24969. i = 0;
  24970. while (i < size && this._sensorDevice === null) {
  24971. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  24972. this._sensorDevice = devices[i];
  24973. }
  24974. i++;
  24975. }
  24976. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  24977. };
  24978. WebVRCamera.prototype._update = function () {
  24979. if (this._vrEnabled) {
  24980. this._cacheState = this._sensorDevice.getState();
  24981. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  24982. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  24983. this.rotation.x = -this._cacheRotation.z;
  24984. this.rotation.y = -this._cacheRotation.y;
  24985. this.rotation.z = this._cacheRotation.x;
  24986. }
  24987. _super.prototype._update.call(this);
  24988. };
  24989. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  24990. _super.prototype.attachControl.call(this, element, noPreventDefault);
  24991. if (navigator.getVRDevices) {
  24992. navigator.getVRDevices().then(this._getWebVRDevices);
  24993. }
  24994. else if (navigator.mozGetVRDevices) {
  24995. navigator.mozGetVRDevices(this._getWebVRDevices);
  24996. }
  24997. };
  24998. WebVRCamera.prototype.detachControl = function (element) {
  24999. _super.prototype.detachControl.call(this, element);
  25000. this._vrEnabled = false;
  25001. };
  25002. return WebVRCamera;
  25003. })(BABYLON.OculusCamera);
  25004. BABYLON.WebVRCamera = WebVRCamera;
  25005. })(BABYLON || (BABYLON = {}));
  25006. //# sourceMappingURL=babylon.webVRCamera.js.map
  25007. var BABYLON;
  25008. (function (BABYLON) {
  25009. // Standard optimizations
  25010. var SceneOptimization = (function () {
  25011. function SceneOptimization(priority) {
  25012. if (priority === void 0) { priority = 0; }
  25013. this.priority = priority;
  25014. this.apply = function (scene) {
  25015. return true; // Return true if everything that can be done was applied
  25016. };
  25017. }
  25018. return SceneOptimization;
  25019. })();
  25020. BABYLON.SceneOptimization = SceneOptimization;
  25021. var TextureOptimization = (function (_super) {
  25022. __extends(TextureOptimization, _super);
  25023. function TextureOptimization(priority, maximumSize) {
  25024. var _this = this;
  25025. if (priority === void 0) { priority = 0; }
  25026. if (maximumSize === void 0) { maximumSize = 1024; }
  25027. _super.call(this, priority);
  25028. this.priority = priority;
  25029. this.maximumSize = maximumSize;
  25030. this.apply = function (scene) {
  25031. var allDone = true;
  25032. for (var index = 0; index < scene.textures.length; index++) {
  25033. var texture = scene.textures[index];
  25034. if (!texture.canRescale) {
  25035. continue;
  25036. }
  25037. var currentSize = texture.getSize();
  25038. var maxDimension = Math.max(currentSize.width, currentSize.height);
  25039. if (maxDimension > _this.maximumSize) {
  25040. texture.scale(0.5);
  25041. allDone = false;
  25042. }
  25043. }
  25044. return allDone;
  25045. };
  25046. }
  25047. return TextureOptimization;
  25048. })(SceneOptimization);
  25049. BABYLON.TextureOptimization = TextureOptimization;
  25050. var HardwareScalingOptimization = (function (_super) {
  25051. __extends(HardwareScalingOptimization, _super);
  25052. function HardwareScalingOptimization(priority, maximumScale) {
  25053. var _this = this;
  25054. if (priority === void 0) { priority = 0; }
  25055. if (maximumScale === void 0) { maximumScale = 2; }
  25056. _super.call(this, priority);
  25057. this.priority = priority;
  25058. this.maximumScale = maximumScale;
  25059. this._currentScale = 1;
  25060. this.apply = function (scene) {
  25061. _this._currentScale++;
  25062. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  25063. return _this._currentScale >= _this.maximumScale;
  25064. };
  25065. }
  25066. return HardwareScalingOptimization;
  25067. })(SceneOptimization);
  25068. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  25069. var ShadowsOptimization = (function (_super) {
  25070. __extends(ShadowsOptimization, _super);
  25071. function ShadowsOptimization() {
  25072. _super.apply(this, arguments);
  25073. this.apply = function (scene) {
  25074. scene.shadowsEnabled = false;
  25075. return true;
  25076. };
  25077. }
  25078. return ShadowsOptimization;
  25079. })(SceneOptimization);
  25080. BABYLON.ShadowsOptimization = ShadowsOptimization;
  25081. var PostProcessesOptimization = (function (_super) {
  25082. __extends(PostProcessesOptimization, _super);
  25083. function PostProcessesOptimization() {
  25084. _super.apply(this, arguments);
  25085. this.apply = function (scene) {
  25086. scene.postProcessesEnabled = false;
  25087. return true;
  25088. };
  25089. }
  25090. return PostProcessesOptimization;
  25091. })(SceneOptimization);
  25092. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  25093. var LensFlaresOptimization = (function (_super) {
  25094. __extends(LensFlaresOptimization, _super);
  25095. function LensFlaresOptimization() {
  25096. _super.apply(this, arguments);
  25097. this.apply = function (scene) {
  25098. scene.lensFlaresEnabled = false;
  25099. return true;
  25100. };
  25101. }
  25102. return LensFlaresOptimization;
  25103. })(SceneOptimization);
  25104. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  25105. var ParticlesOptimization = (function (_super) {
  25106. __extends(ParticlesOptimization, _super);
  25107. function ParticlesOptimization() {
  25108. _super.apply(this, arguments);
  25109. this.apply = function (scene) {
  25110. scene.particlesEnabled = false;
  25111. return true;
  25112. };
  25113. }
  25114. return ParticlesOptimization;
  25115. })(SceneOptimization);
  25116. BABYLON.ParticlesOptimization = ParticlesOptimization;
  25117. var RenderTargetsOptimization = (function (_super) {
  25118. __extends(RenderTargetsOptimization, _super);
  25119. function RenderTargetsOptimization() {
  25120. _super.apply(this, arguments);
  25121. this.apply = function (scene) {
  25122. scene.renderTargetsEnabled = false;
  25123. return true;
  25124. };
  25125. }
  25126. return RenderTargetsOptimization;
  25127. })(SceneOptimization);
  25128. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  25129. var MergeMeshesOptimization = (function (_super) {
  25130. __extends(MergeMeshesOptimization, _super);
  25131. function MergeMeshesOptimization() {
  25132. var _this = this;
  25133. _super.apply(this, arguments);
  25134. this._canBeMerged = function (abstractMesh) {
  25135. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  25136. return false;
  25137. }
  25138. var mesh = abstractMesh;
  25139. if (!mesh.isVisible || !mesh.isEnabled()) {
  25140. return false;
  25141. }
  25142. if (mesh.instances.length > 0) {
  25143. return false;
  25144. }
  25145. if (mesh.skeleton || mesh.hasLODLevels) {
  25146. return false;
  25147. }
  25148. return true;
  25149. };
  25150. this.apply = function (scene) {
  25151. var globalPool = scene.meshes.slice(0);
  25152. var globalLength = globalPool.length;
  25153. for (var index = 0; index < globalLength; index++) {
  25154. var currentPool = new Array();
  25155. var current = globalPool[index];
  25156. // Checks
  25157. if (!_this._canBeMerged(current)) {
  25158. continue;
  25159. }
  25160. currentPool.push(current);
  25161. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  25162. var otherMesh = globalPool[subIndex];
  25163. if (!_this._canBeMerged(otherMesh)) {
  25164. continue;
  25165. }
  25166. if (otherMesh.material !== current.material) {
  25167. continue;
  25168. }
  25169. if (otherMesh.checkCollisions !== current.checkCollisions) {
  25170. continue;
  25171. }
  25172. currentPool.push(otherMesh);
  25173. globalLength--;
  25174. globalPool.splice(subIndex, 1);
  25175. subIndex--;
  25176. }
  25177. if (currentPool.length < 2) {
  25178. continue;
  25179. }
  25180. // Merge meshes
  25181. BABYLON.Mesh.MergeMeshes(currentPool);
  25182. }
  25183. return true;
  25184. };
  25185. }
  25186. return MergeMeshesOptimization;
  25187. })(SceneOptimization);
  25188. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  25189. // Options
  25190. var SceneOptimizerOptions = (function () {
  25191. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  25192. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  25193. if (trackerDuration === void 0) { trackerDuration = 2000; }
  25194. this.targetFrameRate = targetFrameRate;
  25195. this.trackerDuration = trackerDuration;
  25196. this.optimizations = new Array();
  25197. }
  25198. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  25199. var result = new SceneOptimizerOptions(targetFrameRate);
  25200. var priority = 0;
  25201. result.optimizations.push(new MergeMeshesOptimization(priority));
  25202. result.optimizations.push(new ShadowsOptimization(priority));
  25203. result.optimizations.push(new LensFlaresOptimization(priority));
  25204. // Next priority
  25205. priority++;
  25206. result.optimizations.push(new PostProcessesOptimization(priority));
  25207. result.optimizations.push(new ParticlesOptimization(priority));
  25208. // Next priority
  25209. priority++;
  25210. result.optimizations.push(new TextureOptimization(priority, 1024));
  25211. return result;
  25212. };
  25213. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  25214. var result = new SceneOptimizerOptions(targetFrameRate);
  25215. var priority = 0;
  25216. result.optimizations.push(new MergeMeshesOptimization(priority));
  25217. result.optimizations.push(new ShadowsOptimization(priority));
  25218. result.optimizations.push(new LensFlaresOptimization(priority));
  25219. // Next priority
  25220. priority++;
  25221. result.optimizations.push(new PostProcessesOptimization(priority));
  25222. result.optimizations.push(new ParticlesOptimization(priority));
  25223. // Next priority
  25224. priority++;
  25225. result.optimizations.push(new TextureOptimization(priority, 512));
  25226. // Next priority
  25227. priority++;
  25228. result.optimizations.push(new RenderTargetsOptimization(priority));
  25229. // Next priority
  25230. priority++;
  25231. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  25232. return result;
  25233. };
  25234. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  25235. var result = new SceneOptimizerOptions(targetFrameRate);
  25236. var priority = 0;
  25237. result.optimizations.push(new MergeMeshesOptimization(priority));
  25238. result.optimizations.push(new ShadowsOptimization(priority));
  25239. result.optimizations.push(new LensFlaresOptimization(priority));
  25240. // Next priority
  25241. priority++;
  25242. result.optimizations.push(new PostProcessesOptimization(priority));
  25243. result.optimizations.push(new ParticlesOptimization(priority));
  25244. // Next priority
  25245. priority++;
  25246. result.optimizations.push(new TextureOptimization(priority, 256));
  25247. // Next priority
  25248. priority++;
  25249. result.optimizations.push(new RenderTargetsOptimization(priority));
  25250. // Next priority
  25251. priority++;
  25252. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  25253. return result;
  25254. };
  25255. return SceneOptimizerOptions;
  25256. })();
  25257. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  25258. // Scene optimizer tool
  25259. var SceneOptimizer = (function () {
  25260. function SceneOptimizer() {
  25261. }
  25262. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  25263. // TODO: add an epsilon
  25264. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  25265. if (onSuccess) {
  25266. onSuccess();
  25267. }
  25268. return;
  25269. }
  25270. // Apply current level of optimizations
  25271. var allDone = true;
  25272. var noOptimizationApplied = true;
  25273. for (var index = 0; index < options.optimizations.length; index++) {
  25274. var optimization = options.optimizations[index];
  25275. if (optimization.priority === currentPriorityLevel) {
  25276. noOptimizationApplied = false;
  25277. allDone = allDone && optimization.apply(scene);
  25278. }
  25279. }
  25280. // If no optimization was applied, this is a failure :(
  25281. if (noOptimizationApplied) {
  25282. if (onFailure) {
  25283. onFailure();
  25284. }
  25285. return;
  25286. }
  25287. // If all optimizations were done, move to next level
  25288. if (allDone) {
  25289. currentPriorityLevel++;
  25290. }
  25291. // Let's the system running for a specific amount of time before checking FPS
  25292. scene.executeWhenReady(function () {
  25293. setTimeout(function () {
  25294. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  25295. }, options.trackerDuration);
  25296. });
  25297. };
  25298. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  25299. if (!options) {
  25300. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  25301. }
  25302. // Let's the system running for a specific amount of time before checking FPS
  25303. scene.executeWhenReady(function () {
  25304. setTimeout(function () {
  25305. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  25306. }, options.trackerDuration);
  25307. });
  25308. };
  25309. return SceneOptimizer;
  25310. })();
  25311. BABYLON.SceneOptimizer = SceneOptimizer;
  25312. })(BABYLON || (BABYLON = {}));
  25313. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  25314. (function (BABYLON) {
  25315. var Internals;
  25316. (function (Internals) {
  25317. var MeshLODLevel = (function () {
  25318. function MeshLODLevel(distance, mesh) {
  25319. this.distance = distance;
  25320. this.mesh = mesh;
  25321. }
  25322. return MeshLODLevel;
  25323. })();
  25324. Internals.MeshLODLevel = MeshLODLevel;
  25325. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25326. })(BABYLON || (BABYLON = {}));
  25327. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  25328. (function (BABYLON) {
  25329. var AudioEngine = (function () {
  25330. function AudioEngine() {
  25331. this.audioContext = null;
  25332. this.canUseWebAudio = false;
  25333. this.WarnedWebAudioUnsupported = false;
  25334. try {
  25335. if (typeof AudioContext !== 'undefined') {
  25336. this.audioContext = new AudioContext();
  25337. this.canUseWebAudio = true;
  25338. }
  25339. else if (typeof webkitAudioContext !== 'undefined') {
  25340. this.audioContext = new webkitAudioContext();
  25341. this.canUseWebAudio = true;
  25342. }
  25343. }
  25344. catch (e) {
  25345. this.canUseWebAudio = false;
  25346. BABYLON.Tools.Error("Web Audio: " + e.message);
  25347. }
  25348. // create a global volume gain node
  25349. if (this.canUseWebAudio) {
  25350. this.masterGain = this.audioContext.createGain();
  25351. this.masterGain.gain.value = 1;
  25352. this.masterGain.connect(this.audioContext.destination);
  25353. }
  25354. }
  25355. AudioEngine.prototype.dispose = function () {
  25356. if (this.canUseWebAudio) {
  25357. if (this._connectedAnalyser) {
  25358. this._connectedAnalyser.stopDebugCanvas();
  25359. this._connectedAnalyser.dispose();
  25360. this.masterGain.disconnect();
  25361. this.masterGain.connect(this.audioContext.destination);
  25362. this._connectedAnalyser = null;
  25363. }
  25364. this.masterGain.gain.value = 1;
  25365. }
  25366. this.WarnedWebAudioUnsupported = false;
  25367. };
  25368. AudioEngine.prototype.getGlobalVolume = function () {
  25369. if (this.canUseWebAudio) {
  25370. return this.masterGain.gain.value;
  25371. }
  25372. else {
  25373. return -1;
  25374. }
  25375. };
  25376. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  25377. if (this.canUseWebAudio) {
  25378. this.masterGain.gain.value = newVolume;
  25379. }
  25380. };
  25381. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  25382. if (this._connectedAnalyser) {
  25383. this._connectedAnalyser.stopDebugCanvas();
  25384. }
  25385. this._connectedAnalyser = analyser;
  25386. if (this.canUseWebAudio) {
  25387. this.masterGain.disconnect();
  25388. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  25389. }
  25390. };
  25391. return AudioEngine;
  25392. })();
  25393. BABYLON.AudioEngine = AudioEngine;
  25394. })(BABYLON || (BABYLON = {}));
  25395. //# sourceMappingURL=babylon.audioengine.js.mapvar BABYLON;
  25396. (function (BABYLON) {
  25397. var Sound = (function () {
  25398. /**
  25399. * Create a sound and attach it to a scene
  25400. * @param name Name of your sound
  25401. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  25402. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  25403. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  25404. */
  25405. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  25406. var _this = this;
  25407. this.autoplay = false;
  25408. this.loop = false;
  25409. this.useCustomAttenuation = false;
  25410. this.spatialSound = false;
  25411. this.refDistance = 1;
  25412. this.rolloffFactor = 1;
  25413. this.maxDistance = 100;
  25414. this.distanceModel = "linear";
  25415. this.panningModel = "HRTF";
  25416. this._playbackRate = 1;
  25417. this._startTime = 0;
  25418. this._startOffset = 0;
  25419. this._position = BABYLON.Vector3.Zero();
  25420. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  25421. this._volume = 1;
  25422. this._isLoaded = false;
  25423. this._isReadyToPlay = false;
  25424. this._isPlaying = false;
  25425. this._isDirectional = false;
  25426. // Used if you'd like to create a directional sound.
  25427. // If not set, the sound will be omnidirectional
  25428. this._coneInnerAngle = 360;
  25429. this._coneOuterAngle = 360;
  25430. this._coneOuterGain = 0;
  25431. this.name = name;
  25432. this._scene = scene;
  25433. this._readyToPlayCallback = readyToPlayCallback;
  25434. // Default custom attenuation function is a linear attenuation
  25435. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  25436. if (currentDistance < maxDistance) {
  25437. return currentVolume * (1 - currentDistance / maxDistance);
  25438. }
  25439. else {
  25440. return 0;
  25441. }
  25442. };
  25443. if (options) {
  25444. this.autoplay = options.autoplay || false;
  25445. this.loop = options.loop || false;
  25446. // if volume === 0, we need another way to check this option
  25447. if (options.volume !== undefined) {
  25448. this._volume = options.volume;
  25449. }
  25450. this.spatialSound = options.spatialSound || false;
  25451. this.maxDistance = options.maxDistance || 100;
  25452. this.useCustomAttenuation = options.useCustomAttenuation || false;
  25453. this.rolloffFactor = options.rolloffFactor || 1;
  25454. this.refDistance = options.refDistance || 1;
  25455. this.distanceModel = options.distanceModel || "linear";
  25456. this.panningModel = options.panningModel || "HRTF";
  25457. this._playbackRate = options.playbackRate || 1;
  25458. }
  25459. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25460. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  25461. this._soundGain.gain.value = this._volume;
  25462. this._inputAudioNode = this._soundGain;
  25463. this._ouputAudioNode = this._soundGain;
  25464. if (this.spatialSound) {
  25465. this._createSpatialParameters();
  25466. }
  25467. this._scene.mainSoundTrack.AddSound(this);
  25468. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  25469. if (urlOrArrayBuffer) {
  25470. // If it's an URL
  25471. if (typeof (urlOrArrayBuffer) === "string") {
  25472. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  25473. _this._soundLoaded(data);
  25474. }, null, null, true);
  25475. }
  25476. else {
  25477. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  25478. this._soundLoaded(urlOrArrayBuffer);
  25479. }
  25480. else {
  25481. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  25482. }
  25483. }
  25484. }
  25485. }
  25486. else {
  25487. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  25488. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  25489. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  25490. }
  25491. }
  25492. }
  25493. Sound.prototype.dispose = function () {
  25494. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  25495. if (this._isPlaying) {
  25496. this.stop();
  25497. }
  25498. this._isReadyToPlay = false;
  25499. if (this.soundTrackId === -1) {
  25500. this._scene.mainSoundTrack.RemoveSound(this);
  25501. }
  25502. else {
  25503. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  25504. }
  25505. this._soundGain.disconnect();
  25506. this._soundSource.disconnect();
  25507. if (this._soundPanner) {
  25508. this._soundPanner.disconnect();
  25509. this._soundPanner = null;
  25510. }
  25511. this._audioBuffer = null;
  25512. this._soundGain = null;
  25513. this._soundSource = null;
  25514. if (this._connectedMesh) {
  25515. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  25516. this._connectedMesh = null;
  25517. }
  25518. }
  25519. };
  25520. Sound.prototype._soundLoaded = function (audioData) {
  25521. var _this = this;
  25522. this._isLoaded = true;
  25523. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  25524. _this._audioBuffer = buffer;
  25525. _this._isReadyToPlay = true;
  25526. if (_this.autoplay) {
  25527. _this.play();
  25528. }
  25529. if (_this._readyToPlayCallback) {
  25530. _this._readyToPlayCallback();
  25531. }
  25532. }, function (error) {
  25533. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  25534. });
  25535. };
  25536. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  25537. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25538. this._audioBuffer = audioBuffer;
  25539. this._isReadyToPlay = true;
  25540. }
  25541. };
  25542. Sound.prototype.updateOptions = function (options) {
  25543. if (options) {
  25544. this.loop = options.loop || this.loop;
  25545. this.maxDistance = options.maxDistance || this.maxDistance;
  25546. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  25547. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  25548. this.refDistance = options.refDistance || this.refDistance;
  25549. this.distanceModel = options.distanceModel || this.distanceModel;
  25550. this.panningModel = options.panningModel || this.panningModel;
  25551. this._playbackRate = options.playbackRate || this._playbackRate;
  25552. }
  25553. };
  25554. Sound.prototype._createSpatialParameters = function () {
  25555. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25556. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  25557. if (this.useCustomAttenuation) {
  25558. // Tricks to disable in a way embedded Web Audio attenuation
  25559. this._soundPanner.distanceModel = "linear";
  25560. this._soundPanner.maxDistance = Number.MAX_VALUE;
  25561. this._soundPanner.refDistance = 1;
  25562. this._soundPanner.rolloffFactor = 1;
  25563. this._soundPanner.panningModel = "HRTF";
  25564. }
  25565. else {
  25566. this._soundPanner.distanceModel = this.distanceModel;
  25567. this._soundPanner.maxDistance = this.maxDistance;
  25568. this._soundPanner.refDistance = this.refDistance;
  25569. this._soundPanner.rolloffFactor = this.rolloffFactor;
  25570. this._soundPanner.panningModel = this.panningModel;
  25571. }
  25572. this._soundPanner.connect(this._ouputAudioNode);
  25573. this._inputAudioNode = this._soundPanner;
  25574. }
  25575. };
  25576. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  25577. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25578. this._ouputAudioNode.disconnect();
  25579. this._ouputAudioNode.connect(soundTrackAudioNode);
  25580. }
  25581. };
  25582. /**
  25583. * Transform this sound into a directional source
  25584. * @param coneInnerAngle Size of the inner cone in degree
  25585. * @param coneOuterAngle Size of the outer cone in degree
  25586. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  25587. */
  25588. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25589. if (coneOuterAngle < coneInnerAngle) {
  25590. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  25591. return;
  25592. }
  25593. this._coneInnerAngle = coneInnerAngle;
  25594. this._coneOuterAngle = coneOuterAngle;
  25595. this._coneOuterGain = coneOuterGain;
  25596. this._isDirectional = true;
  25597. if (this._isPlaying && this.loop) {
  25598. this.stop();
  25599. this.play();
  25600. }
  25601. };
  25602. Sound.prototype.setPosition = function (newPosition) {
  25603. this._position = newPosition;
  25604. if (this._isPlaying && this.spatialSound) {
  25605. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25606. }
  25607. };
  25608. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  25609. this._localDirection = newLocalDirection;
  25610. if (this._connectedMesh && this._isPlaying) {
  25611. this._updateDirection();
  25612. }
  25613. };
  25614. Sound.prototype._updateDirection = function () {
  25615. var mat = this._connectedMesh.getWorldMatrix();
  25616. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  25617. direction.normalize();
  25618. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  25619. };
  25620. Sound.prototype.updateDistanceFromListener = function () {
  25621. if (this._connectedMesh && this.useCustomAttenuation) {
  25622. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  25623. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  25624. }
  25625. };
  25626. Sound.prototype.setAttenuationFunction = function (callback) {
  25627. this._customAttenuationFunction = callback;
  25628. };
  25629. /**
  25630. * Play the sound
  25631. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  25632. */
  25633. Sound.prototype.play = function (time) {
  25634. if (this._isReadyToPlay) {
  25635. try {
  25636. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  25637. if (!this._soundSource) {
  25638. if (this.spatialSound) {
  25639. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25640. if (this._isDirectional) {
  25641. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  25642. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  25643. this._soundPanner.coneOuterGain = this._coneOuterGain;
  25644. if (this._connectedMesh) {
  25645. this._updateDirection();
  25646. }
  25647. else {
  25648. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  25649. }
  25650. }
  25651. }
  25652. }
  25653. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  25654. this._soundSource.buffer = this._audioBuffer;
  25655. this._soundSource.connect(this._inputAudioNode);
  25656. this._soundSource.loop = this.loop;
  25657. this._soundSource.playbackRate.value = this._playbackRate;
  25658. this._startTime = startTime;
  25659. if (this.onended) {
  25660. this._soundSource.onended = this.onended;
  25661. }
  25662. this._soundSource.start(startTime, this._startOffset % this._soundSource.buffer.duration);
  25663. this._isPlaying = true;
  25664. }
  25665. catch (ex) {
  25666. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  25667. }
  25668. }
  25669. };
  25670. /**
  25671. * Stop the sound
  25672. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  25673. */
  25674. Sound.prototype.stop = function (time) {
  25675. if (this._isPlaying) {
  25676. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  25677. this._soundSource.stop(stopTime);
  25678. this._isPlaying = false;
  25679. }
  25680. };
  25681. Sound.prototype.pause = function () {
  25682. if (this._isPlaying) {
  25683. this._soundSource.stop(0);
  25684. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  25685. }
  25686. };
  25687. Sound.prototype.setVolume = function (newVolume) {
  25688. this._volume = newVolume;
  25689. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25690. this._soundGain.gain.value = newVolume;
  25691. }
  25692. };
  25693. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  25694. this._playbackRate = newPlaybackRate;
  25695. if (this._isPlaying) {
  25696. this._soundSource.playbackRate.value = this._playbackRate;
  25697. }
  25698. };
  25699. Sound.prototype.getVolume = function () {
  25700. return this._volume;
  25701. };
  25702. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  25703. var _this = this;
  25704. this._connectedMesh = meshToConnectTo;
  25705. if (!this.spatialSound) {
  25706. this._createSpatialParameters();
  25707. this.spatialSound = true;
  25708. if (this._isPlaying && this.loop) {
  25709. this.stop();
  25710. this.play();
  25711. }
  25712. }
  25713. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  25714. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  25715. };
  25716. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  25717. this.setPosition(connectedMesh.position);
  25718. if (this._isDirectional && this._isPlaying) {
  25719. this._updateDirection();
  25720. }
  25721. };
  25722. return Sound;
  25723. })();
  25724. BABYLON.Sound = Sound;
  25725. })(BABYLON || (BABYLON = {}));
  25726. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  25727. (function (BABYLON) {
  25728. var SoundTrack = (function () {
  25729. function SoundTrack(scene, options) {
  25730. this.id = -1;
  25731. this._isMainTrack = false;
  25732. this._scene = scene;
  25733. this._audioEngine = BABYLON.Engine.audioEngine;
  25734. this.soundCollection = new Array();
  25735. if (this._audioEngine.canUseWebAudio) {
  25736. this._trackGain = this._audioEngine.audioContext.createGain();
  25737. this._trackGain.connect(this._audioEngine.masterGain);
  25738. if (options) {
  25739. if (options.volume) {
  25740. this._trackGain.gain.value = options.volume;
  25741. }
  25742. if (options.mainTrack) {
  25743. this._isMainTrack = options.mainTrack;
  25744. }
  25745. }
  25746. }
  25747. if (!this._isMainTrack) {
  25748. this._scene.soundTracks.push(this);
  25749. this.id = this._scene.soundTracks.length - 1;
  25750. }
  25751. }
  25752. SoundTrack.prototype.dispose = function () {
  25753. if (this._audioEngine.canUseWebAudio) {
  25754. if (this._connectedAnalyser) {
  25755. this._connectedAnalyser.stopDebugCanvas();
  25756. }
  25757. while (this.soundCollection.length) {
  25758. this.soundCollection[0].dispose();
  25759. }
  25760. this._trackGain.disconnect();
  25761. this._trackGain = null;
  25762. }
  25763. };
  25764. SoundTrack.prototype.AddSound = function (sound) {
  25765. sound.connectToSoundTrackAudioNode(this._trackGain);
  25766. if (sound.soundTrackId) {
  25767. if (sound.soundTrackId === -1) {
  25768. this._scene.mainSoundTrack.RemoveSound(sound);
  25769. }
  25770. else {
  25771. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  25772. }
  25773. }
  25774. this.soundCollection.push(sound);
  25775. sound.soundTrackId = this.id;
  25776. };
  25777. SoundTrack.prototype.RemoveSound = function (sound) {
  25778. var index = this.soundCollection.indexOf(sound);
  25779. if (index !== -1) {
  25780. this.soundCollection.splice(index, 1);
  25781. }
  25782. };
  25783. SoundTrack.prototype.setVolume = function (newVolume) {
  25784. if (this._audioEngine.canUseWebAudio) {
  25785. this._trackGain.gain.value = newVolume;
  25786. }
  25787. };
  25788. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  25789. if (this._connectedAnalyser) {
  25790. this._connectedAnalyser.stopDebugCanvas();
  25791. }
  25792. this._connectedAnalyser = analyser;
  25793. if (this._audioEngine.canUseWebAudio) {
  25794. this._trackGain.disconnect();
  25795. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  25796. }
  25797. };
  25798. return SoundTrack;
  25799. })();
  25800. BABYLON.SoundTrack = SoundTrack;
  25801. })(BABYLON || (BABYLON = {}));
  25802. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  25803. (function (BABYLON) {
  25804. var DebugLayer = (function () {
  25805. function DebugLayer(scene) {
  25806. var _this = this;
  25807. this._enabled = false;
  25808. this._labelsEnabled = false;
  25809. this._displayStatistics = true;
  25810. this._displayTree = false;
  25811. this._displayLogs = false;
  25812. this._identityMatrix = BABYLON.Matrix.Identity();
  25813. this.axisRatio = 0.02;
  25814. this.accentColor = "orange";
  25815. this._scene = scene;
  25816. this._syncPositions = function () {
  25817. var engine = _this._scene.getEngine();
  25818. var canvasRect = engine.getRenderingCanvasClientRect();
  25819. if (_this._showUI) {
  25820. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  25821. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  25822. _this._statsDiv.style.width = "400px";
  25823. _this._statsDiv.style.height = "auto";
  25824. _this._statsSubsetDiv.style.maxHeight = "240px";
  25825. _this._optionsDiv.style.left = "0px";
  25826. _this._optionsDiv.style.top = "10px";
  25827. _this._optionsDiv.style.width = "200px";
  25828. _this._optionsDiv.style.height = "auto";
  25829. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  25830. _this._logDiv.style.left = "0px";
  25831. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  25832. _this._logDiv.style.width = "600px";
  25833. _this._logDiv.style.height = "160px";
  25834. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  25835. _this._treeDiv.style.top = "10px";
  25836. _this._treeDiv.style.width = "300px";
  25837. _this._treeDiv.style.height = "auto";
  25838. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  25839. }
  25840. _this._globalDiv.style.left = canvasRect.left + "px";
  25841. _this._globalDiv.style.top = canvasRect.top + "px";
  25842. _this._drawingCanvas.style.left = "0px";
  25843. _this._drawingCanvas.style.top = "0px";
  25844. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  25845. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  25846. var devicePixelRatio = window.devicePixelRatio || 1;
  25847. var context = _this._drawingContext;
  25848. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  25849. _this._ratio = devicePixelRatio / backingStoreRatio;
  25850. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  25851. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  25852. };
  25853. this._onCanvasClick = function (evt) {
  25854. _this._clickPosition = {
  25855. x: evt.clientX * _this._ratio,
  25856. y: evt.clientY * _this._ratio
  25857. };
  25858. };
  25859. this._syncData = function () {
  25860. if (_this._showUI) {
  25861. if (_this._displayStatistics) {
  25862. _this._displayStats();
  25863. _this._statsDiv.style.display = "";
  25864. }
  25865. else {
  25866. _this._statsDiv.style.display = "none";
  25867. }
  25868. if (_this._displayLogs) {
  25869. _this._logDiv.style.display = "";
  25870. }
  25871. else {
  25872. _this._logDiv.style.display = "none";
  25873. }
  25874. if (_this._displayTree) {
  25875. _this._treeDiv.style.display = "";
  25876. if (_this._needToRefreshMeshesTree) {
  25877. _this._needToRefreshMeshesTree = false;
  25878. _this._refreshMeshesTreeContent();
  25879. }
  25880. }
  25881. else {
  25882. _this._treeDiv.style.display = "none";
  25883. }
  25884. }
  25885. if (_this._labelsEnabled || !_this._showUI) {
  25886. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  25887. var engine = _this._scene.getEngine();
  25888. var viewport = _this._scene.activeCamera.viewport;
  25889. var globalViewport = viewport.toGlobal(engine);
  25890. // Meshes
  25891. var meshes = _this._scene.getActiveMeshes();
  25892. for (var index = 0; index < meshes.length; index++) {
  25893. var mesh = meshes.data[index];
  25894. var position = mesh.getBoundingInfo().boundingSphere.center;
  25895. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25896. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  25897. _this._renderAxis(projectedPosition, mesh, globalViewport);
  25898. }
  25899. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  25900. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  25901. mesh.renderOverlay = !mesh.renderOverlay;
  25902. }, function () {
  25903. return mesh.renderOverlay ? 'red' : 'black';
  25904. });
  25905. }
  25906. }
  25907. // Cameras
  25908. var cameras = _this._scene.cameras;
  25909. for (index = 0; index < cameras.length; index++) {
  25910. var camera = cameras[index];
  25911. if (camera === _this._scene.activeCamera) {
  25912. continue;
  25913. }
  25914. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25915. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  25916. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  25917. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  25918. _this._scene.activeCamera = camera;
  25919. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  25920. }, function () {
  25921. return "purple";
  25922. });
  25923. }
  25924. }
  25925. // Lights
  25926. var lights = _this._scene.lights;
  25927. for (index = 0; index < lights.length; index++) {
  25928. var light = lights[index];
  25929. if (light.position) {
  25930. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  25931. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  25932. _this._renderLabel(light.name, projectedPosition, -20, function () {
  25933. light.setEnabled(!light.isEnabled());
  25934. }, function () {
  25935. return light.isEnabled() ? "orange" : "gray";
  25936. });
  25937. }
  25938. }
  25939. }
  25940. }
  25941. _this._clickPosition = undefined;
  25942. };
  25943. }
  25944. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  25945. while (this._treeSubsetDiv.hasChildNodes()) {
  25946. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  25947. }
  25948. // Add meshes
  25949. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  25950. sortedArray.sort(function (a, b) {
  25951. if (a.name === b.name) {
  25952. return 0;
  25953. }
  25954. return (a.name > b.name) ? 1 : -1;
  25955. });
  25956. for (var index = 0; index < sortedArray.length; index++) {
  25957. var mesh = sortedArray[index];
  25958. if (!mesh.isEnabled()) {
  25959. continue;
  25960. }
  25961. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  25962. m.isVisible = element.checked;
  25963. }, mesh);
  25964. }
  25965. };
  25966. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  25967. this._drawingContext.beginPath();
  25968. this._drawingContext.moveTo(zero.x, zero.y);
  25969. this._drawingContext.lineTo(unit.x, unit.y);
  25970. this._drawingContext.strokeStyle = color;
  25971. this._drawingContext.lineWidth = 4;
  25972. this._drawingContext.stroke();
  25973. this._drawingContext.font = "normal 14px Segoe UI";
  25974. this._drawingContext.fillStyle = color;
  25975. this._drawingContext.fillText(label, unitText.x, unitText.y);
  25976. };
  25977. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  25978. var position = mesh.getBoundingInfo().boundingSphere.center;
  25979. var worldMatrix = mesh.getWorldMatrix();
  25980. 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());
  25981. var unit = (unprojectedVector.subtract(position)).length();
  25982. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25983. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25984. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  25985. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25986. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25987. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  25988. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25989. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25990. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  25991. };
  25992. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  25993. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  25994. this._drawingContext.font = "normal 12px Segoe UI";
  25995. var textMetrics = this._drawingContext.measureText(text);
  25996. var centerX = projectedPosition.x - textMetrics.width / 2;
  25997. var centerY = projectedPosition.y;
  25998. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  25999. onClick();
  26000. }
  26001. this._drawingContext.beginPath();
  26002. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26003. this._drawingContext.fillStyle = getFillStyle();
  26004. this._drawingContext.globalAlpha = 0.5;
  26005. this._drawingContext.fill();
  26006. this._drawingContext.globalAlpha = 1.0;
  26007. this._drawingContext.strokeStyle = '#FFFFFF';
  26008. this._drawingContext.lineWidth = 1;
  26009. this._drawingContext.stroke();
  26010. this._drawingContext.fillStyle = "#FFFFFF";
  26011. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26012. this._drawingContext.beginPath();
  26013. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26014. this._drawingContext.fill();
  26015. }
  26016. };
  26017. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26018. if (!this._clickPosition) {
  26019. return false;
  26020. }
  26021. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26022. return false;
  26023. }
  26024. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26025. return false;
  26026. }
  26027. return true;
  26028. };
  26029. DebugLayer.prototype.isVisible = function () {
  26030. return this._enabled;
  26031. };
  26032. DebugLayer.prototype.hide = function () {
  26033. if (!this._enabled) {
  26034. return;
  26035. }
  26036. this._enabled = false;
  26037. var engine = this._scene.getEngine();
  26038. this._scene.unregisterAfterRender(this._syncData);
  26039. document.body.removeChild(this._globalDiv);
  26040. window.removeEventListener("resize", this._syncPositions);
  26041. this._scene.forceShowBoundingBoxes = false;
  26042. this._scene.forceWireframe = false;
  26043. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26044. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26045. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26046. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26047. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26048. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26049. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26050. this._scene.shadowsEnabled = true;
  26051. this._scene.particlesEnabled = true;
  26052. this._scene.postProcessesEnabled = true;
  26053. this._scene.collisionsEnabled = true;
  26054. this._scene.lightsEnabled = true;
  26055. this._scene.texturesEnabled = true;
  26056. this._scene.lensFlaresEnabled = true;
  26057. this._scene.proceduralTexturesEnabled = true;
  26058. this._scene.renderTargetsEnabled = true;
  26059. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26060. };
  26061. DebugLayer.prototype.show = function (showUI) {
  26062. if (showUI === void 0) { showUI = true; }
  26063. if (this._enabled) {
  26064. return;
  26065. }
  26066. this._enabled = true;
  26067. this._showUI = showUI;
  26068. var engine = this._scene.getEngine();
  26069. this._globalDiv = document.createElement("div");
  26070. document.body.appendChild(this._globalDiv);
  26071. this._generateDOMelements();
  26072. window.addEventListener("resize", this._syncPositions);
  26073. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26074. this._syncPositions();
  26075. this._scene.registerAfterRender(this._syncData);
  26076. };
  26077. DebugLayer.prototype._clearLabels = function () {
  26078. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26079. for (var index = 0; index < this._scene.meshes.length; index++) {
  26080. var mesh = this._scene.meshes[index];
  26081. mesh.renderOverlay = false;
  26082. }
  26083. };
  26084. DebugLayer.prototype._generateheader = function (root, text) {
  26085. var header = document.createElement("div");
  26086. header.innerHTML = text + "&nbsp;";
  26087. header.style.textAlign = "right";
  26088. header.style.width = "100%";
  26089. header.style.color = "white";
  26090. header.style.backgroundColor = "Black";
  26091. header.style.padding = "5px 5px 4px 0px";
  26092. header.style.marginLeft = "-5px";
  26093. header.style.fontWeight = "bold";
  26094. root.appendChild(header);
  26095. };
  26096. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26097. var label = document.createElement("label");
  26098. label.innerHTML = title;
  26099. label.style.color = color;
  26100. root.appendChild(label);
  26101. root.appendChild(document.createElement("br"));
  26102. };
  26103. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26104. if (tag === void 0) { tag = null; }
  26105. var label = document.createElement("label");
  26106. var boundingBoxesCheckbox = document.createElement("input");
  26107. boundingBoxesCheckbox.type = "checkbox";
  26108. boundingBoxesCheckbox.checked = initialState;
  26109. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26110. task(evt.target, tag);
  26111. });
  26112. label.appendChild(boundingBoxesCheckbox);
  26113. var container = document.createElement("span");
  26114. var leftPart = document.createElement("span");
  26115. var rightPart = document.createElement("span");
  26116. rightPart.style.cssFloat = "right";
  26117. leftPart.innerHTML = leftTitle;
  26118. rightPart.innerHTML = rightTitle;
  26119. rightPart.style.fontSize = "12px";
  26120. rightPart.style.maxWidth = "200px";
  26121. container.appendChild(leftPart);
  26122. container.appendChild(rightPart);
  26123. label.appendChild(container);
  26124. root.appendChild(label);
  26125. root.appendChild(document.createElement("br"));
  26126. };
  26127. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  26128. if (tag === void 0) { tag = null; }
  26129. var label = document.createElement("label");
  26130. var boundingBoxesCheckbox = document.createElement("input");
  26131. boundingBoxesCheckbox.type = "checkbox";
  26132. boundingBoxesCheckbox.checked = initialState;
  26133. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26134. task(evt.target, tag);
  26135. });
  26136. label.appendChild(boundingBoxesCheckbox);
  26137. label.appendChild(document.createTextNode(title));
  26138. root.appendChild(label);
  26139. root.appendChild(document.createElement("br"));
  26140. };
  26141. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  26142. if (tag === void 0) { tag = null; }
  26143. var label = document.createElement("label");
  26144. var boundingBoxesRadio = document.createElement("input");
  26145. boundingBoxesRadio.type = "radio";
  26146. boundingBoxesRadio.name = name;
  26147. boundingBoxesRadio.checked = initialState;
  26148. boundingBoxesRadio.addEventListener("change", function (evt) {
  26149. task(evt.target, tag);
  26150. });
  26151. label.appendChild(boundingBoxesRadio);
  26152. label.appendChild(document.createTextNode(title));
  26153. root.appendChild(label);
  26154. root.appendChild(document.createElement("br"));
  26155. };
  26156. DebugLayer.prototype._generateDOMelements = function () {
  26157. var _this = this;
  26158. this._globalDiv.id = "DebugLayer";
  26159. this._globalDiv.style.position = "absolute";
  26160. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  26161. this._globalDiv.style.fontSize = "14px";
  26162. this._globalDiv.style.color = "white";
  26163. // Drawing canvas
  26164. this._drawingCanvas = document.createElement("canvas");
  26165. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  26166. this._drawingCanvas.style.position = "absolute";
  26167. this._drawingCanvas.style.pointerEvents = "none";
  26168. this._drawingContext = this._drawingCanvas.getContext("2d");
  26169. this._globalDiv.appendChild(this._drawingCanvas);
  26170. if (this._showUI) {
  26171. var background = "rgba(128, 128, 128, 0.4)";
  26172. var border = "rgb(180, 180, 180) solid 1px";
  26173. // Stats
  26174. this._statsDiv = document.createElement("div");
  26175. this._statsDiv.id = "DebugLayerStats";
  26176. this._statsDiv.style.border = border;
  26177. this._statsDiv.style.position = "absolute";
  26178. this._statsDiv.style.background = background;
  26179. this._statsDiv.style.padding = "0px 0px 0px 5px";
  26180. this._generateheader(this._statsDiv, "STATISTICS");
  26181. this._statsSubsetDiv = document.createElement("div");
  26182. this._statsSubsetDiv.style.paddingTop = "5px";
  26183. this._statsSubsetDiv.style.paddingBottom = "5px";
  26184. this._statsSubsetDiv.style.overflowY = "auto";
  26185. this._statsDiv.appendChild(this._statsSubsetDiv);
  26186. // Tree
  26187. this._treeDiv = document.createElement("div");
  26188. this._treeDiv.id = "DebugLayerTree";
  26189. this._treeDiv.style.border = border;
  26190. this._treeDiv.style.position = "absolute";
  26191. this._treeDiv.style.background = background;
  26192. this._treeDiv.style.padding = "0px 0px 0px 5px";
  26193. this._treeDiv.style.display = "none";
  26194. this._generateheader(this._treeDiv, "MESHES TREE");
  26195. this._treeSubsetDiv = document.createElement("div");
  26196. this._treeSubsetDiv.style.paddingTop = "5px";
  26197. this._treeSubsetDiv.style.paddingRight = "5px";
  26198. this._treeSubsetDiv.style.overflowY = "auto";
  26199. this._treeSubsetDiv.style.maxHeight = "300px";
  26200. this._treeDiv.appendChild(this._treeSubsetDiv);
  26201. this._needToRefreshMeshesTree = true;
  26202. // Logs
  26203. this._logDiv = document.createElement("div");
  26204. this._logDiv.style.border = border;
  26205. this._logDiv.id = "DebugLayerLogs";
  26206. this._logDiv.style.position = "absolute";
  26207. this._logDiv.style.background = background;
  26208. this._logDiv.style.padding = "0px 0px 0px 5px";
  26209. this._logDiv.style.display = "none";
  26210. this._generateheader(this._logDiv, "LOGS");
  26211. this._logSubsetDiv = document.createElement("div");
  26212. this._logSubsetDiv.style.height = "127px";
  26213. this._logSubsetDiv.style.paddingTop = "5px";
  26214. this._logSubsetDiv.style.overflowY = "auto";
  26215. this._logSubsetDiv.style.fontSize = "12px";
  26216. this._logSubsetDiv.style.fontFamily = "consolas";
  26217. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  26218. this._logDiv.appendChild(this._logSubsetDiv);
  26219. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  26220. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  26221. };
  26222. // Options
  26223. this._optionsDiv = document.createElement("div");
  26224. this._optionsDiv.id = "DebugLayerOptions";
  26225. this._optionsDiv.style.border = border;
  26226. this._optionsDiv.style.position = "absolute";
  26227. this._optionsDiv.style.background = background;
  26228. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  26229. this._optionsDiv.style.overflowY = "auto";
  26230. this._generateheader(this._optionsDiv, "OPTIONS");
  26231. this._optionsSubsetDiv = document.createElement("div");
  26232. this._optionsSubsetDiv.style.paddingTop = "5px";
  26233. this._optionsSubsetDiv.style.paddingBottom = "5px";
  26234. this._optionsSubsetDiv.style.overflowY = "auto";
  26235. this._optionsSubsetDiv.style.maxHeight = "200px";
  26236. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  26237. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  26238. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  26239. _this._displayStatistics = element.checked;
  26240. });
  26241. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  26242. _this._displayLogs = element.checked;
  26243. });
  26244. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  26245. _this._displayTree = element.checked;
  26246. _this._needToRefreshMeshesTree = true;
  26247. });
  26248. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26249. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  26250. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  26251. _this._scene.forceShowBoundingBoxes = element.checked;
  26252. });
  26253. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  26254. _this._labelsEnabled = element.checked;
  26255. if (!_this._labelsEnabled) {
  26256. _this._clearLabels();
  26257. }
  26258. });
  26259. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  26260. if (element.checked) {
  26261. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  26262. }
  26263. else {
  26264. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  26265. }
  26266. });
  26267. ;
  26268. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26269. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  26270. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  26271. if (element.checked) {
  26272. _this._scene.forceWireframe = false;
  26273. _this._scene.forcePointsCloud = false;
  26274. }
  26275. });
  26276. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  26277. if (element.checked) {
  26278. _this._scene.forceWireframe = true;
  26279. _this._scene.forcePointsCloud = false;
  26280. }
  26281. });
  26282. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  26283. if (element.checked) {
  26284. _this._scene.forceWireframe = false;
  26285. _this._scene.forcePointsCloud = true;
  26286. }
  26287. });
  26288. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26289. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  26290. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  26291. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  26292. });
  26293. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  26294. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  26295. });
  26296. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  26297. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  26298. });
  26299. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  26300. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  26301. });
  26302. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  26303. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  26304. });
  26305. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  26306. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  26307. });
  26308. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  26309. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  26310. });
  26311. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  26312. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  26313. });
  26314. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26315. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  26316. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  26317. _this._scene.animationsEnabled = element.checked;
  26318. });
  26319. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  26320. _this._scene.collisionsEnabled = element.checked;
  26321. });
  26322. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  26323. _this._scene.fogEnabled = element.checked;
  26324. });
  26325. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  26326. _this._scene.lensFlaresEnabled = element.checked;
  26327. });
  26328. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  26329. _this._scene.lightsEnabled = element.checked;
  26330. });
  26331. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  26332. _this._scene.particlesEnabled = element.checked;
  26333. });
  26334. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  26335. _this._scene.postProcessesEnabled = element.checked;
  26336. });
  26337. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  26338. _this._scene.proceduralTexturesEnabled = element.checked;
  26339. });
  26340. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  26341. _this._scene.renderTargetsEnabled = element.checked;
  26342. });
  26343. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  26344. _this._scene.shadowsEnabled = element.checked;
  26345. });
  26346. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  26347. _this._scene.skeletonsEnabled = element.checked;
  26348. });
  26349. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  26350. _this._scene.texturesEnabled = element.checked;
  26351. });
  26352. this._globalDiv.appendChild(this._statsDiv);
  26353. this._globalDiv.appendChild(this._logDiv);
  26354. this._globalDiv.appendChild(this._optionsDiv);
  26355. this._globalDiv.appendChild(this._treeDiv);
  26356. }
  26357. };
  26358. DebugLayer.prototype._displayStats = function () {
  26359. var scene = this._scene;
  26360. var engine = scene.getEngine();
  26361. var glInfo = engine.getGlInfo();
  26362. 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>";
  26363. if (this.customStatsFunction) {
  26364. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  26365. }
  26366. };
  26367. return DebugLayer;
  26368. })();
  26369. BABYLON.DebugLayer = DebugLayer;
  26370. })(BABYLON || (BABYLON = {}));
  26371. //# sourceMappingURL=babylon.debugLayer.js.map
  26372. var BABYLON;
  26373. (function (BABYLON) {
  26374. var RawTexture = (function (_super) {
  26375. __extends(RawTexture, _super);
  26376. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  26377. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26378. if (invertY === void 0) { invertY = false; }
  26379. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26380. _super.call(this, null, scene, !generateMipMaps, invertY);
  26381. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  26382. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26383. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26384. }
  26385. // Statics
  26386. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26387. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26388. if (invertY === void 0) { invertY = false; }
  26389. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26390. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  26391. };
  26392. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26393. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26394. if (invertY === void 0) { invertY = false; }
  26395. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26396. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26397. };
  26398. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26399. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26400. if (invertY === void 0) { invertY = false; }
  26401. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26402. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26403. };
  26404. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26405. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26406. if (invertY === void 0) { invertY = false; }
  26407. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26408. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  26409. };
  26410. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26411. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26412. if (invertY === void 0) { invertY = false; }
  26413. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26414. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  26415. };
  26416. return RawTexture;
  26417. })(BABYLON.Texture);
  26418. BABYLON.RawTexture = RawTexture;
  26419. })(BABYLON || (BABYLON = {}));
  26420. //# sourceMappingURL=babylon.rawTexture.js.map
  26421. var BABYLON;
  26422. (function (BABYLON) {
  26423. var IndexedVector2 = (function (_super) {
  26424. __extends(IndexedVector2, _super);
  26425. function IndexedVector2(original, index) {
  26426. _super.call(this, original.x, original.y);
  26427. this.index = index;
  26428. }
  26429. return IndexedVector2;
  26430. })(BABYLON.Vector2);
  26431. var PolygonPoints = (function () {
  26432. function PolygonPoints() {
  26433. this.elements = new Array();
  26434. }
  26435. PolygonPoints.prototype.add = function (originalPoints) {
  26436. var _this = this;
  26437. var result = new Array();
  26438. originalPoints.forEach(function (point) {
  26439. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  26440. var newPoint = new IndexedVector2(point, _this.elements.length);
  26441. result.push(newPoint);
  26442. _this.elements.push(newPoint);
  26443. }
  26444. });
  26445. return result;
  26446. };
  26447. PolygonPoints.prototype.computeBounds = function () {
  26448. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26449. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26450. this.elements.forEach(function (point) {
  26451. // x
  26452. if (point.x < lmin.x) {
  26453. lmin.x = point.x;
  26454. }
  26455. else if (point.x > lmax.x) {
  26456. lmax.x = point.x;
  26457. }
  26458. // y
  26459. if (point.y < lmin.y) {
  26460. lmin.y = point.y;
  26461. }
  26462. else if (point.y > lmax.y) {
  26463. lmax.y = point.y;
  26464. }
  26465. });
  26466. return {
  26467. min: lmin,
  26468. max: lmax,
  26469. width: lmax.x - lmin.x,
  26470. height: lmax.y - lmin.y
  26471. };
  26472. };
  26473. return PolygonPoints;
  26474. })();
  26475. var Polygon = (function () {
  26476. function Polygon() {
  26477. }
  26478. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  26479. return [
  26480. new BABYLON.Vector2(xmin, ymin),
  26481. new BABYLON.Vector2(xmax, ymin),
  26482. new BABYLON.Vector2(xmax, ymax),
  26483. new BABYLON.Vector2(xmin, ymax)
  26484. ];
  26485. };
  26486. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  26487. if (cx === void 0) { cx = 0; }
  26488. if (cy === void 0) { cy = 0; }
  26489. if (numberOfSides === void 0) { numberOfSides = 32; }
  26490. var result = new Array();
  26491. var angle = 0;
  26492. var increment = (Math.PI * 2) / numberOfSides;
  26493. for (var i = 0; i < numberOfSides; i++) {
  26494. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  26495. angle -= increment;
  26496. }
  26497. return result;
  26498. };
  26499. Polygon.Parse = function (input) {
  26500. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  26501. var i, result = [];
  26502. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  26503. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  26504. }
  26505. return result;
  26506. };
  26507. Polygon.StartingAt = function (x, y) {
  26508. return BABYLON.Path2.StartingAt(x, y);
  26509. };
  26510. return Polygon;
  26511. })();
  26512. BABYLON.Polygon = Polygon;
  26513. var PolygonMeshBuilder = (function () {
  26514. function PolygonMeshBuilder(name, contours, scene) {
  26515. this._points = new PolygonPoints();
  26516. if (!("poly2tri" in window)) {
  26517. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  26518. }
  26519. this._name = name;
  26520. this._scene = scene;
  26521. var points;
  26522. if (contours instanceof BABYLON.Path2) {
  26523. points = contours.getPoints();
  26524. }
  26525. else {
  26526. points = contours;
  26527. }
  26528. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  26529. }
  26530. PolygonMeshBuilder.prototype.addHole = function (hole) {
  26531. this._swctx.addHole(this._points.add(hole));
  26532. return this;
  26533. };
  26534. PolygonMeshBuilder.prototype.build = function (updatable) {
  26535. if (updatable === void 0) { updatable = false; }
  26536. var result = new BABYLON.Mesh(this._name, this._scene);
  26537. var normals = [];
  26538. var positions = [];
  26539. var uvs = [];
  26540. var bounds = this._points.computeBounds();
  26541. this._points.elements.forEach(function (p) {
  26542. normals.push(0, 1.0, 0);
  26543. positions.push(p.x, 0, p.y);
  26544. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  26545. });
  26546. var indices = [];
  26547. this._swctx.triangulate();
  26548. this._swctx.getTriangles().forEach(function (triangle) {
  26549. triangle.getPoints().forEach(function (point) {
  26550. indices.push(point.index);
  26551. });
  26552. });
  26553. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  26554. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  26555. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  26556. result.setIndices(indices);
  26557. return result;
  26558. };
  26559. return PolygonMeshBuilder;
  26560. })();
  26561. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  26562. })(BABYLON || (BABYLON = {}));
  26563. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  26564. (function (BABYLON) {
  26565. var SimplificationSettings = (function () {
  26566. function SimplificationSettings(quality, distance) {
  26567. this.quality = quality;
  26568. this.distance = distance;
  26569. }
  26570. return SimplificationSettings;
  26571. })();
  26572. BABYLON.SimplificationSettings = SimplificationSettings;
  26573. /**
  26574. * The implemented types of simplification.
  26575. * At the moment only Quadratic Error Decimation is implemented.
  26576. */
  26577. (function (SimplificationType) {
  26578. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  26579. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  26580. var SimplificationType = BABYLON.SimplificationType;
  26581. var DecimationTriangle = (function () {
  26582. function DecimationTriangle(vertices) {
  26583. this.vertices = vertices;
  26584. this.error = new Array(4);
  26585. this.deleted = false;
  26586. this.isDirty = false;
  26587. this.borderFactor = 0;
  26588. }
  26589. return DecimationTriangle;
  26590. })();
  26591. BABYLON.DecimationTriangle = DecimationTriangle;
  26592. var DecimationVertex = (function () {
  26593. function DecimationVertex(position, normal, uv, id) {
  26594. this.position = position;
  26595. this.normal = normal;
  26596. this.uv = uv;
  26597. this.id = id;
  26598. this.isBorder = true;
  26599. this.q = new QuadraticMatrix();
  26600. this.triangleCount = 0;
  26601. this.triangleStart = 0;
  26602. }
  26603. return DecimationVertex;
  26604. })();
  26605. BABYLON.DecimationVertex = DecimationVertex;
  26606. var QuadraticMatrix = (function () {
  26607. function QuadraticMatrix(data) {
  26608. this.data = new Array(10);
  26609. for (var i = 0; i < 10; ++i) {
  26610. if (data && data[i]) {
  26611. this.data[i] = data[i];
  26612. }
  26613. else {
  26614. this.data[i] = 0;
  26615. }
  26616. }
  26617. }
  26618. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  26619. 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];
  26620. return det;
  26621. };
  26622. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  26623. for (var i = 0; i < 10; ++i) {
  26624. this.data[i] += matrix.data[i];
  26625. }
  26626. };
  26627. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  26628. for (var i = 0; i < 10; ++i) {
  26629. this.data[i] += data[i];
  26630. }
  26631. };
  26632. QuadraticMatrix.prototype.add = function (matrix) {
  26633. var m = new QuadraticMatrix();
  26634. for (var i = 0; i < 10; ++i) {
  26635. m.data[i] = this.data[i] + matrix.data[i];
  26636. }
  26637. return m;
  26638. };
  26639. QuadraticMatrix.FromData = function (a, b, c, d) {
  26640. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  26641. };
  26642. //returning an array to avoid garbage collection
  26643. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  26644. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  26645. };
  26646. return QuadraticMatrix;
  26647. })();
  26648. BABYLON.QuadraticMatrix = QuadraticMatrix;
  26649. var Reference = (function () {
  26650. function Reference(vertexId, triangleId) {
  26651. this.vertexId = vertexId;
  26652. this.triangleId = triangleId;
  26653. }
  26654. return Reference;
  26655. })();
  26656. BABYLON.Reference = Reference;
  26657. /**
  26658. * An implementation of the Quadratic Error simplification algorithm.
  26659. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  26660. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  26661. * @author RaananW
  26662. */
  26663. var QuadraticErrorSimplification = (function () {
  26664. function QuadraticErrorSimplification(_mesh) {
  26665. this._mesh = _mesh;
  26666. this.initialised = false;
  26667. this.syncIterations = 5000;
  26668. this.aggressiveness = 7;
  26669. this.decimationIterations = 100;
  26670. }
  26671. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  26672. var _this = this;
  26673. this.initWithMesh(this._mesh, function () {
  26674. _this.runDecimation(settings, successCallback);
  26675. });
  26676. };
  26677. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  26678. var _this = this;
  26679. var targetCount = ~~(this.triangles.length * settings.quality);
  26680. var deletedTriangles = 0;
  26681. var triangleCount = this.triangles.length;
  26682. var iterationFunction = function (iteration, callback) {
  26683. setTimeout(function () {
  26684. if (iteration % 5 === 0) {
  26685. _this.updateMesh(iteration === 0);
  26686. }
  26687. for (var i = 0; i < _this.triangles.length; ++i) {
  26688. _this.triangles[i].isDirty = false;
  26689. }
  26690. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  26691. var trianglesIterator = function (i) {
  26692. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  26693. var t = _this.triangles[tIdx];
  26694. if (!t)
  26695. return;
  26696. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  26697. return;
  26698. }
  26699. for (var j = 0; j < 3; ++j) {
  26700. if (t.error[j] < threshold) {
  26701. var deleted0 = [];
  26702. var deleted1 = [];
  26703. var i0 = t.vertices[j];
  26704. var i1 = t.vertices[(j + 1) % 3];
  26705. var v0 = _this.vertices[i0];
  26706. var v1 = _this.vertices[i1];
  26707. if (v0.isBorder !== v1.isBorder)
  26708. continue;
  26709. var p = BABYLON.Vector3.Zero();
  26710. var n = BABYLON.Vector3.Zero();
  26711. var uv = BABYLON.Vector2.Zero();
  26712. var color = new BABYLON.Color4(0, 0, 0, 1);
  26713. _this.calculateError(v0, v1, p, n, uv, color);
  26714. var delTr = [];
  26715. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  26716. continue;
  26717. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  26718. continue;
  26719. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  26720. continue;
  26721. }
  26722. v0.normal = n;
  26723. if (v0.uv)
  26724. v0.uv = uv;
  26725. else if (v0.color)
  26726. v0.color = color;
  26727. v0.q = v1.q.add(v0.q);
  26728. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  26729. continue;
  26730. if (p.equals(v0.position))
  26731. continue;
  26732. v0.position = p;
  26733. var tStart = _this.references.length;
  26734. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  26735. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  26736. var tCount = _this.references.length - tStart;
  26737. if (tCount <= v0.triangleCount) {
  26738. if (tCount) {
  26739. for (var c = 0; c < tCount; c++) {
  26740. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  26741. }
  26742. }
  26743. }
  26744. else {
  26745. v0.triangleStart = tStart;
  26746. }
  26747. v0.triangleCount = tCount;
  26748. break;
  26749. }
  26750. }
  26751. };
  26752. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  26753. return (triangleCount - deletedTriangles <= targetCount);
  26754. });
  26755. }, 0);
  26756. };
  26757. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  26758. if (triangleCount - deletedTriangles <= targetCount)
  26759. loop.breakLoop();
  26760. else {
  26761. iterationFunction(loop.index, function () {
  26762. loop.executeNext();
  26763. });
  26764. }
  26765. }, function () {
  26766. setTimeout(function () {
  26767. successCallback(_this.reconstructMesh());
  26768. }, 0);
  26769. });
  26770. };
  26771. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  26772. var _this = this;
  26773. if (!mesh)
  26774. return;
  26775. this.vertices = [];
  26776. this.triangles = [];
  26777. this._mesh = mesh;
  26778. //It is assumed that a mesh has positions, normals and either uvs or colors.
  26779. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26780. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26781. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26782. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26783. var indices = mesh.getIndices();
  26784. var vertexInit = function (i) {
  26785. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), null, i);
  26786. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26787. vertex.uv = BABYLON.Vector2.FromArray(uvs, i * 2);
  26788. }
  26789. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26790. vertex.color = BABYLON.Color4.FromArray(colorsData, i * 4);
  26791. }
  26792. _this.vertices.push(vertex);
  26793. };
  26794. var totalVertices = mesh.getTotalVertices();
  26795. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  26796. var indicesInit = function (i) {
  26797. var pos = i * 3;
  26798. var i0 = indices[pos + 0];
  26799. var i1 = indices[pos + 1];
  26800. var i2 = indices[pos + 2];
  26801. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  26802. _this.triangles.push(triangle);
  26803. };
  26804. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  26805. _this.init(callback);
  26806. });
  26807. });
  26808. };
  26809. QuadraticErrorSimplification.prototype.init = function (callback) {
  26810. var _this = this;
  26811. var triangleInit1 = function (i) {
  26812. var t = _this.triangles[i];
  26813. 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();
  26814. for (var j = 0; j < 3; j++) {
  26815. _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))));
  26816. }
  26817. };
  26818. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  26819. var triangleInit2 = function (i) {
  26820. var t = _this.triangles[i];
  26821. for (var j = 0; j < 3; ++j) {
  26822. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  26823. }
  26824. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  26825. };
  26826. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  26827. _this.initialised = true;
  26828. callback();
  26829. });
  26830. });
  26831. };
  26832. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  26833. var newTriangles = [];
  26834. var i;
  26835. for (i = 0; i < this.vertices.length; ++i) {
  26836. this.vertices[i].triangleCount = 0;
  26837. }
  26838. var t;
  26839. var j;
  26840. for (i = 0; i < this.triangles.length; ++i) {
  26841. if (!this.triangles[i].deleted) {
  26842. t = this.triangles[i];
  26843. for (j = 0; j < 3; ++j) {
  26844. this.vertices[t.vertices[j]].triangleCount = 1;
  26845. }
  26846. newTriangles.push(t);
  26847. }
  26848. }
  26849. var newVerticesOrder = [];
  26850. //compact vertices, get the IDs of the vertices used.
  26851. var dst = 0;
  26852. for (i = 0; i < this.vertices.length; ++i) {
  26853. if (this.vertices[i].triangleCount) {
  26854. this.vertices[i].triangleStart = dst;
  26855. this.vertices[dst].position = this.vertices[i].position;
  26856. this.vertices[dst].normal = this.vertices[i].normal;
  26857. this.vertices[dst].uv = this.vertices[i].uv;
  26858. this.vertices[dst].color = this.vertices[i].color;
  26859. newVerticesOrder.push(i);
  26860. dst++;
  26861. }
  26862. }
  26863. for (i = 0; i < newTriangles.length; ++i) {
  26864. t = newTriangles[i];
  26865. for (j = 0; j < 3; ++j) {
  26866. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  26867. }
  26868. }
  26869. this.vertices = this.vertices.slice(0, dst);
  26870. var newPositionData = [];
  26871. var newNormalData = [];
  26872. var newUVsData = [];
  26873. var newColorsData = [];
  26874. for (i = 0; i < newVerticesOrder.length; ++i) {
  26875. newPositionData.push(this.vertices[i].position.x);
  26876. newPositionData.push(this.vertices[i].position.y);
  26877. newPositionData.push(this.vertices[i].position.z);
  26878. newNormalData.push(this.vertices[i].normal.x);
  26879. newNormalData.push(this.vertices[i].normal.y);
  26880. newNormalData.push(this.vertices[i].normal.z);
  26881. if (this.vertices[i].uv) {
  26882. newUVsData.push(this.vertices[i].uv.x);
  26883. newUVsData.push(this.vertices[i].uv.y);
  26884. }
  26885. else if (this.vertices[i].color) {
  26886. newColorsData.push(this.vertices[i].color.r);
  26887. newColorsData.push(this.vertices[i].color.g);
  26888. newColorsData.push(this.vertices[i].color.b);
  26889. newColorsData.push(this.vertices[i].color.a);
  26890. }
  26891. }
  26892. var newIndicesArray = [];
  26893. for (i = 0; i < newTriangles.length; ++i) {
  26894. newIndicesArray.push(newTriangles[i].vertices[0]);
  26895. newIndicesArray.push(newTriangles[i].vertices[1]);
  26896. newIndicesArray.push(newTriangles[i].vertices[2]);
  26897. }
  26898. //not cloning, to avoid geometry problems. Creating a whole new mesh.
  26899. var newMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  26900. newMesh.material = this._mesh.material;
  26901. newMesh.parent = this._mesh.parent;
  26902. newMesh.setIndices(newIndicesArray);
  26903. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  26904. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  26905. if (newUVsData.length > 0)
  26906. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  26907. if (newColorsData.length > 0)
  26908. newMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  26909. //preparing the skeleton support
  26910. if (this._mesh.skeleton) {
  26911. }
  26912. return newMesh;
  26913. };
  26914. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  26915. for (var i = 0; i < vertex1.triangleCount; ++i) {
  26916. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  26917. if (t.deleted)
  26918. continue;
  26919. var s = this.references[vertex1.triangleStart + i].vertexId;
  26920. var id1 = t.vertices[(s + 1) % 3];
  26921. var id2 = t.vertices[(s + 2) % 3];
  26922. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  26923. deletedArray[i] = true;
  26924. delTr.push(t);
  26925. continue;
  26926. }
  26927. var d1 = this.vertices[id1].position.subtract(point);
  26928. d1 = d1.normalize();
  26929. var d2 = this.vertices[id2].position.subtract(point);
  26930. d2 = d2.normalize();
  26931. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  26932. return true;
  26933. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  26934. deletedArray[i] = false;
  26935. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  26936. return true;
  26937. }
  26938. return false;
  26939. };
  26940. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  26941. var newDeleted = deletedTriangles;
  26942. for (var i = 0; i < vertex.triangleCount; ++i) {
  26943. var ref = this.references[vertex.triangleStart + i];
  26944. var t = this.triangles[ref.triangleId];
  26945. if (t.deleted)
  26946. continue;
  26947. if (deletedArray[i]) {
  26948. t.deleted = true;
  26949. newDeleted++;
  26950. continue;
  26951. }
  26952. t.vertices[ref.vertexId] = vertexId;
  26953. t.isDirty = true;
  26954. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  26955. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  26956. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  26957. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  26958. this.references.push(ref);
  26959. }
  26960. return newDeleted;
  26961. };
  26962. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  26963. for (var i = 0; i < this.vertices.length; ++i) {
  26964. var vCount = [];
  26965. var vId = [];
  26966. var v = this.vertices[i];
  26967. var j;
  26968. for (j = 0; j < v.triangleCount; ++j) {
  26969. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  26970. for (var ii = 0; ii < 3; ii++) {
  26971. var ofs = 0;
  26972. var id = triangle.vertices[ii];
  26973. while (ofs < vCount.length) {
  26974. if (vId[ofs] === id)
  26975. break;
  26976. ++ofs;
  26977. }
  26978. if (ofs === vCount.length) {
  26979. vCount.push(1);
  26980. vId.push(id);
  26981. }
  26982. else {
  26983. vCount[ofs]++;
  26984. }
  26985. }
  26986. }
  26987. for (j = 0; j < vCount.length; ++j) {
  26988. if (vCount[j] === 1) {
  26989. this.vertices[vId[j]].isBorder = true;
  26990. }
  26991. else {
  26992. this.vertices[vId[j]].isBorder = false;
  26993. }
  26994. }
  26995. }
  26996. };
  26997. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  26998. if (identifyBorders === void 0) { identifyBorders = false; }
  26999. var i;
  27000. if (!identifyBorders) {
  27001. var newTrianglesVector = [];
  27002. for (i = 0; i < this.triangles.length; ++i) {
  27003. if (!this.triangles[i].deleted) {
  27004. newTrianglesVector.push(this.triangles[i]);
  27005. }
  27006. }
  27007. this.triangles = newTrianglesVector;
  27008. }
  27009. for (i = 0; i < this.vertices.length; ++i) {
  27010. this.vertices[i].triangleCount = 0;
  27011. this.vertices[i].triangleStart = 0;
  27012. }
  27013. var t;
  27014. var j;
  27015. var v;
  27016. for (i = 0; i < this.triangles.length; ++i) {
  27017. t = this.triangles[i];
  27018. for (j = 0; j < 3; ++j) {
  27019. v = this.vertices[t.vertices[j]];
  27020. v.triangleCount++;
  27021. }
  27022. }
  27023. var tStart = 0;
  27024. for (i = 0; i < this.vertices.length; ++i) {
  27025. this.vertices[i].triangleStart = tStart;
  27026. tStart += this.vertices[i].triangleCount;
  27027. this.vertices[i].triangleCount = 0;
  27028. }
  27029. var newReferences = new Array(this.triangles.length * 3);
  27030. for (i = 0; i < this.triangles.length; ++i) {
  27031. t = this.triangles[i];
  27032. for (j = 0; j < 3; ++j) {
  27033. v = this.vertices[t.vertices[j]];
  27034. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  27035. v.triangleCount++;
  27036. }
  27037. }
  27038. this.references = newReferences;
  27039. if (identifyBorders) {
  27040. this.identifyBorder();
  27041. }
  27042. };
  27043. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  27044. var x = point.x;
  27045. var y = point.y;
  27046. var z = point.z;
  27047. 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];
  27048. };
  27049. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  27050. var q = vertex1.q.add(vertex2.q);
  27051. var border = vertex1.isBorder && vertex2.isBorder;
  27052. var error = 0;
  27053. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  27054. if (qDet !== 0 && !border) {
  27055. if (!pointResult) {
  27056. pointResult = BABYLON.Vector3.Zero();
  27057. }
  27058. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  27059. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  27060. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  27061. error = this.vertexError(q, pointResult);
  27062. //TODO this should be correctly calculated
  27063. if (normalResult) {
  27064. normalResult.copyFrom(vertex1.normal);
  27065. if (vertex1.uv)
  27066. uvResult.copyFrom(vertex1.uv);
  27067. else if (vertex1.color)
  27068. colorResult.copyFrom(vertex1.color);
  27069. }
  27070. }
  27071. else {
  27072. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  27073. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  27074. var error1 = this.vertexError(q, vertex1.position);
  27075. var error2 = this.vertexError(q, vertex2.position);
  27076. var error3 = this.vertexError(q, p3);
  27077. error = Math.min(error1, error2, error3);
  27078. if (error === error1) {
  27079. if (pointResult) {
  27080. pointResult.copyFrom(vertex1.position);
  27081. normalResult.copyFrom(vertex1.normal);
  27082. if (vertex1.uv)
  27083. uvResult.copyFrom(vertex1.uv);
  27084. else if (vertex1.color)
  27085. colorResult.copyFrom(vertex1.color);
  27086. }
  27087. }
  27088. else if (error === error2) {
  27089. if (pointResult) {
  27090. pointResult.copyFrom(vertex2.position);
  27091. normalResult.copyFrom(vertex2.normal);
  27092. if (vertex2.uv)
  27093. uvResult.copyFrom(vertex2.uv);
  27094. else if (vertex2.color)
  27095. colorResult.copyFrom(vertex2.color);
  27096. }
  27097. }
  27098. else {
  27099. if (pointResult) {
  27100. pointResult.copyFrom(p3);
  27101. normalResult.copyFrom(vertex1.normal);
  27102. if (vertex1.uv)
  27103. uvResult.copyFrom(vertex1.uv);
  27104. else if (vertex1.color)
  27105. colorResult.copyFrom(vertex1.color);
  27106. }
  27107. }
  27108. }
  27109. return error;
  27110. };
  27111. return QuadraticErrorSimplification;
  27112. })();
  27113. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  27114. })(BABYLON || (BABYLON = {}));
  27115. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  27116. (function (BABYLON) {
  27117. var Analyser = (function () {
  27118. function Analyser(scene) {
  27119. this.SMOOTHING = 0.75;
  27120. this.FFT_SIZE = 512;
  27121. this.BARGRAPHAMPLITUDE = 256;
  27122. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  27123. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  27124. this._scene = scene;
  27125. this._audioEngine = BABYLON.Engine.audioEngine;
  27126. if (this._audioEngine.canUseWebAudio) {
  27127. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  27128. this._webAudioAnalyser.minDecibels = -140;
  27129. this._webAudioAnalyser.maxDecibels = 0;
  27130. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27131. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27132. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  27133. }
  27134. }
  27135. Analyser.prototype.getFrequencyBinCount = function () {
  27136. if (this._audioEngine.canUseWebAudio) {
  27137. return this._webAudioAnalyser.frequencyBinCount;
  27138. }
  27139. else {
  27140. return 0;
  27141. }
  27142. };
  27143. Analyser.prototype.getByteFrequencyData = function () {
  27144. if (this._audioEngine.canUseWebAudio) {
  27145. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27146. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27147. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  27148. }
  27149. return this._byteFreqs;
  27150. };
  27151. Analyser.prototype.getByteTimeDomainData = function () {
  27152. if (this._audioEngine.canUseWebAudio) {
  27153. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27154. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27155. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  27156. }
  27157. return this._byteTime;
  27158. };
  27159. Analyser.prototype.getFloatFrequencyData = function () {
  27160. if (this._audioEngine.canUseWebAudio) {
  27161. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27162. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27163. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  27164. }
  27165. return this._floatFreqs;
  27166. };
  27167. Analyser.prototype.drawDebugCanvas = function () {
  27168. var _this = this;
  27169. if (this._audioEngine.canUseWebAudio) {
  27170. if (!this._debugCanvas) {
  27171. this._debugCanvas = document.createElement("canvas");
  27172. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  27173. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  27174. this._debugCanvas.style.position = "absolute";
  27175. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  27176. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  27177. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  27178. document.body.appendChild(this._debugCanvas);
  27179. this._registerFunc = function () {
  27180. _this.drawDebugCanvas();
  27181. };
  27182. this._scene.registerBeforeRender(this._registerFunc);
  27183. }
  27184. if (this._registerFunc) {
  27185. var workingArray = this.getByteFrequencyData();
  27186. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  27187. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  27188. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  27189. var value = workingArray[i];
  27190. var percent = value / this.BARGRAPHAMPLITUDE;
  27191. var height = this.DEBUGCANVASSIZE.height * percent;
  27192. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  27193. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  27194. var hue = i / this.getFrequencyBinCount() * 360;
  27195. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  27196. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  27197. }
  27198. }
  27199. }
  27200. };
  27201. Analyser.prototype.stopDebugCanvas = function () {
  27202. if (this._debugCanvas) {
  27203. this._scene.unregisterBeforeRender(this._registerFunc);
  27204. this._registerFunc = null;
  27205. document.body.removeChild(this._debugCanvas);
  27206. this._debugCanvas = null;
  27207. this._debugCanvasContext = null;
  27208. }
  27209. };
  27210. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  27211. if (this._audioEngine.canUseWebAudio) {
  27212. inputAudioNode.connect(this._webAudioAnalyser);
  27213. this._webAudioAnalyser.connect(outputAudioNode);
  27214. }
  27215. };
  27216. Analyser.prototype.dispose = function () {
  27217. if (this._audioEngine.canUseWebAudio) {
  27218. this._webAudioAnalyser.disconnect();
  27219. }
  27220. };
  27221. return Analyser;
  27222. })();
  27223. BABYLON.Analyser = Analyser;
  27224. })(BABYLON || (BABYLON = {}));
  27225. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  27226. (function (BABYLON) {
  27227. var DepthRenderer = (function () {
  27228. function DepthRenderer(scene, type) {
  27229. var _this = this;
  27230. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  27231. this._viewMatrix = BABYLON.Matrix.Zero();
  27232. this._projectionMatrix = BABYLON.Matrix.Zero();
  27233. this._transformMatrix = BABYLON.Matrix.Zero();
  27234. this._worldViewProjection = BABYLON.Matrix.Zero();
  27235. this._scene = scene;
  27236. var engine = scene.getEngine();
  27237. // Render target
  27238. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  27239. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27240. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27241. this._depthMap.refreshRate = 1;
  27242. this._depthMap.renderParticles = false;
  27243. this._depthMap.renderList = null;
  27244. // Custom render function
  27245. var renderSubMesh = function (subMesh) {
  27246. var mesh = subMesh.getRenderingMesh();
  27247. var scene = _this._scene;
  27248. var engine = scene.getEngine();
  27249. // Culling
  27250. engine.setState(subMesh.getMaterial().backFaceCulling);
  27251. // Managing instances
  27252. var batch = mesh._getInstancesRenderList(subMesh._id);
  27253. if (batch.mustReturn) {
  27254. return;
  27255. }
  27256. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  27257. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  27258. engine.enableEffect(_this._effect);
  27259. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  27260. var material = subMesh.getMaterial();
  27261. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27262. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  27263. // Alpha test
  27264. if (material && material.needAlphaTesting()) {
  27265. var alphaTexture = material.getAlphaTestTexture();
  27266. _this._effect.setTexture("diffuseSampler", alphaTexture);
  27267. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27268. }
  27269. // Bones
  27270. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  27271. if (useBones) {
  27272. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27273. }
  27274. if (hardwareInstancedRendering) {
  27275. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  27276. }
  27277. else {
  27278. if (batch.renderSelf[subMesh._id]) {
  27279. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  27280. // Draw
  27281. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  27282. }
  27283. if (batch.visibleInstances[subMesh._id]) {
  27284. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  27285. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  27286. _this._effect.setMatrix("world", instance.getWorldMatrix());
  27287. // Draw
  27288. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  27289. }
  27290. }
  27291. }
  27292. }
  27293. };
  27294. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  27295. var index;
  27296. for (index = 0; index < opaqueSubMeshes.length; index++) {
  27297. renderSubMesh(opaqueSubMeshes.data[index]);
  27298. }
  27299. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  27300. renderSubMesh(alphaTestSubMeshes.data[index]);
  27301. }
  27302. };
  27303. }
  27304. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  27305. var defines = [];
  27306. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27307. var mesh = subMesh.getMesh();
  27308. var scene = mesh.getScene();
  27309. var material = subMesh.getMaterial();
  27310. // Alpha test
  27311. if (material && material.needAlphaTesting()) {
  27312. defines.push("#define ALPHATEST");
  27313. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27314. attribs.push(BABYLON.VertexBuffer.UVKind);
  27315. defines.push("#define UV1");
  27316. }
  27317. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27318. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27319. defines.push("#define UV2");
  27320. }
  27321. }
  27322. // Bones
  27323. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27324. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27325. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27326. defines.push("#define BONES");
  27327. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27328. }
  27329. // Instances
  27330. if (useInstances) {
  27331. defines.push("#define INSTANCES");
  27332. attribs.push("world0");
  27333. attribs.push("world1");
  27334. attribs.push("world2");
  27335. attribs.push("world3");
  27336. }
  27337. // Get correct effect
  27338. var join = defines.join("\n");
  27339. if (this._cachedDefines !== join) {
  27340. this._cachedDefines = join;
  27341. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  27342. }
  27343. return this._effect.isReady();
  27344. };
  27345. DepthRenderer.prototype.getDepthMap = function () {
  27346. return this._depthMap;
  27347. };
  27348. // Methods
  27349. DepthRenderer.prototype.dispose = function () {
  27350. this._depthMap.dispose();
  27351. };
  27352. return DepthRenderer;
  27353. })();
  27354. BABYLON.DepthRenderer = DepthRenderer;
  27355. })(BABYLON || (BABYLON = {}));
  27356. //# sourceMappingURL=babylon.depthRenderer.js.map
  27357. var BABYLON;
  27358. (function (BABYLON) {
  27359. var SSAORenderingPipeline = (function (_super) {
  27360. __extends(SSAORenderingPipeline, _super);
  27361. function SSAORenderingPipeline(name, scene, ratio) {
  27362. var _this = this;
  27363. if (ratio === void 0) { ratio = 1.0; }
  27364. _super.call(this, scene.getEngine(), name);
  27365. // Members
  27366. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  27367. this.SSAORenderEffect = "SSAORenderEffect";
  27368. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  27369. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  27370. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  27371. this._scene = null;
  27372. this._depthTexture = null;
  27373. this._randomTexture = null;
  27374. this._originalColorPostProcess = null;
  27375. this._ssaoPostProcess = null;
  27376. this._blurHPostProcess = null;
  27377. this._blurVPostProcess = null;
  27378. this._ssaoCombinePostProcess = null;
  27379. this._firstUpdate = true;
  27380. this._scene = scene;
  27381. // Set up assets
  27382. this._createRandomTexture();
  27383. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  27384. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27385. this._createSSAOPostProcess(ratio);
  27386. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlur", new BABYLON.Vector2(1.0, 0.0), 1.0, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27387. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlur", new BABYLON.Vector2(0.0, 1.0), 1.0, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27388. this._createSSAOCombinePostProcess();
  27389. // Set up pipeline
  27390. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  27391. return _this._originalColorPostProcess;
  27392. }, true));
  27393. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  27394. return _this._ssaoPostProcess;
  27395. }, true));
  27396. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  27397. return _this._blurHPostProcess;
  27398. }, true));
  27399. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  27400. return _this._blurVPostProcess;
  27401. }, true));
  27402. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  27403. return _this._ssaoCombinePostProcess;
  27404. }, true));
  27405. // Finish
  27406. scene.postProcessRenderPipelineManager.addPipeline(this);
  27407. }
  27408. // Public Methods
  27409. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  27410. return this._blurHPostProcess;
  27411. };
  27412. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  27413. return this._blurVPostProcess;
  27414. };
  27415. // Private Methods
  27416. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  27417. var _this = this;
  27418. var sampleSphere = [
  27419. 0.5381,
  27420. 0.1856,
  27421. -0.4319,
  27422. 0.1379,
  27423. 0.2486,
  27424. 0.4430,
  27425. 0.3371,
  27426. 0.5679,
  27427. -0.0057,
  27428. -0.6999,
  27429. -0.0451,
  27430. -0.0019,
  27431. 0.0689,
  27432. -0.1598,
  27433. -0.8547,
  27434. 0.0560,
  27435. 0.0069,
  27436. -0.1843,
  27437. -0.0146,
  27438. 0.1402,
  27439. 0.0762,
  27440. 0.0100,
  27441. -0.1924,
  27442. -0.0344,
  27443. -0.3577,
  27444. -0.5301,
  27445. -0.4358,
  27446. -0.3169,
  27447. 0.1063,
  27448. 0.0158,
  27449. 0.0103,
  27450. -0.5869,
  27451. 0.0046,
  27452. -0.0897,
  27453. -0.4940,
  27454. 0.3287,
  27455. 0.7119,
  27456. -0.0154,
  27457. -0.0918,
  27458. -0.0533,
  27459. 0.0596,
  27460. -0.5411,
  27461. 0.0352,
  27462. -0.0631,
  27463. 0.5460,
  27464. -0.4776,
  27465. 0.2847,
  27466. -0.0271
  27467. ];
  27468. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  27469. this._ssaoPostProcess.onApply = function (effect) {
  27470. if (_this._firstUpdate === true) {
  27471. effect.setArray3("sampleSphere", sampleSphere);
  27472. _this._firstUpdate = false;
  27473. }
  27474. effect.setTexture("textureSampler", _this._depthTexture);
  27475. effect.setTexture("randomSampler", _this._randomTexture);
  27476. };
  27477. return this._ssaoPostProcess;
  27478. };
  27479. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function () {
  27480. var _this = this;
  27481. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  27482. this._ssaoCombinePostProcess.onApply = function (effect) {
  27483. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  27484. };
  27485. return this._ssaoCombinePostProcess;
  27486. };
  27487. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  27488. var size = 512;
  27489. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  27490. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  27491. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  27492. var context = this._randomTexture.getContext();
  27493. var rand = function (min, max) {
  27494. return Math.random() * (max - min) + min;
  27495. };
  27496. for (var x = 0; x < size; x++) {
  27497. for (var y = 0; y < size; y++) {
  27498. var randVector = BABYLON.Vector3.Zero();
  27499. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  27500. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  27501. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  27502. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  27503. context.fillRect(x, y, 1, 1);
  27504. }
  27505. }
  27506. this._randomTexture.update(false);
  27507. };
  27508. return SSAORenderingPipeline;
  27509. })(BABYLON.PostProcessRenderPipeline);
  27510. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  27511. })(BABYLON || (BABYLON = {}));
  27512. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map