babylon.2.0-beta.debug.js 1.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513
  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 parameters = action.getTriggerParameter();
  8353. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  8354. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  8355. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8356. if (areIntersecting && currentIntersectionInProgress === -1) {
  8357. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8358. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8359. sourceMesh._intersectionsInProgress.push(otherMesh);
  8360. }
  8361. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8362. sourceMesh._intersectionsInProgress.push(otherMesh);
  8363. }
  8364. }
  8365. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8366. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8367. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8368. if (indexOfOther > -1) {
  8369. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8370. }
  8371. }
  8372. }
  8373. }
  8374. }
  8375. };
  8376. Scene.prototype.render = function () {
  8377. var startDate = BABYLON.Tools.Now;
  8378. this._particlesDuration = 0;
  8379. this._spritesDuration = 0;
  8380. this._activeParticles = 0;
  8381. this._renderDuration = 0;
  8382. this._renderTargetsDuration = 0;
  8383. this._evaluateActiveMeshesDuration = 0;
  8384. this._totalVertices = 0;
  8385. this._activeVertices = 0;
  8386. this._activeBones = 0;
  8387. this.getEngine().resetDrawCalls();
  8388. this._meshesForIntersections.reset();
  8389. this.resetCachedMaterial();
  8390. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8391. // Actions
  8392. if (this.actionManager) {
  8393. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8394. }
  8395. // Before render
  8396. if (this.beforeRender) {
  8397. this.beforeRender();
  8398. }
  8399. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8400. this._onBeforeRenderCallbacks[callbackIndex]();
  8401. }
  8402. // Animations
  8403. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8404. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8405. this._animate();
  8406. // Physics
  8407. if (this._physicsEngine) {
  8408. BABYLON.Tools.StartPerformanceCounter("Physics");
  8409. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8410. BABYLON.Tools.EndPerformanceCounter("Physics");
  8411. }
  8412. // Customs render targets
  8413. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8414. var engine = this.getEngine();
  8415. if (this.renderTargetsEnabled) {
  8416. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8417. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8418. var renderTarget = this.customRenderTargets[customIndex];
  8419. if (renderTarget._shouldRender()) {
  8420. this._renderId++;
  8421. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8422. if (!this.activeCamera)
  8423. throw new Error("Active camera not set");
  8424. // Viewport
  8425. engine.setViewport(this.activeCamera.viewport);
  8426. // Camera
  8427. this.updateTransformMatrix();
  8428. renderTarget.render();
  8429. }
  8430. }
  8431. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8432. this._renderId++;
  8433. }
  8434. if (this.customRenderTargets.length > 0) {
  8435. engine.restoreDefaultFramebuffer();
  8436. }
  8437. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8438. // Procedural textures
  8439. if (this.proceduralTexturesEnabled) {
  8440. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8441. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8442. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8443. if (proceduralTexture._shouldRender()) {
  8444. proceduralTexture.render();
  8445. }
  8446. }
  8447. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8448. }
  8449. // Clear
  8450. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8451. // Shadows
  8452. if (this.shadowsEnabled) {
  8453. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8454. var light = this.lights[lightIndex];
  8455. var shadowGenerator = light.getShadowGenerator();
  8456. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8457. this._renderTargets.push(shadowGenerator.getShadowMap());
  8458. }
  8459. }
  8460. }
  8461. // Depth renderer
  8462. if (this._depthRenderer) {
  8463. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8464. }
  8465. // RenderPipeline
  8466. this.postProcessRenderPipelineManager.update();
  8467. // Multi-cameras?
  8468. if (this.activeCameras.length > 0) {
  8469. var currentRenderId = this._renderId;
  8470. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8471. this._renderId = currentRenderId;
  8472. this._processSubCameras(this.activeCameras[cameraIndex]);
  8473. }
  8474. }
  8475. else {
  8476. if (!this.activeCamera) {
  8477. throw new Error("No camera defined");
  8478. }
  8479. this._processSubCameras(this.activeCamera);
  8480. }
  8481. // Intersection checks
  8482. this._checkIntersections();
  8483. // Update the audio listener attached to the camera
  8484. this._updateAudioParameters();
  8485. // After render
  8486. if (this.afterRender) {
  8487. this.afterRender();
  8488. }
  8489. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8490. this._onAfterRenderCallbacks[callbackIndex]();
  8491. }
  8492. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8493. this._toBeDisposed.data[index].dispose();
  8494. this._toBeDisposed[index] = null;
  8495. }
  8496. this._toBeDisposed.reset();
  8497. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8498. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8499. };
  8500. Scene.prototype._updateAudioParameters = function () {
  8501. var listeningCamera;
  8502. var audioEngine = BABYLON.Engine.audioEngine;
  8503. if (this.activeCameras.length > 0) {
  8504. listeningCamera = this.activeCameras[0];
  8505. }
  8506. else {
  8507. listeningCamera = this.activeCamera;
  8508. }
  8509. if (listeningCamera && audioEngine.canUseWebAudio) {
  8510. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8511. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8512. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8513. cameraDirection.normalize();
  8514. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8515. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8516. var sound = this.mainSoundTrack.soundCollection[i];
  8517. if (sound.useCustomAttenuation) {
  8518. sound.updateDistanceFromListener();
  8519. }
  8520. }
  8521. for (i = 0; i < this.soundTracks.length; i++) {
  8522. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8523. sound = this.soundTracks[i].soundCollection[j];
  8524. if (sound.useCustomAttenuation) {
  8525. sound.updateDistanceFromListener();
  8526. }
  8527. }
  8528. }
  8529. }
  8530. };
  8531. Scene.prototype.enableDepthRenderer = function () {
  8532. if (this._depthRenderer) {
  8533. return this._depthRenderer;
  8534. }
  8535. this._depthRenderer = new BABYLON.DepthRenderer(this);
  8536. return this._depthRenderer;
  8537. };
  8538. Scene.prototype.disableDepthRenderer = function () {
  8539. if (!this._depthRenderer) {
  8540. return;
  8541. }
  8542. this._depthRenderer.dispose();
  8543. this._depthRenderer = null;
  8544. };
  8545. Scene.prototype.dispose = function () {
  8546. this.beforeRender = null;
  8547. this.afterRender = null;
  8548. this.skeletons = [];
  8549. this._boundingBoxRenderer.dispose();
  8550. if (this._depthRenderer) {
  8551. this._depthRenderer.dispose();
  8552. }
  8553. // Debug layer
  8554. this.debugLayer.hide();
  8555. // Events
  8556. if (this.onDispose) {
  8557. this.onDispose();
  8558. }
  8559. this._onBeforeRenderCallbacks = [];
  8560. this._onAfterRenderCallbacks = [];
  8561. this.detachControl();
  8562. // Release sounds & sounds tracks
  8563. this.mainSoundTrack.dispose();
  8564. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  8565. this.soundTracks[scIndex].dispose();
  8566. }
  8567. // Detach cameras
  8568. var canvas = this._engine.getRenderingCanvas();
  8569. var index;
  8570. for (index = 0; index < this.cameras.length; index++) {
  8571. this.cameras[index].detachControl(canvas);
  8572. }
  8573. while (this.lights.length) {
  8574. this.lights[0].dispose();
  8575. }
  8576. while (this.meshes.length) {
  8577. this.meshes[0].dispose(true);
  8578. }
  8579. while (this.cameras.length) {
  8580. this.cameras[0].dispose();
  8581. }
  8582. while (this.materials.length) {
  8583. this.materials[0].dispose();
  8584. }
  8585. while (this.particleSystems.length) {
  8586. this.particleSystems[0].dispose();
  8587. }
  8588. while (this.spriteManagers.length) {
  8589. this.spriteManagers[0].dispose();
  8590. }
  8591. while (this.layers.length) {
  8592. this.layers[0].dispose();
  8593. }
  8594. while (this.textures.length) {
  8595. this.textures[0].dispose();
  8596. }
  8597. // Post-processes
  8598. this.postProcessManager.dispose();
  8599. // Physics
  8600. if (this._physicsEngine) {
  8601. this.disablePhysicsEngine();
  8602. }
  8603. // Remove from engine
  8604. index = this._engine.scenes.indexOf(this);
  8605. if (index > -1) {
  8606. this._engine.scenes.splice(index, 1);
  8607. }
  8608. this._engine.wipeCaches();
  8609. };
  8610. // Collisions
  8611. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8612. if (excludedMesh === void 0) { excludedMesh = null; }
  8613. position.divideToRef(collider.radius, this._scaledPosition);
  8614. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8615. collider.retry = 0;
  8616. collider.initialVelocity = this._scaledVelocity;
  8617. collider.initialPosition = this._scaledPosition;
  8618. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8619. finalPosition.multiplyInPlace(collider.radius);
  8620. };
  8621. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8622. if (excludedMesh === void 0) { excludedMesh = null; }
  8623. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8624. if (collider.retry >= maximumRetry) {
  8625. finalPosition.copyFrom(position);
  8626. return;
  8627. }
  8628. collider._initialize(position, velocity, closeDistance);
  8629. for (var index = 0; index < this.meshes.length; index++) {
  8630. var mesh = this.meshes[index];
  8631. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8632. mesh._checkCollision(collider);
  8633. }
  8634. }
  8635. if (!collider.collisionFound) {
  8636. position.addToRef(velocity, finalPosition);
  8637. return;
  8638. }
  8639. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8640. collider._getResponse(position, velocity);
  8641. }
  8642. if (velocity.length() <= closeDistance) {
  8643. finalPosition.copyFrom(position);
  8644. return;
  8645. }
  8646. collider.retry++;
  8647. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8648. };
  8649. // Octrees
  8650. Scene.prototype.getWorldExtends = function () {
  8651. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8652. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8653. for (var index = 0; index < this.meshes.length; index++) {
  8654. var mesh = this.meshes[index];
  8655. mesh.computeWorldMatrix(true);
  8656. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8657. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8658. BABYLON.Tools.CheckExtends(minBox, min, max);
  8659. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8660. }
  8661. return {
  8662. min: min,
  8663. max: max
  8664. };
  8665. };
  8666. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8667. if (maxCapacity === void 0) { maxCapacity = 64; }
  8668. if (maxDepth === void 0) { maxDepth = 2; }
  8669. if (!this._selectionOctree) {
  8670. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8671. }
  8672. var worldExtends = this.getWorldExtends();
  8673. // Update octree
  8674. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  8675. return this._selectionOctree;
  8676. };
  8677. // Picking
  8678. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8679. var engine = this._engine;
  8680. if (!camera) {
  8681. if (!this.activeCamera)
  8682. throw new Error("Active camera not set");
  8683. camera = this.activeCamera;
  8684. }
  8685. var cameraViewport = camera.viewport;
  8686. var viewport = cameraViewport.toGlobal(engine);
  8687. // Moving coordinates to local viewport world
  8688. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8689. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8690. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8691. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8692. };
  8693. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8694. var pickingInfo = null;
  8695. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8696. var mesh = this.meshes[meshIndex];
  8697. if (predicate) {
  8698. if (!predicate(mesh)) {
  8699. continue;
  8700. }
  8701. }
  8702. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8703. continue;
  8704. }
  8705. var world = mesh.getWorldMatrix();
  8706. var ray = rayFunction(world);
  8707. var result = mesh.intersects(ray, fastCheck);
  8708. if (!result || !result.hit)
  8709. continue;
  8710. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8711. continue;
  8712. pickingInfo = result;
  8713. if (fastCheck) {
  8714. break;
  8715. }
  8716. }
  8717. return pickingInfo || new BABYLON.PickingInfo();
  8718. };
  8719. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8720. var _this = this;
  8721. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8722. /// <param name="x">X position on screen</param>
  8723. /// <param name="y">Y position on screen</param>
  8724. /// <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>
  8725. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8726. /// <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>
  8727. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  8728. };
  8729. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8730. var _this = this;
  8731. return this._internalPick(function (world) {
  8732. if (!_this._pickWithRayInverseMatrix) {
  8733. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8734. }
  8735. world.invertToRef(_this._pickWithRayInverseMatrix);
  8736. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8737. }, predicate, fastCheck);
  8738. };
  8739. Scene.prototype.setPointerOverMesh = function (mesh) {
  8740. if (this._pointerOverMesh === mesh) {
  8741. return;
  8742. }
  8743. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8744. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8745. }
  8746. this._pointerOverMesh = mesh;
  8747. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8748. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8749. }
  8750. };
  8751. Scene.prototype.getPointerOverMesh = function () {
  8752. return this._pointerOverMesh;
  8753. };
  8754. // Physics
  8755. Scene.prototype.getPhysicsEngine = function () {
  8756. return this._physicsEngine;
  8757. };
  8758. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8759. if (this._physicsEngine) {
  8760. return true;
  8761. }
  8762. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8763. if (!this._physicsEngine.isSupported()) {
  8764. this._physicsEngine = null;
  8765. return false;
  8766. }
  8767. this._physicsEngine._initialize(gravity);
  8768. return true;
  8769. };
  8770. Scene.prototype.disablePhysicsEngine = function () {
  8771. if (!this._physicsEngine) {
  8772. return;
  8773. }
  8774. this._physicsEngine.dispose();
  8775. this._physicsEngine = undefined;
  8776. };
  8777. Scene.prototype.isPhysicsEnabled = function () {
  8778. return this._physicsEngine !== undefined;
  8779. };
  8780. Scene.prototype.setGravity = function (gravity) {
  8781. if (!this._physicsEngine) {
  8782. return;
  8783. }
  8784. this._physicsEngine._setGravity(gravity);
  8785. };
  8786. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8787. if (parts.parts) {
  8788. options = parts;
  8789. parts = parts.parts;
  8790. }
  8791. if (!this._physicsEngine) {
  8792. return null;
  8793. }
  8794. for (var index = 0; index < parts.length; index++) {
  8795. var mesh = parts[index].mesh;
  8796. mesh._physicImpostor = parts[index].impostor;
  8797. mesh._physicsMass = options.mass / parts.length;
  8798. mesh._physicsFriction = options.friction;
  8799. mesh._physicRestitution = options.restitution;
  8800. }
  8801. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8802. };
  8803. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8804. for (var index = 0; index < compound.parts.length; index++) {
  8805. var mesh = compound.parts[index].mesh;
  8806. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8807. this._physicsEngine._unregisterMesh(mesh);
  8808. }
  8809. };
  8810. // Misc.
  8811. Scene.prototype.createDefaultCameraOrLight = function () {
  8812. // Light
  8813. if (this.lights.length === 0) {
  8814. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  8815. }
  8816. // Camera
  8817. if (!this.activeCamera) {
  8818. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  8819. // Compute position
  8820. var worldExtends = this.getWorldExtends();
  8821. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  8822. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  8823. camera.setTarget(worldCenter);
  8824. this.activeCamera = camera;
  8825. }
  8826. };
  8827. // Tags
  8828. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  8829. if (tagsQuery === undefined) {
  8830. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8831. return list;
  8832. }
  8833. var listByTags = [];
  8834. forEach = forEach || (function (item) {
  8835. return;
  8836. });
  8837. for (var i in list) {
  8838. var item = list[i];
  8839. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8840. listByTags.push(item);
  8841. forEach(item);
  8842. }
  8843. }
  8844. return listByTags;
  8845. };
  8846. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  8847. return this._getByTags(this.meshes, tagsQuery, forEach);
  8848. };
  8849. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  8850. return this._getByTags(this.cameras, tagsQuery, forEach);
  8851. };
  8852. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  8853. return this._getByTags(this.lights, tagsQuery, forEach);
  8854. };
  8855. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  8856. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  8857. };
  8858. // Statics
  8859. Scene.FOGMODE_NONE = 0;
  8860. Scene.FOGMODE_EXP = 1;
  8861. Scene.FOGMODE_EXP2 = 2;
  8862. Scene.FOGMODE_LINEAR = 3;
  8863. Scene.MinDeltaTime = 1.0;
  8864. Scene.MaxDeltaTime = 1000.0;
  8865. return Scene;
  8866. })();
  8867. BABYLON.Scene = Scene;
  8868. })(BABYLON || (BABYLON = {}));
  8869. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  8870. (function (BABYLON) {
  8871. var VertexBuffer = (function () {
  8872. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8873. if (engine instanceof BABYLON.Mesh) {
  8874. this._engine = engine.getScene().getEngine();
  8875. }
  8876. else {
  8877. this._engine = engine;
  8878. }
  8879. this._updatable = updatable;
  8880. this._data = data;
  8881. if (!postponeInternalCreation) {
  8882. this.create();
  8883. }
  8884. this._kind = kind;
  8885. if (stride) {
  8886. this._strideSize = stride;
  8887. return;
  8888. }
  8889. switch (kind) {
  8890. case VertexBuffer.PositionKind:
  8891. this._strideSize = 3;
  8892. break;
  8893. case VertexBuffer.NormalKind:
  8894. this._strideSize = 3;
  8895. break;
  8896. case VertexBuffer.UVKind:
  8897. this._strideSize = 2;
  8898. break;
  8899. case VertexBuffer.UV2Kind:
  8900. this._strideSize = 2;
  8901. break;
  8902. case VertexBuffer.ColorKind:
  8903. this._strideSize = 4;
  8904. break;
  8905. case VertexBuffer.MatricesIndicesKind:
  8906. this._strideSize = 4;
  8907. break;
  8908. case VertexBuffer.MatricesWeightsKind:
  8909. this._strideSize = 4;
  8910. break;
  8911. }
  8912. }
  8913. // Properties
  8914. VertexBuffer.prototype.isUpdatable = function () {
  8915. return this._updatable;
  8916. };
  8917. VertexBuffer.prototype.getData = function () {
  8918. return this._data;
  8919. };
  8920. VertexBuffer.prototype.getBuffer = function () {
  8921. return this._buffer;
  8922. };
  8923. VertexBuffer.prototype.getStrideSize = function () {
  8924. return this._strideSize;
  8925. };
  8926. // Methods
  8927. VertexBuffer.prototype.create = function (data) {
  8928. if (!data && this._buffer) {
  8929. return; // nothing to do
  8930. }
  8931. data = data || this._data;
  8932. if (!this._buffer) {
  8933. if (this._updatable) {
  8934. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8935. }
  8936. else {
  8937. this._buffer = this._engine.createVertexBuffer(data);
  8938. }
  8939. }
  8940. if (this._updatable) {
  8941. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  8942. this._data = data;
  8943. }
  8944. };
  8945. VertexBuffer.prototype.update = function (data) {
  8946. this.create(data);
  8947. };
  8948. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  8949. if (!this._buffer) {
  8950. return;
  8951. }
  8952. if (this._updatable) {
  8953. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  8954. this._data = null;
  8955. }
  8956. };
  8957. VertexBuffer.prototype.dispose = function () {
  8958. if (!this._buffer) {
  8959. return;
  8960. }
  8961. if (this._engine._releaseBuffer(this._buffer)) {
  8962. this._buffer = null;
  8963. }
  8964. };
  8965. Object.defineProperty(VertexBuffer, "PositionKind", {
  8966. get: function () {
  8967. return VertexBuffer._PositionKind;
  8968. },
  8969. enumerable: true,
  8970. configurable: true
  8971. });
  8972. Object.defineProperty(VertexBuffer, "NormalKind", {
  8973. get: function () {
  8974. return VertexBuffer._NormalKind;
  8975. },
  8976. enumerable: true,
  8977. configurable: true
  8978. });
  8979. Object.defineProperty(VertexBuffer, "UVKind", {
  8980. get: function () {
  8981. return VertexBuffer._UVKind;
  8982. },
  8983. enumerable: true,
  8984. configurable: true
  8985. });
  8986. Object.defineProperty(VertexBuffer, "UV2Kind", {
  8987. get: function () {
  8988. return VertexBuffer._UV2Kind;
  8989. },
  8990. enumerable: true,
  8991. configurable: true
  8992. });
  8993. Object.defineProperty(VertexBuffer, "ColorKind", {
  8994. get: function () {
  8995. return VertexBuffer._ColorKind;
  8996. },
  8997. enumerable: true,
  8998. configurable: true
  8999. });
  9000. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9001. get: function () {
  9002. return VertexBuffer._MatricesIndicesKind;
  9003. },
  9004. enumerable: true,
  9005. configurable: true
  9006. });
  9007. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9008. get: function () {
  9009. return VertexBuffer._MatricesWeightsKind;
  9010. },
  9011. enumerable: true,
  9012. configurable: true
  9013. });
  9014. // Enums
  9015. VertexBuffer._PositionKind = "position";
  9016. VertexBuffer._NormalKind = "normal";
  9017. VertexBuffer._UVKind = "uv";
  9018. VertexBuffer._UV2Kind = "uv2";
  9019. VertexBuffer._ColorKind = "color";
  9020. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9021. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9022. return VertexBuffer;
  9023. })();
  9024. BABYLON.VertexBuffer = VertexBuffer;
  9025. })(BABYLON || (BABYLON = {}));
  9026. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9027. var BABYLON;
  9028. (function (BABYLON) {
  9029. var AbstractMesh = (function (_super) {
  9030. __extends(AbstractMesh, _super);
  9031. function AbstractMesh(name, scene) {
  9032. _super.call(this, name, scene);
  9033. // Properties
  9034. this.definedFacingForward = true; // orientation for POV movement & rotation
  9035. this.position = new BABYLON.Vector3(0, 0, 0);
  9036. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9037. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9038. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9039. this.visibility = 1.0;
  9040. this.alphaIndex = Number.MAX_VALUE;
  9041. this.infiniteDistance = false;
  9042. this.isVisible = true;
  9043. this.isPickable = true;
  9044. this.showBoundingBox = false;
  9045. this.showSubMeshesBoundingBox = false;
  9046. this.onDispose = null;
  9047. this.checkCollisions = false;
  9048. this.isBlocker = false;
  9049. this.renderingGroupId = 0;
  9050. this.receiveShadows = false;
  9051. this.renderOutline = false;
  9052. this.outlineColor = BABYLON.Color3.Red();
  9053. this.outlineWidth = 0.02;
  9054. this.renderOverlay = false;
  9055. this.overlayColor = BABYLON.Color3.Red();
  9056. this.overlayAlpha = 0.5;
  9057. this.hasVertexAlpha = false;
  9058. this.useVertexColors = true;
  9059. this.applyFog = true;
  9060. this.useOctreeForRenderingSelection = true;
  9061. this.useOctreeForPicking = true;
  9062. this.useOctreeForCollisions = true;
  9063. this.layerMask = 0xFFFFFFFF;
  9064. // Physics
  9065. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9066. // Collisions
  9067. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9068. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9069. this._collider = new BABYLON.Collider();
  9070. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9071. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9072. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9073. // Cache
  9074. this._localScaling = BABYLON.Matrix.Zero();
  9075. this._localRotation = BABYLON.Matrix.Zero();
  9076. this._localTranslation = BABYLON.Matrix.Zero();
  9077. this._localBillboard = BABYLON.Matrix.Zero();
  9078. this._localPivotScaling = BABYLON.Matrix.Zero();
  9079. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9080. this._localWorld = BABYLON.Matrix.Zero();
  9081. this._worldMatrix = BABYLON.Matrix.Zero();
  9082. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9083. this._absolutePosition = BABYLON.Vector3.Zero();
  9084. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9085. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9086. this._isDirty = false;
  9087. this._pivotMatrix = BABYLON.Matrix.Identity();
  9088. this._isDisposed = false;
  9089. this._renderId = 0;
  9090. this._intersectionsInProgress = new Array();
  9091. this._onAfterWorldMatrixUpdate = new Array();
  9092. scene.meshes.push(this);
  9093. }
  9094. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9095. get: function () {
  9096. return AbstractMesh._BILLBOARDMODE_NONE;
  9097. },
  9098. enumerable: true,
  9099. configurable: true
  9100. });
  9101. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9102. get: function () {
  9103. return AbstractMesh._BILLBOARDMODE_X;
  9104. },
  9105. enumerable: true,
  9106. configurable: true
  9107. });
  9108. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9109. get: function () {
  9110. return AbstractMesh._BILLBOARDMODE_Y;
  9111. },
  9112. enumerable: true,
  9113. configurable: true
  9114. });
  9115. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9116. get: function () {
  9117. return AbstractMesh._BILLBOARDMODE_Z;
  9118. },
  9119. enumerable: true,
  9120. configurable: true
  9121. });
  9122. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9123. get: function () {
  9124. return AbstractMesh._BILLBOARDMODE_ALL;
  9125. },
  9126. enumerable: true,
  9127. configurable: true
  9128. });
  9129. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9130. // Methods
  9131. get: function () {
  9132. return false;
  9133. },
  9134. enumerable: true,
  9135. configurable: true
  9136. });
  9137. AbstractMesh.prototype.getLOD = function (camera) {
  9138. return this;
  9139. };
  9140. AbstractMesh.prototype.getTotalVertices = function () {
  9141. return 0;
  9142. };
  9143. AbstractMesh.prototype.getIndices = function () {
  9144. return null;
  9145. };
  9146. AbstractMesh.prototype.getVerticesData = function (kind) {
  9147. return null;
  9148. };
  9149. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9150. return false;
  9151. };
  9152. AbstractMesh.prototype.getBoundingInfo = function () {
  9153. if (this._masterMesh) {
  9154. return this._masterMesh.getBoundingInfo();
  9155. }
  9156. if (!this._boundingInfo) {
  9157. this._updateBoundingInfo();
  9158. }
  9159. return this._boundingInfo;
  9160. };
  9161. AbstractMesh.prototype._preActivate = function () {
  9162. };
  9163. AbstractMesh.prototype._activate = function (renderId) {
  9164. this._renderId = renderId;
  9165. };
  9166. AbstractMesh.prototype.getWorldMatrix = function () {
  9167. if (this._masterMesh) {
  9168. return this._masterMesh.getWorldMatrix();
  9169. }
  9170. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9171. this.computeWorldMatrix();
  9172. }
  9173. return this._worldMatrix;
  9174. };
  9175. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9176. get: function () {
  9177. return this._worldMatrix;
  9178. },
  9179. enumerable: true,
  9180. configurable: true
  9181. });
  9182. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9183. get: function () {
  9184. return this._absolutePosition;
  9185. },
  9186. enumerable: true,
  9187. configurable: true
  9188. });
  9189. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9190. if (!this.rotationQuaternion) {
  9191. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9192. this.rotation = BABYLON.Vector3.Zero();
  9193. }
  9194. if (!space || space == 0 /* LOCAL */) {
  9195. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9196. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9197. }
  9198. else {
  9199. if (this.parent) {
  9200. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9201. invertParentWorldMatrix.invert();
  9202. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9203. }
  9204. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9205. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9206. }
  9207. };
  9208. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9209. var displacementVector = axis.scale(distance);
  9210. if (!space || space == 0 /* LOCAL */) {
  9211. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9212. this.setPositionWithLocalVector(tempV3);
  9213. }
  9214. else {
  9215. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9216. }
  9217. };
  9218. AbstractMesh.prototype.getAbsolutePosition = function () {
  9219. this.computeWorldMatrix();
  9220. return this._absolutePosition;
  9221. };
  9222. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9223. if (!absolutePosition) {
  9224. return;
  9225. }
  9226. var absolutePositionX;
  9227. var absolutePositionY;
  9228. var absolutePositionZ;
  9229. if (absolutePosition.x === undefined) {
  9230. if (arguments.length < 3) {
  9231. return;
  9232. }
  9233. absolutePositionX = arguments[0];
  9234. absolutePositionY = arguments[1];
  9235. absolutePositionZ = arguments[2];
  9236. }
  9237. else {
  9238. absolutePositionX = absolutePosition.x;
  9239. absolutePositionY = absolutePosition.y;
  9240. absolutePositionZ = absolutePosition.z;
  9241. }
  9242. if (this.parent) {
  9243. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9244. invertParentWorldMatrix.invert();
  9245. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9246. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9247. }
  9248. else {
  9249. this.position.x = absolutePositionX;
  9250. this.position.y = absolutePositionY;
  9251. this.position.z = absolutePositionZ;
  9252. }
  9253. };
  9254. // ================================== Point of View Movement =================================
  9255. /**
  9256. * Perform relative position change from the point of view of behind the front of the mesh.
  9257. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9258. * Supports definition of mesh facing forward or backward.
  9259. * @param {number} amountRight
  9260. * @param {number} amountUp
  9261. * @param {number} amountForward
  9262. */
  9263. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9264. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9265. };
  9266. /**
  9267. * Calculate relative position change from the point of view of behind the front of the mesh.
  9268. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9269. * Supports definition of mesh facing forward or backward.
  9270. * @param {number} amountRight
  9271. * @param {number} amountUp
  9272. * @param {number} amountForward
  9273. */
  9274. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9275. var rotMatrix = new BABYLON.Matrix();
  9276. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9277. rotQuaternion.toRotationMatrix(rotMatrix);
  9278. var translationDelta = BABYLON.Vector3.Zero();
  9279. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9280. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9281. return translationDelta;
  9282. };
  9283. // ================================== Point of View Rotation =================================
  9284. /**
  9285. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9286. * Supports definition of mesh facing forward or backward.
  9287. * @param {number} flipBack
  9288. * @param {number} twirlClockwise
  9289. * @param {number} tiltRight
  9290. */
  9291. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9292. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9293. };
  9294. /**
  9295. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9296. * Supports definition of mesh facing forward or backward.
  9297. * @param {number} flipBack
  9298. * @param {number} twirlClockwise
  9299. * @param {number} tiltRight
  9300. */
  9301. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9302. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9303. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9304. };
  9305. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9306. this._pivotMatrix = matrix;
  9307. this._cache.pivotMatrixUpdated = true;
  9308. };
  9309. AbstractMesh.prototype.getPivotMatrix = function () {
  9310. return this._pivotMatrix;
  9311. };
  9312. AbstractMesh.prototype._isSynchronized = function () {
  9313. if (this._isDirty) {
  9314. return false;
  9315. }
  9316. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9317. return false;
  9318. if (this._cache.pivotMatrixUpdated) {
  9319. return false;
  9320. }
  9321. if (this.infiniteDistance) {
  9322. return false;
  9323. }
  9324. if (!this._cache.position.equals(this.position))
  9325. return false;
  9326. if (this.rotationQuaternion) {
  9327. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9328. return false;
  9329. }
  9330. else {
  9331. if (!this._cache.rotation.equals(this.rotation))
  9332. return false;
  9333. }
  9334. if (!this._cache.scaling.equals(this.scaling))
  9335. return false;
  9336. return true;
  9337. };
  9338. AbstractMesh.prototype._initCache = function () {
  9339. _super.prototype._initCache.call(this);
  9340. this._cache.localMatrixUpdated = false;
  9341. this._cache.position = BABYLON.Vector3.Zero();
  9342. this._cache.scaling = BABYLON.Vector3.Zero();
  9343. this._cache.rotation = BABYLON.Vector3.Zero();
  9344. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9345. };
  9346. AbstractMesh.prototype.markAsDirty = function (property) {
  9347. if (property === "rotation") {
  9348. this.rotationQuaternion = null;
  9349. }
  9350. this._currentRenderId = Number.MAX_VALUE;
  9351. this._isDirty = true;
  9352. };
  9353. AbstractMesh.prototype._updateBoundingInfo = function () {
  9354. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9355. this._boundingInfo._update(this.worldMatrixFromCache);
  9356. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9357. };
  9358. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9359. if (!this.subMeshes) {
  9360. return;
  9361. }
  9362. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9363. var subMesh = this.subMeshes[subIndex];
  9364. subMesh.updateBoundingInfo(matrix);
  9365. }
  9366. };
  9367. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9368. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9369. return this._worldMatrix;
  9370. }
  9371. this._cache.position.copyFrom(this.position);
  9372. this._cache.scaling.copyFrom(this.scaling);
  9373. this._cache.pivotMatrixUpdated = false;
  9374. this._currentRenderId = this.getScene().getRenderId();
  9375. this._isDirty = false;
  9376. // Scaling
  9377. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9378. // Rotation
  9379. if (this.rotationQuaternion) {
  9380. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9381. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9382. }
  9383. else {
  9384. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9385. this._cache.rotation.copyFrom(this.rotation);
  9386. }
  9387. // Translation
  9388. if (this.infiniteDistance && !this.parent) {
  9389. var camera = this.getScene().activeCamera;
  9390. var cameraWorldMatrix = camera.getWorldMatrix();
  9391. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9392. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9393. }
  9394. else {
  9395. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9396. }
  9397. // Composing transformations
  9398. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9399. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9400. // Billboarding
  9401. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9402. var localPosition = this.position.clone();
  9403. var zero = this.getScene().activeCamera.position.clone();
  9404. if (this.parent && this.parent.position) {
  9405. localPosition.addInPlace(this.parent.position);
  9406. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9407. }
  9408. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9409. zero = this.getScene().activeCamera.position;
  9410. }
  9411. else {
  9412. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9413. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9414. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9415. zero.y = localPosition.y + 0.001;
  9416. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9417. zero.z = localPosition.z + 0.001;
  9418. }
  9419. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9420. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9421. this._localBillboard.invert();
  9422. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9423. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9424. }
  9425. // Local world
  9426. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9427. // Parent
  9428. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9429. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9430. }
  9431. else {
  9432. this._worldMatrix.copyFrom(this._localWorld);
  9433. }
  9434. // Bounding info
  9435. this._updateBoundingInfo();
  9436. // Absolute position
  9437. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9438. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9439. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9440. }
  9441. return this._worldMatrix;
  9442. };
  9443. /**
  9444. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9445. * @param func: callback function to add
  9446. */
  9447. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9448. this._onAfterWorldMatrixUpdate.push(func);
  9449. };
  9450. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9451. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  9452. if (index > -1) {
  9453. this._onAfterWorldMatrixUpdate.splice(index, 1);
  9454. }
  9455. };
  9456. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9457. this.computeWorldMatrix();
  9458. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9459. };
  9460. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9461. this.computeWorldMatrix();
  9462. var invLocalWorldMatrix = this._localWorld.clone();
  9463. invLocalWorldMatrix.invert();
  9464. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9465. };
  9466. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9467. this.computeWorldMatrix();
  9468. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9469. };
  9470. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9471. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9472. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9473. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9474. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9475. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9476. /// <returns>Mesh oriented towards targetMesh</returns>
  9477. yawCor = yawCor || 0; // default to zero if undefined
  9478. pitchCor = pitchCor || 0;
  9479. rollCor = rollCor || 0;
  9480. var dv = targetPoint.subtract(this.position);
  9481. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9482. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9483. var pitch = Math.atan2(dv.y, len);
  9484. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9485. };
  9486. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9487. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9488. return false;
  9489. }
  9490. return true;
  9491. };
  9492. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9493. if (!camera) {
  9494. camera = this.getScene().activeCamera;
  9495. }
  9496. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9497. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9498. return false;
  9499. }
  9500. return true;
  9501. };
  9502. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9503. if (!this._boundingInfo || !mesh._boundingInfo) {
  9504. return false;
  9505. }
  9506. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9507. };
  9508. AbstractMesh.prototype.intersectsPoint = function (point) {
  9509. if (!this._boundingInfo) {
  9510. return false;
  9511. }
  9512. return this._boundingInfo.intersectsPoint(point);
  9513. };
  9514. // Physics
  9515. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9516. var physicsEngine = this.getScene().getPhysicsEngine();
  9517. if (!physicsEngine) {
  9518. return;
  9519. }
  9520. if (impostor.impostor) {
  9521. // Old API
  9522. options = impostor;
  9523. impostor = impostor.impostor;
  9524. }
  9525. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9526. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9527. physicsEngine._unregisterMesh(this);
  9528. return;
  9529. }
  9530. options.mass = options.mass || 0;
  9531. options.friction = options.friction || 0.2;
  9532. options.restitution = options.restitution || 0.2;
  9533. this._physicImpostor = impostor;
  9534. this._physicsMass = options.mass;
  9535. this._physicsFriction = options.friction;
  9536. this._physicRestitution = options.restitution;
  9537. return physicsEngine._registerMesh(this, impostor, options);
  9538. };
  9539. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9540. if (!this._physicImpostor) {
  9541. return BABYLON.PhysicsEngine.NoImpostor;
  9542. }
  9543. return this._physicImpostor;
  9544. };
  9545. AbstractMesh.prototype.getPhysicsMass = function () {
  9546. if (!this._physicsMass) {
  9547. return 0;
  9548. }
  9549. return this._physicsMass;
  9550. };
  9551. AbstractMesh.prototype.getPhysicsFriction = function () {
  9552. if (!this._physicsFriction) {
  9553. return 0;
  9554. }
  9555. return this._physicsFriction;
  9556. };
  9557. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9558. if (!this._physicRestitution) {
  9559. return 0;
  9560. }
  9561. return this._physicRestitution;
  9562. };
  9563. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9564. if (!camera) {
  9565. camera = this.getScene().activeCamera;
  9566. }
  9567. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9568. };
  9569. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9570. if (!camera) {
  9571. camera = this.getScene().activeCamera;
  9572. }
  9573. return this.absolutePosition.subtract(camera.position).length();
  9574. };
  9575. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9576. if (!this._physicImpostor) {
  9577. return;
  9578. }
  9579. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9580. };
  9581. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9582. if (!this._physicImpostor) {
  9583. return;
  9584. }
  9585. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9586. };
  9587. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9588. if (!this._physicImpostor) {
  9589. return;
  9590. }
  9591. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9592. };
  9593. // Collisions
  9594. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9595. var globalPosition = this.getAbsolutePosition();
  9596. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9597. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9598. this._collider.radius = this.ellipsoid;
  9599. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  9600. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  9601. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9602. this.position.addInPlace(this._diffPositionForCollisions);
  9603. }
  9604. };
  9605. // Submeshes octree
  9606. /**
  9607. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9608. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9609. */
  9610. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9611. if (maxCapacity === void 0) { maxCapacity = 64; }
  9612. if (maxDepth === void 0) { maxDepth = 2; }
  9613. if (!this._submeshesOctree) {
  9614. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9615. }
  9616. this.computeWorldMatrix(true);
  9617. // Update octree
  9618. var bbox = this.getBoundingInfo().boundingBox;
  9619. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9620. return this._submeshesOctree;
  9621. };
  9622. // Collisions
  9623. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9624. this._generatePointsArray();
  9625. // Transformation
  9626. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9627. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9628. subMesh._lastColliderWorldVertices = [];
  9629. subMesh._trianglePlanes = [];
  9630. var start = subMesh.verticesStart;
  9631. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9632. for (var i = start; i < end; i++) {
  9633. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9634. }
  9635. }
  9636. // Collide
  9637. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  9638. };
  9639. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9640. var subMeshes;
  9641. var len;
  9642. // Octrees
  9643. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9644. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9645. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9646. len = intersections.length;
  9647. subMeshes = intersections.data;
  9648. }
  9649. else {
  9650. subMeshes = this.subMeshes;
  9651. len = subMeshes.length;
  9652. }
  9653. for (var index = 0; index < len; index++) {
  9654. var subMesh = subMeshes[index];
  9655. // Bounding test
  9656. if (len > 1 && !subMesh._checkCollision(collider))
  9657. continue;
  9658. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9659. }
  9660. };
  9661. AbstractMesh.prototype._checkCollision = function (collider) {
  9662. // Bounding box test
  9663. if (!this._boundingInfo._checkCollision(collider))
  9664. return;
  9665. // Transformation matrix
  9666. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9667. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9668. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9669. };
  9670. // Picking
  9671. AbstractMesh.prototype._generatePointsArray = function () {
  9672. return false;
  9673. };
  9674. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9675. var pickingInfo = new BABYLON.PickingInfo();
  9676. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9677. return pickingInfo;
  9678. }
  9679. if (!this._generatePointsArray()) {
  9680. return pickingInfo;
  9681. }
  9682. var intersectInfo = null;
  9683. // Octrees
  9684. var subMeshes;
  9685. var len;
  9686. if (this._submeshesOctree && this.useOctreeForPicking) {
  9687. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9688. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9689. len = intersections.length;
  9690. subMeshes = intersections.data;
  9691. }
  9692. else {
  9693. subMeshes = this.subMeshes;
  9694. len = subMeshes.length;
  9695. }
  9696. for (var index = 0; index < len; index++) {
  9697. var subMesh = subMeshes[index];
  9698. // Bounding test
  9699. if (len > 1 && !subMesh.canIntersects(ray))
  9700. continue;
  9701. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9702. if (currentIntersectInfo) {
  9703. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9704. intersectInfo = currentIntersectInfo;
  9705. if (fastCheck) {
  9706. break;
  9707. }
  9708. }
  9709. }
  9710. }
  9711. if (intersectInfo) {
  9712. // Get picked point
  9713. var world = this.getWorldMatrix();
  9714. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9715. var direction = ray.direction.clone();
  9716. direction = direction.scale(intersectInfo.distance);
  9717. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9718. var pickedPoint = worldOrigin.add(worldDirection);
  9719. // Return result
  9720. pickingInfo.hit = true;
  9721. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9722. pickingInfo.pickedPoint = pickedPoint;
  9723. pickingInfo.pickedMesh = this;
  9724. pickingInfo.bu = intersectInfo.bu;
  9725. pickingInfo.bv = intersectInfo.bv;
  9726. pickingInfo.faceId = intersectInfo.faceId;
  9727. return pickingInfo;
  9728. }
  9729. return pickingInfo;
  9730. };
  9731. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9732. return null;
  9733. };
  9734. AbstractMesh.prototype.releaseSubMeshes = function () {
  9735. if (this.subMeshes) {
  9736. while (this.subMeshes.length) {
  9737. this.subMeshes[0].dispose();
  9738. }
  9739. }
  9740. else {
  9741. this.subMeshes = new Array();
  9742. }
  9743. };
  9744. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9745. // Physics
  9746. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9747. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9748. }
  9749. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9750. var other = this._intersectionsInProgress[index];
  9751. var pos = other._intersectionsInProgress.indexOf(this);
  9752. other._intersectionsInProgress.splice(pos, 1);
  9753. }
  9754. this._intersectionsInProgress = [];
  9755. // SubMeshes
  9756. this.releaseSubMeshes();
  9757. // Remove from scene
  9758. var index = this.getScene().meshes.indexOf(this);
  9759. if (index != -1) {
  9760. // Remove from the scene if mesh found
  9761. this.getScene().meshes.splice(index, 1);
  9762. }
  9763. if (!doNotRecurse) {
  9764. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9765. if (this.getScene().particleSystems[index].emitter == this) {
  9766. this.getScene().particleSystems[index].dispose();
  9767. index--;
  9768. }
  9769. }
  9770. // Children
  9771. var objects = this.getScene().meshes.slice(0);
  9772. for (index = 0; index < objects.length; index++) {
  9773. if (objects[index].parent == this) {
  9774. objects[index].dispose();
  9775. }
  9776. }
  9777. }
  9778. else {
  9779. for (index = 0; index < this.getScene().meshes.length; index++) {
  9780. var obj = this.getScene().meshes[index];
  9781. if (obj.parent === this) {
  9782. obj.parent = null;
  9783. obj.computeWorldMatrix(true);
  9784. }
  9785. }
  9786. }
  9787. this._onAfterWorldMatrixUpdate = [];
  9788. this._isDisposed = true;
  9789. // Callback
  9790. if (this.onDispose) {
  9791. this.onDispose();
  9792. }
  9793. };
  9794. // Statics
  9795. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9796. AbstractMesh._BILLBOARDMODE_X = 1;
  9797. AbstractMesh._BILLBOARDMODE_Y = 2;
  9798. AbstractMesh._BILLBOARDMODE_Z = 4;
  9799. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9800. return AbstractMesh;
  9801. })(BABYLON.Node);
  9802. BABYLON.AbstractMesh = AbstractMesh;
  9803. })(BABYLON || (BABYLON = {}));
  9804. //# sourceMappingURL=babylon.abstractMesh.js.map
  9805. var BABYLON;
  9806. (function (BABYLON) {
  9807. var _InstancesBatch = (function () {
  9808. function _InstancesBatch() {
  9809. this.mustReturn = false;
  9810. this.visibleInstances = new Array();
  9811. this.renderSelf = new Array();
  9812. }
  9813. return _InstancesBatch;
  9814. })();
  9815. BABYLON._InstancesBatch = _InstancesBatch;
  9816. var Mesh = (function (_super) {
  9817. __extends(Mesh, _super);
  9818. /**
  9819. * @constructor
  9820. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9821. * @param {Scene} scene - The scene to add this mesh to.
  9822. * @param {Node} parent - The parent of this mesh, if it has one
  9823. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9824. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9825. * When false, achieved by calling a clone(), also passing False.
  9826. * This will make creation of children, recursive.
  9827. */
  9828. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9829. if (parent === void 0) { parent = null; }
  9830. _super.call(this, name, scene);
  9831. // Members
  9832. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9833. this.instances = new Array();
  9834. this._LODLevels = new Array();
  9835. this._onBeforeRenderCallbacks = new Array();
  9836. this._onAfterRenderCallbacks = new Array();
  9837. this._visibleInstances = {};
  9838. this._renderIdForInstances = new Array();
  9839. this._batchCache = new _InstancesBatch();
  9840. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  9841. if (source) {
  9842. // Geometry
  9843. if (source._geometry) {
  9844. source._geometry.applyToMesh(this);
  9845. }
  9846. // Deep copy
  9847. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9848. // Material
  9849. this.material = source.material;
  9850. if (!doNotCloneChildren) {
  9851. for (var index = 0; index < scene.meshes.length; index++) {
  9852. var mesh = scene.meshes[index];
  9853. if (mesh.parent === source) {
  9854. // doNotCloneChildren is always going to be False
  9855. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  9856. }
  9857. }
  9858. }
  9859. for (index = 0; index < scene.particleSystems.length; index++) {
  9860. var system = scene.particleSystems[index];
  9861. if (system.emitter === source) {
  9862. system.clone(system.name, this);
  9863. }
  9864. }
  9865. this.computeWorldMatrix(true);
  9866. }
  9867. // Parent
  9868. if (parent !== null) {
  9869. this.parent = parent;
  9870. }
  9871. }
  9872. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  9873. // Methods
  9874. get: function () {
  9875. return this._LODLevels.length > 0;
  9876. },
  9877. enumerable: true,
  9878. configurable: true
  9879. });
  9880. Mesh.prototype._sortLODLevels = function () {
  9881. this._LODLevels.sort(function (a, b) {
  9882. if (a.distance < b.distance) {
  9883. return 1;
  9884. }
  9885. if (a.distance > b.distance) {
  9886. return -1;
  9887. }
  9888. return 0;
  9889. });
  9890. };
  9891. /**
  9892. * Add a mesh as LOD level triggered at the given distance.
  9893. * @param {number} distance - the distance from the center of the object to show this level
  9894. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  9895. * @return {BABYLON.Mesh} this mesh (for chaining)
  9896. */
  9897. Mesh.prototype.addLODLevel = function (distance, mesh) {
  9898. if (mesh && mesh._masterMesh) {
  9899. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  9900. return this;
  9901. }
  9902. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  9903. this._LODLevels.push(level);
  9904. if (mesh) {
  9905. mesh._masterMesh = this;
  9906. }
  9907. this._sortLODLevels();
  9908. return this;
  9909. };
  9910. /**
  9911. * Remove a mesh from the LOD array
  9912. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  9913. * @return {BABYLON.Mesh} this mesh (for chaining)
  9914. */
  9915. Mesh.prototype.removeLODLevel = function (mesh) {
  9916. for (var index = 0; index < this._LODLevels.length; index++) {
  9917. if (this._LODLevels[index].mesh === mesh) {
  9918. this._LODLevels.splice(index, 1);
  9919. if (mesh) {
  9920. mesh._masterMesh = null;
  9921. }
  9922. }
  9923. }
  9924. this._sortLODLevels();
  9925. return this;
  9926. };
  9927. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9928. if (!this._LODLevels || this._LODLevels.length === 0) {
  9929. return this;
  9930. }
  9931. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  9932. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  9933. return this;
  9934. }
  9935. for (var index = 0; index < this._LODLevels.length; index++) {
  9936. var level = this._LODLevels[index];
  9937. if (level.distance < distanceToCamera) {
  9938. if (level.mesh) {
  9939. level.mesh._preActivate();
  9940. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9941. }
  9942. return level.mesh;
  9943. }
  9944. }
  9945. return this;
  9946. };
  9947. Object.defineProperty(Mesh.prototype, "geometry", {
  9948. get: function () {
  9949. return this._geometry;
  9950. },
  9951. enumerable: true,
  9952. configurable: true
  9953. });
  9954. Mesh.prototype.getTotalVertices = function () {
  9955. if (!this._geometry) {
  9956. return 0;
  9957. }
  9958. return this._geometry.getTotalVertices();
  9959. };
  9960. Mesh.prototype.getVerticesData = function (kind) {
  9961. if (!this._geometry) {
  9962. return null;
  9963. }
  9964. return this._geometry.getVerticesData(kind);
  9965. };
  9966. Mesh.prototype.getVertexBuffer = function (kind) {
  9967. if (!this._geometry) {
  9968. return undefined;
  9969. }
  9970. return this._geometry.getVertexBuffer(kind);
  9971. };
  9972. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9973. if (!this._geometry) {
  9974. if (this._delayInfo) {
  9975. return this._delayInfo.indexOf(kind) !== -1;
  9976. }
  9977. return false;
  9978. }
  9979. return this._geometry.isVerticesDataPresent(kind);
  9980. };
  9981. Mesh.prototype.getVerticesDataKinds = function () {
  9982. if (!this._geometry) {
  9983. var result = [];
  9984. if (this._delayInfo) {
  9985. for (var kind in this._delayInfo) {
  9986. result.push(kind);
  9987. }
  9988. }
  9989. return result;
  9990. }
  9991. return this._geometry.getVerticesDataKinds();
  9992. };
  9993. Mesh.prototype.getTotalIndices = function () {
  9994. if (!this._geometry) {
  9995. return 0;
  9996. }
  9997. return this._geometry.getTotalIndices();
  9998. };
  9999. Mesh.prototype.getIndices = function () {
  10000. if (!this._geometry) {
  10001. return [];
  10002. }
  10003. return this._geometry.getIndices();
  10004. };
  10005. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10006. get: function () {
  10007. return this._masterMesh !== null && this._masterMesh !== undefined;
  10008. },
  10009. enumerable: true,
  10010. configurable: true
  10011. });
  10012. Mesh.prototype.isReady = function () {
  10013. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10014. return false;
  10015. }
  10016. return _super.prototype.isReady.call(this);
  10017. };
  10018. Mesh.prototype.isDisposed = function () {
  10019. return this._isDisposed;
  10020. };
  10021. // Methods
  10022. Mesh.prototype._preActivate = function () {
  10023. var sceneRenderId = this.getScene().getRenderId();
  10024. if (this._preActivateId == sceneRenderId) {
  10025. return;
  10026. }
  10027. this._preActivateId = sceneRenderId;
  10028. this._visibleInstances = null;
  10029. };
  10030. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10031. if (!this._visibleInstances) {
  10032. this._visibleInstances = {};
  10033. this._visibleInstances.defaultRenderId = renderId;
  10034. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10035. }
  10036. if (!this._visibleInstances[renderId]) {
  10037. this._visibleInstances[renderId] = new Array();
  10038. }
  10039. this._visibleInstances[renderId].push(instance);
  10040. };
  10041. Mesh.prototype.refreshBoundingInfo = function () {
  10042. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10043. if (data) {
  10044. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10045. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10046. }
  10047. if (this.subMeshes) {
  10048. for (var index = 0; index < this.subMeshes.length; index++) {
  10049. this.subMeshes[index].refreshBoundingInfo();
  10050. }
  10051. }
  10052. this._updateBoundingInfo();
  10053. };
  10054. Mesh.prototype._createGlobalSubMesh = function () {
  10055. var totalVertices = this.getTotalVertices();
  10056. if (!totalVertices || !this.getIndices()) {
  10057. return null;
  10058. }
  10059. this.releaseSubMeshes();
  10060. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10061. };
  10062. Mesh.prototype.subdivide = function (count) {
  10063. if (count < 1) {
  10064. return;
  10065. }
  10066. var totalIndices = this.getTotalIndices();
  10067. var subdivisionSize = (totalIndices / count) | 0;
  10068. var offset = 0;
  10069. while (subdivisionSize % 3 != 0) {
  10070. subdivisionSize++;
  10071. }
  10072. this.releaseSubMeshes();
  10073. for (var index = 0; index < count; index++) {
  10074. if (offset >= totalIndices) {
  10075. break;
  10076. }
  10077. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10078. offset += subdivisionSize;
  10079. }
  10080. this.synchronizeInstances();
  10081. };
  10082. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10083. if (kind instanceof Array) {
  10084. var temp = data;
  10085. data = kind;
  10086. kind = temp;
  10087. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10088. }
  10089. if (!this._geometry) {
  10090. var vertexData = new BABYLON.VertexData();
  10091. vertexData.set(data, kind);
  10092. var scene = this.getScene();
  10093. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10094. }
  10095. else {
  10096. this._geometry.setVerticesData(kind, data, updatable, stride);
  10097. }
  10098. };
  10099. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10100. if (!this._geometry) {
  10101. return;
  10102. }
  10103. if (!makeItUnique) {
  10104. this._geometry.updateVerticesData(kind, data, updateExtends);
  10105. }
  10106. else {
  10107. this.makeGeometryUnique();
  10108. this.updateVerticesData(kind, data, updateExtends, false);
  10109. }
  10110. };
  10111. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10112. if (!this._geometry) {
  10113. return;
  10114. }
  10115. if (!makeItUnique) {
  10116. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10117. }
  10118. else {
  10119. this.makeGeometryUnique();
  10120. this.updateVerticesDataDirectly(kind, data, offset, false);
  10121. }
  10122. };
  10123. Mesh.prototype.makeGeometryUnique = function () {
  10124. if (!this._geometry) {
  10125. return;
  10126. }
  10127. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10128. geometry.applyToMesh(this);
  10129. };
  10130. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10131. if (!this._geometry) {
  10132. var vertexData = new BABYLON.VertexData();
  10133. vertexData.indices = indices;
  10134. var scene = this.getScene();
  10135. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10136. }
  10137. else {
  10138. this._geometry.setIndices(indices, totalVertices);
  10139. }
  10140. };
  10141. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10142. var engine = this.getScene().getEngine();
  10143. // Wireframe
  10144. var indexToBind;
  10145. switch (fillMode) {
  10146. case BABYLON.Material.PointFillMode:
  10147. indexToBind = null;
  10148. break;
  10149. case BABYLON.Material.WireFrameFillMode:
  10150. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10151. break;
  10152. default:
  10153. case BABYLON.Material.TriangleFillMode:
  10154. indexToBind = this._geometry.getIndexBuffer();
  10155. break;
  10156. }
  10157. // VBOs
  10158. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10159. };
  10160. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10161. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10162. return;
  10163. }
  10164. var engine = this.getScene().getEngine();
  10165. switch (fillMode) {
  10166. case BABYLON.Material.PointFillMode:
  10167. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10168. break;
  10169. case BABYLON.Material.WireFrameFillMode:
  10170. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10171. break;
  10172. default:
  10173. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10174. }
  10175. };
  10176. Mesh.prototype.registerBeforeRender = function (func) {
  10177. this._onBeforeRenderCallbacks.push(func);
  10178. };
  10179. Mesh.prototype.unregisterBeforeRender = function (func) {
  10180. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10181. if (index > -1) {
  10182. this._onBeforeRenderCallbacks.splice(index, 1);
  10183. }
  10184. };
  10185. Mesh.prototype.registerAfterRender = function (func) {
  10186. this._onAfterRenderCallbacks.push(func);
  10187. };
  10188. Mesh.prototype.unregisterAfterRender = function (func) {
  10189. var index = this._onAfterRenderCallbacks.indexOf(func);
  10190. if (index > -1) {
  10191. this._onAfterRenderCallbacks.splice(index, 1);
  10192. }
  10193. };
  10194. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10195. var scene = this.getScene();
  10196. this._batchCache.mustReturn = false;
  10197. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10198. this._batchCache.visibleInstances[subMeshId] = null;
  10199. if (this._visibleInstances) {
  10200. var currentRenderId = scene.getRenderId();
  10201. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10202. var selfRenderId = this._renderId;
  10203. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10204. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10205. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10206. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10207. }
  10208. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10209. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10210. this._batchCache.mustReturn = true;
  10211. return this._batchCache;
  10212. }
  10213. if (currentRenderId !== selfRenderId) {
  10214. this._batchCache.renderSelf[subMeshId] = false;
  10215. }
  10216. }
  10217. this._renderIdForInstances[subMeshId] = currentRenderId;
  10218. }
  10219. return this._batchCache;
  10220. };
  10221. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10222. var visibleInstances = batch.visibleInstances[subMesh._id];
  10223. var matricesCount = visibleInstances.length + 1;
  10224. var bufferSize = matricesCount * 16 * 4;
  10225. while (this._instancesBufferSize < bufferSize) {
  10226. this._instancesBufferSize *= 2;
  10227. }
  10228. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10229. if (this._worldMatricesInstancesBuffer) {
  10230. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10231. }
  10232. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10233. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10234. }
  10235. var offset = 0;
  10236. var instancesCount = 0;
  10237. var world = this.getWorldMatrix();
  10238. if (batch.renderSelf[subMesh._id]) {
  10239. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10240. offset += 16;
  10241. instancesCount++;
  10242. }
  10243. if (visibleInstances) {
  10244. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10245. var instance = visibleInstances[instanceIndex];
  10246. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10247. offset += 16;
  10248. instancesCount++;
  10249. }
  10250. }
  10251. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10252. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10253. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10254. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10255. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10256. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10257. this._draw(subMesh, fillMode, instancesCount);
  10258. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10259. };
  10260. Mesh.prototype.render = function (subMesh) {
  10261. var scene = this.getScene();
  10262. // Managing instances
  10263. var batch = this._getInstancesRenderList(subMesh._id);
  10264. if (batch.mustReturn) {
  10265. return;
  10266. }
  10267. // Checking geometry state
  10268. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10269. return;
  10270. }
  10271. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10272. this._onBeforeRenderCallbacks[callbackIndex]();
  10273. }
  10274. var engine = scene.getEngine();
  10275. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10276. // Material
  10277. var effectiveMaterial = subMesh.getMaterial();
  10278. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10279. return;
  10280. }
  10281. // Outline - step 1
  10282. var savedDepthWrite = engine.getDepthWrite();
  10283. if (this.renderOutline) {
  10284. engine.setDepthWrite(false);
  10285. scene.getOutlineRenderer().render(subMesh, batch);
  10286. engine.setDepthWrite(savedDepthWrite);
  10287. }
  10288. effectiveMaterial._preBind();
  10289. var effect = effectiveMaterial.getEffect();
  10290. // Bind
  10291. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10292. this._bind(subMesh, effect, fillMode);
  10293. var world = this.getWorldMatrix();
  10294. effectiveMaterial.bind(world, this);
  10295. // Instances rendering
  10296. if (hardwareInstancedRendering) {
  10297. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10298. }
  10299. else {
  10300. if (batch.renderSelf[subMesh._id]) {
  10301. // Draw
  10302. this._draw(subMesh, fillMode);
  10303. }
  10304. if (batch.visibleInstances[subMesh._id]) {
  10305. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10306. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10307. // World
  10308. world = instance.getWorldMatrix();
  10309. effectiveMaterial.bindOnlyWorldMatrix(world);
  10310. // Draw
  10311. this._draw(subMesh, fillMode);
  10312. }
  10313. }
  10314. }
  10315. // Unbind
  10316. effectiveMaterial.unbind();
  10317. // Outline - step 2
  10318. if (this.renderOutline && savedDepthWrite) {
  10319. engine.setDepthWrite(true);
  10320. engine.setColorWrite(false);
  10321. scene.getOutlineRenderer().render(subMesh, batch);
  10322. engine.setColorWrite(true);
  10323. }
  10324. // Overlay
  10325. if (this.renderOverlay) {
  10326. var currentMode = engine.getAlphaMode();
  10327. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10328. scene.getOutlineRenderer().render(subMesh, batch, true);
  10329. engine.setAlphaMode(currentMode);
  10330. }
  10331. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10332. this._onAfterRenderCallbacks[callbackIndex]();
  10333. }
  10334. };
  10335. Mesh.prototype.getEmittedParticleSystems = function () {
  10336. var results = new Array();
  10337. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10338. var particleSystem = this.getScene().particleSystems[index];
  10339. if (particleSystem.emitter === this) {
  10340. results.push(particleSystem);
  10341. }
  10342. }
  10343. return results;
  10344. };
  10345. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10346. var results = new Array();
  10347. var descendants = this.getDescendants();
  10348. descendants.push(this);
  10349. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10350. var particleSystem = this.getScene().particleSystems[index];
  10351. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10352. results.push(particleSystem);
  10353. }
  10354. }
  10355. return results;
  10356. };
  10357. Mesh.prototype.getChildren = function () {
  10358. var results = [];
  10359. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10360. var mesh = this.getScene().meshes[index];
  10361. if (mesh.parent == this) {
  10362. results.push(mesh);
  10363. }
  10364. }
  10365. return results;
  10366. };
  10367. Mesh.prototype._checkDelayState = function () {
  10368. var _this = this;
  10369. var that = this;
  10370. var scene = this.getScene();
  10371. if (this._geometry) {
  10372. this._geometry.load(scene);
  10373. }
  10374. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10375. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10376. scene._addPendingData(that);
  10377. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  10378. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  10379. if (data instanceof ArrayBuffer) {
  10380. _this._delayLoadingFunction(data, _this);
  10381. }
  10382. else {
  10383. _this._delayLoadingFunction(JSON.parse(data), _this);
  10384. }
  10385. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10386. scene._removePendingData(_this);
  10387. }, function () {
  10388. }, scene.database, getBinaryData);
  10389. }
  10390. };
  10391. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  10392. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10393. return false;
  10394. }
  10395. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  10396. return false;
  10397. }
  10398. this._checkDelayState();
  10399. return true;
  10400. };
  10401. Mesh.prototype.setMaterialByID = function (id) {
  10402. var materials = this.getScene().materials;
  10403. for (var index = 0; index < materials.length; index++) {
  10404. if (materials[index].id == id) {
  10405. this.material = materials[index];
  10406. return;
  10407. }
  10408. }
  10409. // Multi
  10410. var multiMaterials = this.getScene().multiMaterials;
  10411. for (index = 0; index < multiMaterials.length; index++) {
  10412. if (multiMaterials[index].id == id) {
  10413. this.material = multiMaterials[index];
  10414. return;
  10415. }
  10416. }
  10417. };
  10418. Mesh.prototype.getAnimatables = function () {
  10419. var results = [];
  10420. if (this.material) {
  10421. results.push(this.material);
  10422. }
  10423. if (this.skeleton) {
  10424. results.push(this.skeleton);
  10425. }
  10426. return results;
  10427. };
  10428. // Geometry
  10429. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  10430. // Position
  10431. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  10432. return;
  10433. }
  10434. this._resetPointsArrayCache();
  10435. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10436. var temp = [];
  10437. for (var index = 0; index < data.length; index += 3) {
  10438. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10439. }
  10440. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  10441. // Normals
  10442. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  10443. return;
  10444. }
  10445. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10446. for (index = 0; index < data.length; index += 3) {
  10447. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10448. }
  10449. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  10450. };
  10451. // Cache
  10452. Mesh.prototype._resetPointsArrayCache = function () {
  10453. this._positions = null;
  10454. };
  10455. Mesh.prototype._generatePointsArray = function () {
  10456. if (this._positions)
  10457. return true;
  10458. this._positions = [];
  10459. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10460. if (!data) {
  10461. return false;
  10462. }
  10463. for (var index = 0; index < data.length; index += 3) {
  10464. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  10465. }
  10466. return true;
  10467. };
  10468. // Clone
  10469. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10470. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  10471. };
  10472. // Dispose
  10473. Mesh.prototype.dispose = function (doNotRecurse) {
  10474. if (this._geometry) {
  10475. this._geometry.releaseForMesh(this, true);
  10476. }
  10477. // Instances
  10478. if (this._worldMatricesInstancesBuffer) {
  10479. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10480. this._worldMatricesInstancesBuffer = null;
  10481. }
  10482. while (this.instances.length) {
  10483. this.instances[0].dispose();
  10484. }
  10485. _super.prototype.dispose.call(this, doNotRecurse);
  10486. };
  10487. // Geometric tools
  10488. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  10489. var _this = this;
  10490. var scene = this.getScene();
  10491. var onload = function (img) {
  10492. // Getting height map data
  10493. var canvas = document.createElement("canvas");
  10494. var context = canvas.getContext("2d");
  10495. var heightMapWidth = img.width;
  10496. var heightMapHeight = img.height;
  10497. canvas.width = heightMapWidth;
  10498. canvas.height = heightMapHeight;
  10499. context.drawImage(img, 0, 0);
  10500. // Create VertexData from map data
  10501. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10502. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  10503. //execute success callback, if set
  10504. if (onSuccess) {
  10505. onSuccess(_this);
  10506. }
  10507. };
  10508. BABYLON.Tools.LoadImage(url, onload, function () {
  10509. }, scene.database);
  10510. };
  10511. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  10512. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10513. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  10514. return;
  10515. }
  10516. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10517. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10518. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  10519. var position = BABYLON.Vector3.Zero();
  10520. var normal = BABYLON.Vector3.Zero();
  10521. var uv = BABYLON.Vector2.Zero();
  10522. for (var index = 0; index < positions.length; index += 3) {
  10523. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  10524. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  10525. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  10526. // Compute height
  10527. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  10528. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  10529. var pos = (u + v * heightMapWidth) * 4;
  10530. var r = buffer[pos] / 255.0;
  10531. var g = buffer[pos + 1] / 255.0;
  10532. var b = buffer[pos + 2] / 255.0;
  10533. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  10534. normal.normalize();
  10535. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  10536. position = position.add(normal);
  10537. position.toArray(positions, index);
  10538. }
  10539. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  10540. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  10541. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  10542. };
  10543. Mesh.prototype.convertToFlatShadedMesh = function () {
  10544. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  10545. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  10546. var kinds = this.getVerticesDataKinds();
  10547. var vbs = [];
  10548. var data = [];
  10549. var newdata = [];
  10550. var updatableNormals = false;
  10551. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10552. var kind = kinds[kindIndex];
  10553. var vertexBuffer = this.getVertexBuffer(kind);
  10554. if (kind === BABYLON.VertexBuffer.NormalKind) {
  10555. updatableNormals = vertexBuffer.isUpdatable();
  10556. kinds.splice(kindIndex, 1);
  10557. kindIndex--;
  10558. continue;
  10559. }
  10560. vbs[kind] = vertexBuffer;
  10561. data[kind] = vbs[kind].getData();
  10562. newdata[kind] = [];
  10563. }
  10564. // Save previous submeshes
  10565. var previousSubmeshes = this.subMeshes.slice(0);
  10566. var indices = this.getIndices();
  10567. var totalIndices = this.getTotalIndices();
  10568. for (var index = 0; index < totalIndices; index++) {
  10569. var vertexIndex = indices[index];
  10570. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10571. kind = kinds[kindIndex];
  10572. var stride = vbs[kind].getStrideSize();
  10573. for (var offset = 0; offset < stride; offset++) {
  10574. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  10575. }
  10576. }
  10577. }
  10578. // Updating faces & normal
  10579. var normals = [];
  10580. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  10581. for (index = 0; index < totalIndices; index += 3) {
  10582. indices[index] = index;
  10583. indices[index + 1] = index + 1;
  10584. indices[index + 2] = index + 2;
  10585. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  10586. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  10587. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  10588. var p1p2 = p1.subtract(p2);
  10589. var p3p2 = p3.subtract(p2);
  10590. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  10591. for (var localIndex = 0; localIndex < 3; localIndex++) {
  10592. normals.push(normal.x);
  10593. normals.push(normal.y);
  10594. normals.push(normal.z);
  10595. }
  10596. }
  10597. this.setIndices(indices);
  10598. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  10599. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10600. kind = kinds[kindIndex];
  10601. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  10602. }
  10603. // Updating submeshes
  10604. this.releaseSubMeshes();
  10605. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  10606. var previousOne = previousSubmeshes[submeshIndex];
  10607. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  10608. }
  10609. this.synchronizeInstances();
  10610. };
  10611. // Instances
  10612. Mesh.prototype.createInstance = function (name) {
  10613. return new BABYLON.InstancedMesh(name, this);
  10614. };
  10615. Mesh.prototype.synchronizeInstances = function () {
  10616. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  10617. var instance = this.instances[instanceIndex];
  10618. instance._syncSubMeshes();
  10619. }
  10620. };
  10621. /**
  10622. * Simplify the mesh according to the given array of settings.
  10623. * Function will return immediately and will simplify async.
  10624. * @param settings a collection of simplification settings.
  10625. * @param parallelProcessing should all levels calculate parallel or one after the other.
  10626. * @param type the type of simplification to run.
  10627. * successCallback optional success callback to be called after the simplification finished processing all settings.
  10628. */
  10629. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  10630. var _this = this;
  10631. if (parallelProcessing === void 0) { parallelProcessing = true; }
  10632. if (type === void 0) { type = 0 /* QUADRATIC */; }
  10633. var getSimplifier = function () {
  10634. switch (type) {
  10635. case 0 /* QUADRATIC */:
  10636. default:
  10637. return new BABYLON.QuadraticErrorSimplification(_this);
  10638. }
  10639. };
  10640. if (parallelProcessing) {
  10641. //parallel simplifier
  10642. settings.forEach(function (setting) {
  10643. var simplifier = getSimplifier();
  10644. simplifier.simplify(setting, function (newMesh) {
  10645. _this.addLODLevel(setting.distance, newMesh);
  10646. //check if it is the last
  10647. if (setting.quality == settings[settings.length - 1].quality && successCallback) {
  10648. //all done, run the success callback.
  10649. successCallback();
  10650. }
  10651. });
  10652. });
  10653. }
  10654. else {
  10655. //single simplifier.
  10656. var simplifier = getSimplifier();
  10657. var runDecimation = function (setting, callback) {
  10658. simplifier.simplify(setting, function (newMesh) {
  10659. _this.addLODLevel(setting.distance, newMesh);
  10660. //run the next quality level
  10661. callback();
  10662. });
  10663. };
  10664. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  10665. runDecimation(settings[loop.index], function () {
  10666. loop.executeNext();
  10667. });
  10668. }, function () {
  10669. //execution ended, run the success callback.
  10670. if (successCallback) {
  10671. successCallback();
  10672. }
  10673. });
  10674. }
  10675. };
  10676. // Statics
  10677. Mesh.CreateBox = function (name, size, scene, updatable) {
  10678. var box = new Mesh(name, scene);
  10679. var vertexData = BABYLON.VertexData.CreateBox(size);
  10680. vertexData.applyToMesh(box, updatable);
  10681. return box;
  10682. };
  10683. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  10684. var sphere = new Mesh(name, scene);
  10685. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  10686. vertexData.applyToMesh(sphere, updatable);
  10687. return sphere;
  10688. };
  10689. // Cylinder and cone (Code inspired by SharpDX.org)
  10690. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  10691. // subdivisions is a new parameter, we need to support old signature
  10692. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  10693. if (scene !== undefined) {
  10694. updatable = scene;
  10695. }
  10696. scene = subdivisions;
  10697. subdivisions = 1;
  10698. }
  10699. var cylinder = new Mesh(name, scene);
  10700. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  10701. vertexData.applyToMesh(cylinder, updatable);
  10702. return cylinder;
  10703. };
  10704. // Torus (Code from SharpDX.org)
  10705. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  10706. var torus = new Mesh(name, scene);
  10707. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  10708. vertexData.applyToMesh(torus, updatable);
  10709. return torus;
  10710. };
  10711. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  10712. var torusKnot = new Mesh(name, scene);
  10713. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  10714. vertexData.applyToMesh(torusKnot, updatable);
  10715. return torusKnot;
  10716. };
  10717. // Lines
  10718. Mesh.CreateLines = function (name, points, scene, updatable) {
  10719. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  10720. var vertexData = BABYLON.VertexData.CreateLines(points);
  10721. vertexData.applyToMesh(lines, updatable);
  10722. return lines;
  10723. };
  10724. // Plane & ground
  10725. Mesh.CreatePlane = function (name, size, scene, updatable) {
  10726. var plane = new Mesh(name, scene);
  10727. var vertexData = BABYLON.VertexData.CreatePlane(size);
  10728. vertexData.applyToMesh(plane, updatable);
  10729. return plane;
  10730. };
  10731. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10732. var ground = new BABYLON.GroundMesh(name, scene);
  10733. ground._setReady(false);
  10734. ground._subdivisions = subdivisions;
  10735. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10736. vertexData.applyToMesh(ground, updatable);
  10737. ground._setReady(true);
  10738. return ground;
  10739. };
  10740. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10741. var tiledGround = new Mesh(name, scene);
  10742. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10743. vertexData.applyToMesh(tiledGround, updatable);
  10744. return tiledGround;
  10745. };
  10746. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  10747. var ground = new BABYLON.GroundMesh(name, scene);
  10748. ground._subdivisions = subdivisions;
  10749. ground._setReady(false);
  10750. var onload = function (img) {
  10751. // Getting height map data
  10752. var canvas = document.createElement("canvas");
  10753. var context = canvas.getContext("2d");
  10754. var heightMapWidth = img.width;
  10755. var heightMapHeight = img.height;
  10756. canvas.width = heightMapWidth;
  10757. canvas.height = heightMapHeight;
  10758. context.drawImage(img, 0, 0);
  10759. // Create VertexData from map data
  10760. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10761. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10762. vertexData.applyToMesh(ground, updatable);
  10763. ground._setReady(true);
  10764. //execute ready callback, if set
  10765. if (onReady) {
  10766. onReady(ground);
  10767. }
  10768. };
  10769. BABYLON.Tools.LoadImage(url, onload, function () {
  10770. }, scene.database);
  10771. return ground;
  10772. };
  10773. // Tools
  10774. Mesh.MinMax = function (meshes) {
  10775. var minVector = null;
  10776. var maxVector = null;
  10777. for (var i in meshes) {
  10778. var mesh = meshes[i];
  10779. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10780. if (!minVector) {
  10781. minVector = boundingBox.minimumWorld;
  10782. maxVector = boundingBox.maximumWorld;
  10783. continue;
  10784. }
  10785. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10786. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10787. }
  10788. return {
  10789. min: minVector,
  10790. max: maxVector
  10791. };
  10792. };
  10793. Mesh.Center = function (meshesOrMinMaxVector) {
  10794. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  10795. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10796. };
  10797. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10798. if (disposeSource === void 0) { disposeSource = true; }
  10799. var source = meshes[0];
  10800. var material = source.material;
  10801. var scene = source.getScene();
  10802. if (!allow32BitsIndices) {
  10803. var totalVertices = 0;
  10804. for (var index = 0; index < meshes.length; index++) {
  10805. totalVertices += meshes[index].getTotalVertices();
  10806. if (totalVertices > 65536) {
  10807. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  10808. return null;
  10809. }
  10810. }
  10811. }
  10812. // Merge
  10813. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  10814. vertexData.transform(source.getWorldMatrix());
  10815. for (index = 1; index < meshes.length; index++) {
  10816. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  10817. otherVertexData.transform(meshes[index].getWorldMatrix());
  10818. vertexData.merge(otherVertexData);
  10819. }
  10820. var newMesh = new Mesh(source.name + "_merged", scene);
  10821. vertexData.applyToMesh(newMesh);
  10822. // Setting properties
  10823. newMesh.material = material;
  10824. newMesh.checkCollisions = source.checkCollisions;
  10825. // Cleaning
  10826. if (disposeSource) {
  10827. for (index = 0; index < meshes.length; index++) {
  10828. meshes[index].dispose();
  10829. }
  10830. }
  10831. return newMesh;
  10832. };
  10833. return Mesh;
  10834. })(BABYLON.AbstractMesh);
  10835. BABYLON.Mesh = Mesh;
  10836. })(BABYLON || (BABYLON = {}));
  10837. //# sourceMappingURL=babylon.mesh.js.map
  10838. var BABYLON;
  10839. (function (BABYLON) {
  10840. var GroundMesh = (function (_super) {
  10841. __extends(GroundMesh, _super);
  10842. function GroundMesh(name, scene) {
  10843. _super.call(this, name, scene);
  10844. this.generateOctree = false;
  10845. this._worldInverse = new BABYLON.Matrix();
  10846. }
  10847. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  10848. get: function () {
  10849. return this._subdivisions;
  10850. },
  10851. enumerable: true,
  10852. configurable: true
  10853. });
  10854. GroundMesh.prototype.optimize = function (chunksCount) {
  10855. this.subdivide(this._subdivisions);
  10856. this.createOrUpdateSubmeshesOctree(32);
  10857. };
  10858. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  10859. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  10860. this.getWorldMatrix().invertToRef(this._worldInverse);
  10861. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  10862. var pickInfo = this.intersects(ray);
  10863. if (pickInfo.hit) {
  10864. return pickInfo.pickedPoint.y;
  10865. }
  10866. return 0;
  10867. };
  10868. return GroundMesh;
  10869. })(BABYLON.Mesh);
  10870. BABYLON.GroundMesh = GroundMesh;
  10871. })(BABYLON || (BABYLON = {}));
  10872. //# sourceMappingURL=babylon.groundMesh.js.map
  10873. var BABYLON;
  10874. (function (BABYLON) {
  10875. /**
  10876. * Creates an instance based on a source mesh.
  10877. */
  10878. var InstancedMesh = (function (_super) {
  10879. __extends(InstancedMesh, _super);
  10880. function InstancedMesh(name, source) {
  10881. _super.call(this, name, source.getScene());
  10882. source.instances.push(this);
  10883. this._sourceMesh = source;
  10884. this.position.copyFrom(source.position);
  10885. this.rotation.copyFrom(source.rotation);
  10886. this.scaling.copyFrom(source.scaling);
  10887. if (source.rotationQuaternion) {
  10888. this.rotationQuaternion = source.rotationQuaternion.clone();
  10889. }
  10890. this.infiniteDistance = source.infiniteDistance;
  10891. this.setPivotMatrix(source.getPivotMatrix());
  10892. this.refreshBoundingInfo();
  10893. this._syncSubMeshes();
  10894. }
  10895. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  10896. // Methods
  10897. get: function () {
  10898. return this._sourceMesh.receiveShadows;
  10899. },
  10900. enumerable: true,
  10901. configurable: true
  10902. });
  10903. Object.defineProperty(InstancedMesh.prototype, "material", {
  10904. get: function () {
  10905. return this._sourceMesh.material;
  10906. },
  10907. enumerable: true,
  10908. configurable: true
  10909. });
  10910. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  10911. get: function () {
  10912. return this._sourceMesh.visibility;
  10913. },
  10914. enumerable: true,
  10915. configurable: true
  10916. });
  10917. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  10918. get: function () {
  10919. return this._sourceMesh.skeleton;
  10920. },
  10921. enumerable: true,
  10922. configurable: true
  10923. });
  10924. InstancedMesh.prototype.getTotalVertices = function () {
  10925. return this._sourceMesh.getTotalVertices();
  10926. };
  10927. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  10928. get: function () {
  10929. return this._sourceMesh;
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. InstancedMesh.prototype.getVerticesData = function (kind) {
  10935. return this._sourceMesh.getVerticesData(kind);
  10936. };
  10937. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  10938. return this._sourceMesh.isVerticesDataPresent(kind);
  10939. };
  10940. InstancedMesh.prototype.getIndices = function () {
  10941. return this._sourceMesh.getIndices();
  10942. };
  10943. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  10944. get: function () {
  10945. return this._sourceMesh._positions;
  10946. },
  10947. enumerable: true,
  10948. configurable: true
  10949. });
  10950. InstancedMesh.prototype.refreshBoundingInfo = function () {
  10951. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10952. if (data) {
  10953. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  10954. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10955. }
  10956. this._updateBoundingInfo();
  10957. };
  10958. InstancedMesh.prototype._preActivate = function () {
  10959. if (this._currentLOD) {
  10960. this._currentLOD._preActivate();
  10961. }
  10962. };
  10963. InstancedMesh.prototype._activate = function (renderId) {
  10964. if (this._currentLOD) {
  10965. this._currentLOD._registerInstanceForRenderId(this, renderId);
  10966. }
  10967. };
  10968. InstancedMesh.prototype.getLOD = function (camera) {
  10969. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  10970. if (this._currentLOD === this.sourceMesh) {
  10971. return this;
  10972. }
  10973. return this._currentLOD;
  10974. };
  10975. InstancedMesh.prototype._syncSubMeshes = function () {
  10976. this.releaseSubMeshes();
  10977. if (this._sourceMesh.subMeshes) {
  10978. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  10979. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  10980. }
  10981. }
  10982. };
  10983. InstancedMesh.prototype._generatePointsArray = function () {
  10984. return this._sourceMesh._generatePointsArray();
  10985. };
  10986. // Clone
  10987. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10988. var result = this._sourceMesh.createInstance(name);
  10989. // Deep copy
  10990. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  10991. // Bounding info
  10992. this.refreshBoundingInfo();
  10993. // Parent
  10994. if (newParent) {
  10995. result.parent = newParent;
  10996. }
  10997. if (!doNotCloneChildren) {
  10998. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10999. var mesh = this.getScene().meshes[index];
  11000. if (mesh.parent === this) {
  11001. mesh.clone(mesh.name, result);
  11002. }
  11003. }
  11004. }
  11005. result.computeWorldMatrix(true);
  11006. return result;
  11007. };
  11008. // Dispoe
  11009. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11010. // Remove from mesh
  11011. var index = this._sourceMesh.instances.indexOf(this);
  11012. this._sourceMesh.instances.splice(index, 1);
  11013. _super.prototype.dispose.call(this, doNotRecurse);
  11014. };
  11015. return InstancedMesh;
  11016. })(BABYLON.AbstractMesh);
  11017. BABYLON.InstancedMesh = InstancedMesh;
  11018. })(BABYLON || (BABYLON = {}));
  11019. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  11020. (function (BABYLON) {
  11021. var SubMesh = (function () {
  11022. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  11023. if (createBoundingBox === void 0) { createBoundingBox = true; }
  11024. this.materialIndex = materialIndex;
  11025. this.verticesStart = verticesStart;
  11026. this.verticesCount = verticesCount;
  11027. this.indexStart = indexStart;
  11028. this.indexCount = indexCount;
  11029. this._renderId = 0;
  11030. this._mesh = mesh;
  11031. this._renderingMesh = renderingMesh || mesh;
  11032. mesh.subMeshes.push(this);
  11033. this._id = mesh.subMeshes.length - 1;
  11034. if (createBoundingBox) {
  11035. this.refreshBoundingInfo();
  11036. }
  11037. }
  11038. SubMesh.prototype.getBoundingInfo = function () {
  11039. return this._boundingInfo;
  11040. };
  11041. SubMesh.prototype.getMesh = function () {
  11042. return this._mesh;
  11043. };
  11044. SubMesh.prototype.getRenderingMesh = function () {
  11045. return this._renderingMesh;
  11046. };
  11047. SubMesh.prototype.getMaterial = function () {
  11048. var rootMaterial = this._renderingMesh.material;
  11049. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11050. var multiMaterial = rootMaterial;
  11051. return multiMaterial.getSubMaterial(this.materialIndex);
  11052. }
  11053. if (!rootMaterial) {
  11054. return this._mesh.getScene().defaultMaterial;
  11055. }
  11056. return rootMaterial;
  11057. };
  11058. // Methods
  11059. SubMesh.prototype.refreshBoundingInfo = function () {
  11060. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11061. if (!data) {
  11062. this._boundingInfo = this._mesh._boundingInfo;
  11063. return;
  11064. }
  11065. var indices = this._renderingMesh.getIndices();
  11066. var extend;
  11067. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11068. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11069. }
  11070. else {
  11071. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11072. }
  11073. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11074. };
  11075. SubMesh.prototype._checkCollision = function (collider) {
  11076. return this._boundingInfo._checkCollision(collider);
  11077. };
  11078. SubMesh.prototype.updateBoundingInfo = function (world) {
  11079. if (!this._boundingInfo) {
  11080. this.refreshBoundingInfo();
  11081. }
  11082. this._boundingInfo._update(world);
  11083. };
  11084. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11085. return this._boundingInfo.isInFrustum(frustumPlanes);
  11086. };
  11087. SubMesh.prototype.render = function () {
  11088. this._renderingMesh.render(this);
  11089. };
  11090. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11091. if (!this._linesIndexBuffer) {
  11092. var linesIndices = [];
  11093. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11094. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11095. }
  11096. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11097. this.linesIndexCount = linesIndices.length;
  11098. }
  11099. return this._linesIndexBuffer;
  11100. };
  11101. SubMesh.prototype.canIntersects = function (ray) {
  11102. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11103. };
  11104. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11105. var intersectInfo = null;
  11106. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11107. var p0 = positions[indices[index]];
  11108. var p1 = positions[indices[index + 1]];
  11109. var p2 = positions[indices[index + 2]];
  11110. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11111. if (currentIntersectInfo) {
  11112. if (currentIntersectInfo.distance < 0) {
  11113. continue;
  11114. }
  11115. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11116. intersectInfo = currentIntersectInfo;
  11117. intersectInfo.faceId = index / 3;
  11118. if (fastCheck) {
  11119. break;
  11120. }
  11121. }
  11122. }
  11123. }
  11124. return intersectInfo;
  11125. };
  11126. // Clone
  11127. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11128. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11129. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11130. return result;
  11131. };
  11132. // Dispose
  11133. SubMesh.prototype.dispose = function () {
  11134. if (this._linesIndexBuffer) {
  11135. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11136. this._linesIndexBuffer = null;
  11137. }
  11138. // Remove from mesh
  11139. var index = this._mesh.subMeshes.indexOf(this);
  11140. this._mesh.subMeshes.splice(index, 1);
  11141. };
  11142. // Statics
  11143. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11144. var minVertexIndex = Number.MAX_VALUE;
  11145. var maxVertexIndex = -Number.MAX_VALUE;
  11146. renderingMesh = renderingMesh || mesh;
  11147. var indices = renderingMesh.getIndices();
  11148. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11149. var vertexIndex = indices[index];
  11150. if (vertexIndex < minVertexIndex)
  11151. minVertexIndex = vertexIndex;
  11152. if (vertexIndex > maxVertexIndex)
  11153. maxVertexIndex = vertexIndex;
  11154. }
  11155. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11156. };
  11157. return SubMesh;
  11158. })();
  11159. BABYLON.SubMesh = SubMesh;
  11160. })(BABYLON || (BABYLON = {}));
  11161. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11162. (function (BABYLON) {
  11163. var BaseTexture = (function () {
  11164. function BaseTexture(scene) {
  11165. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11166. this.hasAlpha = false;
  11167. this.getAlphaFromRGB = false;
  11168. this.level = 1;
  11169. this.isCube = false;
  11170. this.isRenderTarget = false;
  11171. this.animations = new Array();
  11172. this.coordinatesIndex = 0;
  11173. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11174. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11175. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11176. this.anisotropicFilteringLevel = 4;
  11177. this._scene = scene;
  11178. this._scene.textures.push(this);
  11179. }
  11180. BaseTexture.prototype.getScene = function () {
  11181. return this._scene;
  11182. };
  11183. BaseTexture.prototype.getTextureMatrix = function () {
  11184. return null;
  11185. };
  11186. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11187. return null;
  11188. };
  11189. BaseTexture.prototype.getInternalTexture = function () {
  11190. return this._texture;
  11191. };
  11192. BaseTexture.prototype.isReady = function () {
  11193. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11194. return true;
  11195. }
  11196. if (this._texture) {
  11197. return this._texture.isReady;
  11198. }
  11199. return false;
  11200. };
  11201. BaseTexture.prototype.getSize = function () {
  11202. if (this._texture._width) {
  11203. return { width: this._texture._width, height: this._texture._height };
  11204. }
  11205. if (this._texture._size) {
  11206. return { width: this._texture._size, height: this._texture._size };
  11207. }
  11208. return { width: 0, height: 0 };
  11209. };
  11210. BaseTexture.prototype.getBaseSize = function () {
  11211. if (!this.isReady())
  11212. return { width: 0, height: 0 };
  11213. if (this._texture._size) {
  11214. return { width: this._texture._size, height: this._texture._size };
  11215. }
  11216. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11217. };
  11218. BaseTexture.prototype.scale = function (ratio) {
  11219. };
  11220. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11221. get: function () {
  11222. return false;
  11223. },
  11224. enumerable: true,
  11225. configurable: true
  11226. });
  11227. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11228. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11229. for (var index = 0; index < texturesCache.length; index++) {
  11230. var texturesCacheEntry = texturesCache[index];
  11231. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11232. texturesCache.splice(index, 1);
  11233. return;
  11234. }
  11235. }
  11236. };
  11237. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11238. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11239. for (var index = 0; index < texturesCache.length; index++) {
  11240. var texturesCacheEntry = texturesCache[index];
  11241. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11242. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11243. texturesCacheEntry.references++;
  11244. return texturesCacheEntry;
  11245. }
  11246. }
  11247. }
  11248. return null;
  11249. };
  11250. BaseTexture.prototype.delayLoad = function () {
  11251. };
  11252. BaseTexture.prototype.releaseInternalTexture = function () {
  11253. if (!this._texture) {
  11254. return;
  11255. }
  11256. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11257. this._texture.references--;
  11258. // Final reference ?
  11259. if (this._texture.references === 0) {
  11260. var index = texturesCache.indexOf(this._texture);
  11261. texturesCache.splice(index, 1);
  11262. this._scene.getEngine()._releaseTexture(this._texture);
  11263. delete this._texture;
  11264. }
  11265. };
  11266. BaseTexture.prototype.clone = function () {
  11267. return null;
  11268. };
  11269. BaseTexture.prototype.dispose = function () {
  11270. // Remove from scene
  11271. var index = this._scene.textures.indexOf(this);
  11272. if (index >= 0) {
  11273. this._scene.textures.splice(index, 1);
  11274. }
  11275. if (this._texture === undefined) {
  11276. return;
  11277. }
  11278. this.releaseInternalTexture();
  11279. // Callback
  11280. if (this.onDispose) {
  11281. this.onDispose();
  11282. }
  11283. };
  11284. return BaseTexture;
  11285. })();
  11286. BABYLON.BaseTexture = BaseTexture;
  11287. })(BABYLON || (BABYLON = {}));
  11288. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  11289. (function (BABYLON) {
  11290. var RenderingGroup = (function () {
  11291. function RenderingGroup(index, scene) {
  11292. this.index = index;
  11293. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11294. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11295. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11296. this._scene = scene;
  11297. }
  11298. RenderingGroup.prototype.render = function (customRenderFunction) {
  11299. if (customRenderFunction) {
  11300. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11301. return true;
  11302. }
  11303. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11304. return false;
  11305. }
  11306. var engine = this._scene.getEngine();
  11307. // Opaque
  11308. var subIndex;
  11309. var submesh;
  11310. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11311. submesh = this._opaqueSubMeshes.data[subIndex];
  11312. submesh.render();
  11313. }
  11314. // Alpha test
  11315. engine.setAlphaTesting(true);
  11316. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11317. submesh = this._alphaTestSubMeshes.data[subIndex];
  11318. submesh.render();
  11319. }
  11320. engine.setAlphaTesting(false);
  11321. // Transparent
  11322. if (this._transparentSubMeshes.length) {
  11323. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11324. submesh = this._transparentSubMeshes.data[subIndex];
  11325. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11326. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11327. }
  11328. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11329. sortedArray.sort(function (a, b) {
  11330. // Alpha index first
  11331. if (a._alphaIndex > b._alphaIndex) {
  11332. return 1;
  11333. }
  11334. if (a._alphaIndex < b._alphaIndex) {
  11335. return -1;
  11336. }
  11337. // Then distance to camera
  11338. if (a._distanceToCamera < b._distanceToCamera) {
  11339. return 1;
  11340. }
  11341. if (a._distanceToCamera > b._distanceToCamera) {
  11342. return -1;
  11343. }
  11344. return 0;
  11345. });
  11346. // Rendering
  11347. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11348. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11349. submesh = sortedArray[subIndex];
  11350. submesh.render();
  11351. }
  11352. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11353. }
  11354. return true;
  11355. };
  11356. RenderingGroup.prototype.prepare = function () {
  11357. this._opaqueSubMeshes.reset();
  11358. this._transparentSubMeshes.reset();
  11359. this._alphaTestSubMeshes.reset();
  11360. };
  11361. RenderingGroup.prototype.dispatch = function (subMesh) {
  11362. var material = subMesh.getMaterial();
  11363. var mesh = subMesh.getMesh();
  11364. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11365. this._transparentSubMeshes.push(subMesh);
  11366. }
  11367. else if (material.needAlphaTesting()) {
  11368. this._alphaTestSubMeshes.push(subMesh);
  11369. }
  11370. else {
  11371. this._opaqueSubMeshes.push(subMesh); // Opaque
  11372. }
  11373. };
  11374. return RenderingGroup;
  11375. })();
  11376. BABYLON.RenderingGroup = RenderingGroup;
  11377. })(BABYLON || (BABYLON = {}));
  11378. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  11379. (function (BABYLON) {
  11380. var RenderingManager = (function () {
  11381. function RenderingManager(scene) {
  11382. this._renderingGroups = new Array();
  11383. this._scene = scene;
  11384. }
  11385. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11386. if (this._scene._activeParticleSystems.length === 0) {
  11387. return;
  11388. }
  11389. // Particles
  11390. var beforeParticlesDate = BABYLON.Tools.Now;
  11391. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11392. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11393. if (particleSystem.renderingGroupId !== index) {
  11394. continue;
  11395. }
  11396. this._clearDepthBuffer();
  11397. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11398. this._scene._activeParticles += particleSystem.render();
  11399. }
  11400. }
  11401. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11402. };
  11403. RenderingManager.prototype._renderSprites = function (index) {
  11404. if (this._scene.spriteManagers.length === 0) {
  11405. return;
  11406. }
  11407. // Sprites
  11408. var beforeSpritessDate = BABYLON.Tools.Now;
  11409. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11410. var spriteManager = this._scene.spriteManagers[id];
  11411. if (spriteManager.renderingGroupId === index) {
  11412. this._clearDepthBuffer();
  11413. spriteManager.render();
  11414. }
  11415. }
  11416. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11417. };
  11418. RenderingManager.prototype._clearDepthBuffer = function () {
  11419. if (this._depthBufferAlreadyCleaned) {
  11420. return;
  11421. }
  11422. this._scene.getEngine().clear(0, false, true);
  11423. this._depthBufferAlreadyCleaned = true;
  11424. };
  11425. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11426. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11427. this._depthBufferAlreadyCleaned = false;
  11428. var renderingGroup = this._renderingGroups[index];
  11429. if (renderingGroup) {
  11430. this._clearDepthBuffer();
  11431. if (!renderingGroup.render(customRenderFunction)) {
  11432. this._renderingGroups.splice(index, 1);
  11433. }
  11434. }
  11435. if (renderSprites) {
  11436. this._renderSprites(index);
  11437. }
  11438. if (renderParticles) {
  11439. this._renderParticles(index, activeMeshes);
  11440. }
  11441. }
  11442. };
  11443. RenderingManager.prototype.reset = function () {
  11444. for (var index in this._renderingGroups) {
  11445. var renderingGroup = this._renderingGroups[index];
  11446. renderingGroup.prepare();
  11447. }
  11448. };
  11449. RenderingManager.prototype.dispatch = function (subMesh) {
  11450. var mesh = subMesh.getMesh();
  11451. var renderingGroupId = mesh.renderingGroupId || 0;
  11452. if (!this._renderingGroups[renderingGroupId]) {
  11453. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11454. }
  11455. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11456. };
  11457. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11458. return RenderingManager;
  11459. })();
  11460. BABYLON.RenderingManager = RenderingManager;
  11461. })(BABYLON || (BABYLON = {}));
  11462. //# sourceMappingURL=babylon.renderingManager.js.map
  11463. var BABYLON;
  11464. (function (BABYLON) {
  11465. var Texture = (function (_super) {
  11466. __extends(Texture, _super);
  11467. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  11468. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11469. if (onLoad === void 0) { onLoad = null; }
  11470. if (onError === void 0) { onError = null; }
  11471. if (buffer === void 0) { buffer = null; }
  11472. if (deleteBuffer === void 0) { deleteBuffer = false; }
  11473. _super.call(this, scene);
  11474. this.uOffset = 0;
  11475. this.vOffset = 0;
  11476. this.uScale = 1.0;
  11477. this.vScale = 1.0;
  11478. this.uAng = 0;
  11479. this.vAng = 0;
  11480. this.wAng = 0;
  11481. this.name = url;
  11482. this.url = url;
  11483. this._noMipmap = noMipmap;
  11484. this._invertY = invertY;
  11485. this._samplingMode = samplingMode;
  11486. this._buffer = buffer;
  11487. this._deleteBuffer = deleteBuffer;
  11488. if (!url) {
  11489. return;
  11490. }
  11491. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  11492. if (!this._texture) {
  11493. if (!scene.useDelayedTextureLoading) {
  11494. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  11495. if (deleteBuffer) {
  11496. delete this._buffer;
  11497. }
  11498. }
  11499. else {
  11500. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11501. }
  11502. }
  11503. }
  11504. Texture.prototype.delayLoad = function () {
  11505. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11506. return;
  11507. }
  11508. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11509. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  11510. if (!this._texture) {
  11511. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  11512. if (this._deleteBuffer) {
  11513. delete this._buffer;
  11514. }
  11515. }
  11516. };
  11517. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  11518. x -= this.uOffset + 0.5;
  11519. y -= this.vOffset + 0.5;
  11520. z -= 0.5;
  11521. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  11522. t.x *= this.uScale;
  11523. t.y *= this.vScale;
  11524. t.x += 0.5;
  11525. t.y += 0.5;
  11526. t.z += 0.5;
  11527. };
  11528. Texture.prototype.getTextureMatrix = function () {
  11529. 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) {
  11530. return this._cachedTextureMatrix;
  11531. }
  11532. this._cachedUOffset = this.uOffset;
  11533. this._cachedVOffset = this.vOffset;
  11534. this._cachedUScale = this.uScale;
  11535. this._cachedVScale = this.vScale;
  11536. this._cachedUAng = this.uAng;
  11537. this._cachedVAng = this.vAng;
  11538. this._cachedWAng = this.wAng;
  11539. if (!this._cachedTextureMatrix) {
  11540. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11541. this._rowGenerationMatrix = new BABYLON.Matrix();
  11542. this._t0 = BABYLON.Vector3.Zero();
  11543. this._t1 = BABYLON.Vector3.Zero();
  11544. this._t2 = BABYLON.Vector3.Zero();
  11545. }
  11546. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  11547. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  11548. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  11549. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  11550. this._t1.subtractInPlace(this._t0);
  11551. this._t2.subtractInPlace(this._t0);
  11552. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11553. this._cachedTextureMatrix.m[0] = this._t1.x;
  11554. this._cachedTextureMatrix.m[1] = this._t1.y;
  11555. this._cachedTextureMatrix.m[2] = this._t1.z;
  11556. this._cachedTextureMatrix.m[4] = this._t2.x;
  11557. this._cachedTextureMatrix.m[5] = this._t2.y;
  11558. this._cachedTextureMatrix.m[6] = this._t2.z;
  11559. this._cachedTextureMatrix.m[8] = this._t0.x;
  11560. this._cachedTextureMatrix.m[9] = this._t0.y;
  11561. this._cachedTextureMatrix.m[10] = this._t0.z;
  11562. return this._cachedTextureMatrix;
  11563. };
  11564. Texture.prototype.getReflectionTextureMatrix = function () {
  11565. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  11566. return this._cachedTextureMatrix;
  11567. }
  11568. if (!this._cachedTextureMatrix) {
  11569. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11570. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  11571. }
  11572. this._cachedCoordinatesMode = this.coordinatesMode;
  11573. switch (this.coordinatesMode) {
  11574. case BABYLON.Texture.SPHERICAL_MODE:
  11575. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11576. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  11577. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  11578. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  11579. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  11580. break;
  11581. case BABYLON.Texture.PLANAR_MODE:
  11582. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11583. this._cachedTextureMatrix[0] = this.uScale;
  11584. this._cachedTextureMatrix[5] = this.vScale;
  11585. this._cachedTextureMatrix[12] = this.uOffset;
  11586. this._cachedTextureMatrix[13] = this.vOffset;
  11587. break;
  11588. case BABYLON.Texture.PROJECTION_MODE:
  11589. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  11590. this._projectionModeMatrix.m[0] = 0.5;
  11591. this._projectionModeMatrix.m[5] = -0.5;
  11592. this._projectionModeMatrix.m[10] = 0.0;
  11593. this._projectionModeMatrix.m[12] = 0.5;
  11594. this._projectionModeMatrix.m[13] = 0.5;
  11595. this._projectionModeMatrix.m[14] = 1.0;
  11596. this._projectionModeMatrix.m[15] = 1.0;
  11597. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  11598. break;
  11599. default:
  11600. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11601. break;
  11602. }
  11603. return this._cachedTextureMatrix;
  11604. };
  11605. Texture.prototype.clone = function () {
  11606. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  11607. // Base texture
  11608. newTexture.hasAlpha = this.hasAlpha;
  11609. newTexture.level = this.level;
  11610. newTexture.wrapU = this.wrapU;
  11611. newTexture.wrapV = this.wrapV;
  11612. newTexture.coordinatesIndex = this.coordinatesIndex;
  11613. newTexture.coordinatesMode = this.coordinatesMode;
  11614. // Texture
  11615. newTexture.uOffset = this.uOffset;
  11616. newTexture.vOffset = this.vOffset;
  11617. newTexture.uScale = this.uScale;
  11618. newTexture.vScale = this.vScale;
  11619. newTexture.uAng = this.uAng;
  11620. newTexture.vAng = this.vAng;
  11621. newTexture.wAng = this.wAng;
  11622. return newTexture;
  11623. };
  11624. // Statics
  11625. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  11626. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11627. if (onLoad === void 0) { onLoad = null; }
  11628. if (onError === void 0) { onError = null; }
  11629. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  11630. };
  11631. // Constants
  11632. Texture.NEAREST_SAMPLINGMODE = 1;
  11633. Texture.BILINEAR_SAMPLINGMODE = 2;
  11634. Texture.TRILINEAR_SAMPLINGMODE = 3;
  11635. Texture.EXPLICIT_MODE = 0;
  11636. Texture.SPHERICAL_MODE = 1;
  11637. Texture.PLANAR_MODE = 2;
  11638. Texture.CUBIC_MODE = 3;
  11639. Texture.PROJECTION_MODE = 4;
  11640. Texture.SKYBOX_MODE = 5;
  11641. Texture.CLAMP_ADDRESSMODE = 0;
  11642. Texture.WRAP_ADDRESSMODE = 1;
  11643. Texture.MIRROR_ADDRESSMODE = 2;
  11644. return Texture;
  11645. })(BABYLON.BaseTexture);
  11646. BABYLON.Texture = Texture;
  11647. })(BABYLON || (BABYLON = {}));
  11648. //# sourceMappingURL=babylon.texture.js.map
  11649. var BABYLON;
  11650. (function (BABYLON) {
  11651. var CubeTexture = (function (_super) {
  11652. __extends(CubeTexture, _super);
  11653. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  11654. _super.call(this, scene);
  11655. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  11656. this.name = rootUrl;
  11657. this.url = rootUrl;
  11658. this._noMipmap = noMipmap;
  11659. this.hasAlpha = false;
  11660. this._texture = this._getFromCache(rootUrl, noMipmap);
  11661. if (!extensions) {
  11662. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  11663. }
  11664. this._extensions = extensions;
  11665. if (!this._texture) {
  11666. if (!scene.useDelayedTextureLoading) {
  11667. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  11668. }
  11669. else {
  11670. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11671. }
  11672. }
  11673. this.isCube = true;
  11674. this._textureMatrix = BABYLON.Matrix.Identity();
  11675. }
  11676. CubeTexture.prototype.clone = function () {
  11677. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  11678. // Base texture
  11679. newTexture.level = this.level;
  11680. newTexture.wrapU = this.wrapU;
  11681. newTexture.wrapV = this.wrapV;
  11682. newTexture.coordinatesIndex = this.coordinatesIndex;
  11683. newTexture.coordinatesMode = this.coordinatesMode;
  11684. return newTexture;
  11685. };
  11686. // Methods
  11687. CubeTexture.prototype.delayLoad = function () {
  11688. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11689. return;
  11690. }
  11691. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11692. this._texture = this._getFromCache(this.url, this._noMipmap);
  11693. if (!this._texture) {
  11694. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  11695. }
  11696. };
  11697. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  11698. return this._textureMatrix;
  11699. };
  11700. return CubeTexture;
  11701. })(BABYLON.BaseTexture);
  11702. BABYLON.CubeTexture = CubeTexture;
  11703. })(BABYLON || (BABYLON = {}));
  11704. //# sourceMappingURL=babylon.cubeTexture.js.map
  11705. var BABYLON;
  11706. (function (BABYLON) {
  11707. var RenderTargetTexture = (function (_super) {
  11708. __extends(RenderTargetTexture, _super);
  11709. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  11710. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  11711. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  11712. _super.call(this, null, scene, !generateMipMaps);
  11713. this.renderList = new Array();
  11714. this.renderParticles = true;
  11715. this.renderSprites = false;
  11716. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  11717. this._currentRefreshId = -1;
  11718. this._refreshRate = 1;
  11719. this.name = name;
  11720. this.isRenderTarget = true;
  11721. this._size = size;
  11722. this._generateMipMaps = generateMipMaps;
  11723. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  11724. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  11725. // Rendering groups
  11726. this._renderingManager = new BABYLON.RenderingManager(scene);
  11727. }
  11728. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  11729. this._currentRefreshId = -1;
  11730. };
  11731. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  11732. get: function () {
  11733. return this._refreshRate;
  11734. },
  11735. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11736. set: function (value) {
  11737. this._refreshRate = value;
  11738. this.resetRefreshCounter();
  11739. },
  11740. enumerable: true,
  11741. configurable: true
  11742. });
  11743. RenderTargetTexture.prototype._shouldRender = function () {
  11744. if (this._currentRefreshId === -1) {
  11745. this._currentRefreshId = 1;
  11746. return true;
  11747. }
  11748. if (this.refreshRate === this._currentRefreshId) {
  11749. this._currentRefreshId = 1;
  11750. return true;
  11751. }
  11752. this._currentRefreshId++;
  11753. return false;
  11754. };
  11755. RenderTargetTexture.prototype.isReady = function () {
  11756. if (!this.getScene().renderTargetsEnabled) {
  11757. return false;
  11758. }
  11759. return _super.prototype.isReady.call(this);
  11760. };
  11761. RenderTargetTexture.prototype.getRenderSize = function () {
  11762. return this._size;
  11763. };
  11764. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11765. get: function () {
  11766. return true;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. RenderTargetTexture.prototype.scale = function (ratio) {
  11772. var newSize = this._size * ratio;
  11773. this.resize(newSize, this._generateMipMaps);
  11774. };
  11775. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11776. this.releaseInternalTexture();
  11777. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11778. };
  11779. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11780. var scene = this.getScene();
  11781. var engine = scene.getEngine();
  11782. if (this._waitingRenderList) {
  11783. this.renderList = [];
  11784. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11785. var id = this._waitingRenderList[index];
  11786. this.renderList.push(scene.getMeshByID(id));
  11787. }
  11788. delete this._waitingRenderList;
  11789. }
  11790. if (this.renderList && this.renderList.length === 0) {
  11791. return;
  11792. }
  11793. // Bind
  11794. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11795. engine.bindFramebuffer(this._texture);
  11796. }
  11797. // Clear
  11798. engine.clear(scene.clearColor, true, true);
  11799. this._renderingManager.reset();
  11800. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  11801. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  11802. var mesh = currentRenderList[meshIndex];
  11803. if (mesh) {
  11804. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  11805. // Reset _currentRefreshId
  11806. this.resetRefreshCounter();
  11807. continue;
  11808. }
  11809. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  11810. mesh._activate(scene.getRenderId());
  11811. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  11812. var subMesh = mesh.subMeshes[subIndex];
  11813. scene._activeVertices += subMesh.indexCount;
  11814. this._renderingManager.dispatch(subMesh);
  11815. }
  11816. }
  11817. }
  11818. }
  11819. if (!this._doNotChangeAspectRatio) {
  11820. scene.updateTransformMatrix(true);
  11821. }
  11822. if (this.onBeforeRender) {
  11823. this.onBeforeRender();
  11824. }
  11825. // Render
  11826. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  11827. if (useCameraPostProcess) {
  11828. scene.postProcessManager._finalizeFrame(false, this._texture);
  11829. }
  11830. if (this.onAfterRender) {
  11831. this.onAfterRender();
  11832. }
  11833. // Unbind
  11834. engine.unBindFramebuffer(this._texture);
  11835. if (!this._doNotChangeAspectRatio) {
  11836. scene.updateTransformMatrix(true);
  11837. }
  11838. };
  11839. RenderTargetTexture.prototype.clone = function () {
  11840. var textureSize = this.getSize();
  11841. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11842. // Base texture
  11843. newTexture.hasAlpha = this.hasAlpha;
  11844. newTexture.level = this.level;
  11845. // RenderTarget Texture
  11846. newTexture.coordinatesMode = this.coordinatesMode;
  11847. newTexture.renderList = this.renderList.slice(0);
  11848. return newTexture;
  11849. };
  11850. return RenderTargetTexture;
  11851. })(BABYLON.Texture);
  11852. BABYLON.RenderTargetTexture = RenderTargetTexture;
  11853. })(BABYLON || (BABYLON = {}));
  11854. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  11855. var BABYLON;
  11856. (function (BABYLON) {
  11857. var ProceduralTexture = (function (_super) {
  11858. __extends(ProceduralTexture, _super);
  11859. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  11860. if (generateMipMaps === void 0) { generateMipMaps = true; }
  11861. _super.call(this, null, scene, !generateMipMaps);
  11862. this._currentRefreshId = -1;
  11863. this._refreshRate = 1;
  11864. this._vertexDeclaration = [2];
  11865. this._vertexStrideSize = 2 * 4;
  11866. this._uniforms = new Array();
  11867. this._samplers = new Array();
  11868. this._textures = new Array();
  11869. this._floats = new Array();
  11870. this._floatsArrays = {};
  11871. this._colors3 = new Array();
  11872. this._colors4 = new Array();
  11873. this._vectors2 = new Array();
  11874. this._vectors3 = new Array();
  11875. this._matrices = new Array();
  11876. this._fallbackTextureUsed = false;
  11877. scene._proceduralTextures.push(this);
  11878. this.name = name;
  11879. this.isRenderTarget = true;
  11880. this._size = size;
  11881. this._generateMipMaps = generateMipMaps;
  11882. this.setFragment(fragment);
  11883. this._fallbackTexture = fallbackTexture;
  11884. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11885. // VBO
  11886. var vertices = [];
  11887. vertices.push(1, 1);
  11888. vertices.push(-1, 1);
  11889. vertices.push(-1, -1);
  11890. vertices.push(1, -1);
  11891. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11892. // Indices
  11893. var indices = [];
  11894. indices.push(0);
  11895. indices.push(1);
  11896. indices.push(2);
  11897. indices.push(0);
  11898. indices.push(2);
  11899. indices.push(3);
  11900. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11901. }
  11902. ProceduralTexture.prototype.reset = function () {
  11903. if (this._effect === undefined) {
  11904. return;
  11905. }
  11906. var engine = this.getScene().getEngine();
  11907. engine._releaseEffect(this._effect);
  11908. };
  11909. ProceduralTexture.prototype.isReady = function () {
  11910. var _this = this;
  11911. var engine = this.getScene().getEngine();
  11912. var shaders;
  11913. if (!this._fragment) {
  11914. return false;
  11915. }
  11916. if (this._fallbackTextureUsed) {
  11917. return true;
  11918. }
  11919. if (this._fragment.fragmentElement !== undefined) {
  11920. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  11921. }
  11922. else {
  11923. shaders = { vertex: "procedural", fragment: this._fragment };
  11924. }
  11925. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  11926. _this.releaseInternalTexture();
  11927. if (_this._fallbackTexture) {
  11928. _this._texture = _this._fallbackTexture._texture;
  11929. _this._texture.references++;
  11930. }
  11931. _this._fallbackTextureUsed = true;
  11932. });
  11933. return this._effect.isReady();
  11934. };
  11935. ProceduralTexture.prototype.resetRefreshCounter = function () {
  11936. this._currentRefreshId = -1;
  11937. };
  11938. ProceduralTexture.prototype.setFragment = function (fragment) {
  11939. this._fragment = fragment;
  11940. };
  11941. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  11942. get: function () {
  11943. return this._refreshRate;
  11944. },
  11945. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11946. set: function (value) {
  11947. this._refreshRate = value;
  11948. this.resetRefreshCounter();
  11949. },
  11950. enumerable: true,
  11951. configurable: true
  11952. });
  11953. ProceduralTexture.prototype._shouldRender = function () {
  11954. if (!this.isReady() || !this._texture) {
  11955. return false;
  11956. }
  11957. if (this._fallbackTextureUsed) {
  11958. return false;
  11959. }
  11960. if (this._currentRefreshId === -1) {
  11961. this._currentRefreshId = 1;
  11962. return true;
  11963. }
  11964. if (this.refreshRate === this._currentRefreshId) {
  11965. this._currentRefreshId = 1;
  11966. return true;
  11967. }
  11968. this._currentRefreshId++;
  11969. return false;
  11970. };
  11971. ProceduralTexture.prototype.getRenderSize = function () {
  11972. return this._size;
  11973. };
  11974. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  11975. if (this._fallbackTextureUsed) {
  11976. return;
  11977. }
  11978. this.releaseInternalTexture();
  11979. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11980. };
  11981. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  11982. if (this._uniforms.indexOf(uniformName) === -1) {
  11983. this._uniforms.push(uniformName);
  11984. }
  11985. };
  11986. ProceduralTexture.prototype.setTexture = function (name, texture) {
  11987. if (this._samplers.indexOf(name) === -1) {
  11988. this._samplers.push(name);
  11989. }
  11990. this._textures[name] = texture;
  11991. return this;
  11992. };
  11993. ProceduralTexture.prototype.setFloat = function (name, value) {
  11994. this._checkUniform(name);
  11995. this._floats[name] = value;
  11996. return this;
  11997. };
  11998. ProceduralTexture.prototype.setFloats = function (name, value) {
  11999. this._checkUniform(name);
  12000. this._floatsArrays[name] = value;
  12001. return this;
  12002. };
  12003. ProceduralTexture.prototype.setColor3 = function (name, value) {
  12004. this._checkUniform(name);
  12005. this._colors3[name] = value;
  12006. return this;
  12007. };
  12008. ProceduralTexture.prototype.setColor4 = function (name, value) {
  12009. this._checkUniform(name);
  12010. this._colors4[name] = value;
  12011. return this;
  12012. };
  12013. ProceduralTexture.prototype.setVector2 = function (name, value) {
  12014. this._checkUniform(name);
  12015. this._vectors2[name] = value;
  12016. return this;
  12017. };
  12018. ProceduralTexture.prototype.setVector3 = function (name, value) {
  12019. this._checkUniform(name);
  12020. this._vectors3[name] = value;
  12021. return this;
  12022. };
  12023. ProceduralTexture.prototype.setMatrix = function (name, value) {
  12024. this._checkUniform(name);
  12025. this._matrices[name] = value;
  12026. return this;
  12027. };
  12028. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12029. var scene = this.getScene();
  12030. var engine = scene.getEngine();
  12031. engine.bindFramebuffer(this._texture);
  12032. // Clear
  12033. engine.clear(scene.clearColor, true, true);
  12034. // Render
  12035. engine.enableEffect(this._effect);
  12036. engine.setState(false);
  12037. for (var name in this._textures) {
  12038. this._effect.setTexture(name, this._textures[name]);
  12039. }
  12040. for (name in this._floats) {
  12041. this._effect.setFloat(name, this._floats[name]);
  12042. }
  12043. for (name in this._floatsArrays) {
  12044. this._effect.setArray(name, this._floatsArrays[name]);
  12045. }
  12046. for (name in this._colors3) {
  12047. this._effect.setColor3(name, this._colors3[name]);
  12048. }
  12049. for (name in this._colors4) {
  12050. var color = this._colors4[name];
  12051. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12052. }
  12053. for (name in this._vectors2) {
  12054. this._effect.setVector2(name, this._vectors2[name]);
  12055. }
  12056. for (name in this._vectors3) {
  12057. this._effect.setVector3(name, this._vectors3[name]);
  12058. }
  12059. for (name in this._matrices) {
  12060. this._effect.setMatrix(name, this._matrices[name]);
  12061. }
  12062. // VBOs
  12063. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12064. // Draw order
  12065. engine.draw(true, 0, 6);
  12066. // Unbind
  12067. engine.unBindFramebuffer(this._texture);
  12068. };
  12069. ProceduralTexture.prototype.clone = function () {
  12070. var textureSize = this.getSize();
  12071. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12072. // Base texture
  12073. newTexture.hasAlpha = this.hasAlpha;
  12074. newTexture.level = this.level;
  12075. // RenderTarget Texture
  12076. newTexture.coordinatesMode = this.coordinatesMode;
  12077. return newTexture;
  12078. };
  12079. ProceduralTexture.prototype.dispose = function () {
  12080. var index = this.getScene()._proceduralTextures.indexOf(this);
  12081. if (index >= 0) {
  12082. this.getScene()._proceduralTextures.splice(index, 1);
  12083. }
  12084. _super.prototype.dispose.call(this);
  12085. };
  12086. return ProceduralTexture;
  12087. })(BABYLON.Texture);
  12088. BABYLON.ProceduralTexture = ProceduralTexture;
  12089. })(BABYLON || (BABYLON = {}));
  12090. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12091. var BABYLON;
  12092. (function (BABYLON) {
  12093. var WoodProceduralTexture = (function (_super) {
  12094. __extends(WoodProceduralTexture, _super);
  12095. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12096. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12097. this._ampScale = 100.0;
  12098. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12099. this.updateShaderUniforms();
  12100. this.refreshRate = 0;
  12101. }
  12102. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12103. this.setFloat("ampScale", this._ampScale);
  12104. this.setColor3("woodColor", this._woodColor);
  12105. };
  12106. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12107. get: function () {
  12108. return this._ampScale;
  12109. },
  12110. set: function (value) {
  12111. this._ampScale = value;
  12112. this.updateShaderUniforms();
  12113. },
  12114. enumerable: true,
  12115. configurable: true
  12116. });
  12117. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12118. get: function () {
  12119. return this._woodColor;
  12120. },
  12121. set: function (value) {
  12122. this._woodColor = value;
  12123. this.updateShaderUniforms();
  12124. },
  12125. enumerable: true,
  12126. configurable: true
  12127. });
  12128. return WoodProceduralTexture;
  12129. })(BABYLON.ProceduralTexture);
  12130. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12131. var FireProceduralTexture = (function (_super) {
  12132. __extends(FireProceduralTexture, _super);
  12133. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12134. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12135. this._time = 0.0;
  12136. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12137. this._shift = 1.6;
  12138. this._autoGenerateTime = true;
  12139. this._alphaThreshold = 0.5;
  12140. this._fireColors = FireProceduralTexture.RedFireColors;
  12141. this.updateShaderUniforms();
  12142. this.refreshRate = 1;
  12143. }
  12144. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12145. this.setFloat("time", this._time);
  12146. this.setVector2("speed", this._speed);
  12147. this.setFloat("shift", this._shift);
  12148. this.setColor3("c1", this._fireColors[0]);
  12149. this.setColor3("c2", this._fireColors[1]);
  12150. this.setColor3("c3", this._fireColors[2]);
  12151. this.setColor3("c4", this._fireColors[3]);
  12152. this.setColor3("c5", this._fireColors[4]);
  12153. this.setColor3("c6", this._fireColors[5]);
  12154. this.setFloat("alphaThreshold", this._alphaThreshold);
  12155. };
  12156. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12157. if (this._autoGenerateTime) {
  12158. this._time += this.getScene().getAnimationRatio() * 0.03;
  12159. this.updateShaderUniforms();
  12160. }
  12161. _super.prototype.render.call(this, useCameraPostProcess);
  12162. };
  12163. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12164. get: function () {
  12165. return [
  12166. new BABYLON.Color3(0.5, 0.0, 1.0),
  12167. new BABYLON.Color3(0.9, 0.0, 1.0),
  12168. new BABYLON.Color3(0.2, 0.0, 1.0),
  12169. new BABYLON.Color3(1.0, 0.9, 1.0),
  12170. new BABYLON.Color3(0.1, 0.1, 1.0),
  12171. new BABYLON.Color3(0.9, 0.9, 1.0)
  12172. ];
  12173. },
  12174. enumerable: true,
  12175. configurable: true
  12176. });
  12177. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12178. get: function () {
  12179. return [
  12180. new BABYLON.Color3(0.5, 1.0, 0.0),
  12181. new BABYLON.Color3(0.5, 1.0, 0.0),
  12182. new BABYLON.Color3(0.3, 0.4, 0.0),
  12183. new BABYLON.Color3(0.5, 1.0, 0.0),
  12184. new BABYLON.Color3(0.2, 0.0, 0.0),
  12185. new BABYLON.Color3(0.5, 1.0, 0.0)
  12186. ];
  12187. },
  12188. enumerable: true,
  12189. configurable: true
  12190. });
  12191. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12192. get: function () {
  12193. return [
  12194. new BABYLON.Color3(0.5, 0.0, 0.1),
  12195. new BABYLON.Color3(0.9, 0.0, 0.0),
  12196. new BABYLON.Color3(0.2, 0.0, 0.0),
  12197. new BABYLON.Color3(1.0, 0.9, 0.0),
  12198. new BABYLON.Color3(0.1, 0.1, 0.1),
  12199. new BABYLON.Color3(0.9, 0.9, 0.9)
  12200. ];
  12201. },
  12202. enumerable: true,
  12203. configurable: true
  12204. });
  12205. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12206. get: function () {
  12207. return [
  12208. new BABYLON.Color3(0.1, 0.0, 0.5),
  12209. new BABYLON.Color3(0.0, 0.0, 0.5),
  12210. new BABYLON.Color3(0.1, 0.0, 0.2),
  12211. new BABYLON.Color3(0.0, 0.0, 1.0),
  12212. new BABYLON.Color3(0.1, 0.2, 0.3),
  12213. new BABYLON.Color3(0.0, 0.2, 0.9)
  12214. ];
  12215. },
  12216. enumerable: true,
  12217. configurable: true
  12218. });
  12219. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12220. get: function () {
  12221. return this._fireColors;
  12222. },
  12223. set: function (value) {
  12224. this._fireColors = value;
  12225. this.updateShaderUniforms();
  12226. },
  12227. enumerable: true,
  12228. configurable: true
  12229. });
  12230. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12231. get: function () {
  12232. return this._time;
  12233. },
  12234. set: function (value) {
  12235. this._time = value;
  12236. this.updateShaderUniforms();
  12237. },
  12238. enumerable: true,
  12239. configurable: true
  12240. });
  12241. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12242. get: function () {
  12243. return this._speed;
  12244. },
  12245. set: function (value) {
  12246. this._speed = value;
  12247. this.updateShaderUniforms();
  12248. },
  12249. enumerable: true,
  12250. configurable: true
  12251. });
  12252. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12253. get: function () {
  12254. return this._shift;
  12255. },
  12256. set: function (value) {
  12257. this._shift = value;
  12258. this.updateShaderUniforms();
  12259. },
  12260. enumerable: true,
  12261. configurable: true
  12262. });
  12263. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12264. get: function () {
  12265. return this._alphaThreshold;
  12266. },
  12267. set: function (value) {
  12268. this._alphaThreshold = value;
  12269. this.updateShaderUniforms();
  12270. },
  12271. enumerable: true,
  12272. configurable: true
  12273. });
  12274. return FireProceduralTexture;
  12275. })(BABYLON.ProceduralTexture);
  12276. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12277. var CloudProceduralTexture = (function (_super) {
  12278. __extends(CloudProceduralTexture, _super);
  12279. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12280. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12281. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12282. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12283. this.updateShaderUniforms();
  12284. this.refreshRate = 0;
  12285. }
  12286. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12287. this.setColor3("skyColor", this._skyColor);
  12288. this.setColor3("cloudColor", this._cloudColor);
  12289. };
  12290. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12291. get: function () {
  12292. return this._skyColor;
  12293. },
  12294. set: function (value) {
  12295. this._skyColor = value;
  12296. this.updateShaderUniforms();
  12297. },
  12298. enumerable: true,
  12299. configurable: true
  12300. });
  12301. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  12302. get: function () {
  12303. return this._cloudColor;
  12304. },
  12305. set: function (value) {
  12306. this._cloudColor = value;
  12307. this.updateShaderUniforms();
  12308. },
  12309. enumerable: true,
  12310. configurable: true
  12311. });
  12312. return CloudProceduralTexture;
  12313. })(BABYLON.ProceduralTexture);
  12314. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12315. var GrassProceduralTexture = (function (_super) {
  12316. __extends(GrassProceduralTexture, _super);
  12317. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12318. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12319. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12320. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12321. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12322. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12323. this._grassColors = [
  12324. new BABYLON.Color3(0.29, 0.38, 0.02),
  12325. new BABYLON.Color3(0.36, 0.49, 0.09),
  12326. new BABYLON.Color3(0.51, 0.6, 0.28)
  12327. ];
  12328. this.updateShaderUniforms();
  12329. this.refreshRate = 0;
  12330. }
  12331. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  12332. this.setColor3("herb1Color", this._grassColors[0]);
  12333. this.setColor3("herb2Color", this._grassColors[1]);
  12334. this.setColor3("herb3Color", this._grassColors[2]);
  12335. this.setColor3("groundColor", this._groundColor);
  12336. };
  12337. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  12338. get: function () {
  12339. return this._grassColors;
  12340. },
  12341. set: function (value) {
  12342. this._grassColors = value;
  12343. this.updateShaderUniforms();
  12344. },
  12345. enumerable: true,
  12346. configurable: true
  12347. });
  12348. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  12349. get: function () {
  12350. return this._groundColor;
  12351. },
  12352. set: function (value) {
  12353. this.groundColor = value;
  12354. this.updateShaderUniforms();
  12355. },
  12356. enumerable: true,
  12357. configurable: true
  12358. });
  12359. return GrassProceduralTexture;
  12360. })(BABYLON.ProceduralTexture);
  12361. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  12362. var RoadProceduralTexture = (function (_super) {
  12363. __extends(RoadProceduralTexture, _super);
  12364. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12365. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  12366. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  12367. this.updateShaderUniforms();
  12368. this.refreshRate = 0;
  12369. }
  12370. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  12371. this.setColor3("roadColor", this._roadColor);
  12372. };
  12373. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  12374. get: function () {
  12375. return this._roadColor;
  12376. },
  12377. set: function (value) {
  12378. this._roadColor = value;
  12379. this.updateShaderUniforms();
  12380. },
  12381. enumerable: true,
  12382. configurable: true
  12383. });
  12384. return RoadProceduralTexture;
  12385. })(BABYLON.ProceduralTexture);
  12386. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  12387. var BrickProceduralTexture = (function (_super) {
  12388. __extends(BrickProceduralTexture, _super);
  12389. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12390. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  12391. this._numberOfBricksHeight = 15;
  12392. this._numberOfBricksWidth = 5;
  12393. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12394. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12395. this.updateShaderUniforms();
  12396. this.refreshRate = 0;
  12397. }
  12398. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  12399. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  12400. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  12401. this.setColor3("brickColor", this._brickColor);
  12402. this.setColor3("jointColor", this._jointColor);
  12403. };
  12404. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  12405. get: function () {
  12406. return this._numberOfBricksHeight;
  12407. },
  12408. enumerable: true,
  12409. configurable: true
  12410. });
  12411. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  12412. set: function (value) {
  12413. this._numberOfBricksHeight = value;
  12414. this.updateShaderUniforms();
  12415. },
  12416. enumerable: true,
  12417. configurable: true
  12418. });
  12419. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  12420. get: function () {
  12421. return this._numberOfBricksWidth;
  12422. },
  12423. set: function (value) {
  12424. this._numberOfBricksHeight = value;
  12425. this.updateShaderUniforms();
  12426. },
  12427. enumerable: true,
  12428. configurable: true
  12429. });
  12430. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  12431. get: function () {
  12432. return this._jointColor;
  12433. },
  12434. set: function (value) {
  12435. this._jointColor = value;
  12436. this.updateShaderUniforms();
  12437. },
  12438. enumerable: true,
  12439. configurable: true
  12440. });
  12441. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  12442. get: function () {
  12443. return this._brickColor;
  12444. },
  12445. set: function (value) {
  12446. this._brickColor = value;
  12447. this.updateShaderUniforms();
  12448. },
  12449. enumerable: true,
  12450. configurable: true
  12451. });
  12452. return BrickProceduralTexture;
  12453. })(BABYLON.ProceduralTexture);
  12454. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  12455. var MarbleProceduralTexture = (function (_super) {
  12456. __extends(MarbleProceduralTexture, _super);
  12457. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12458. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  12459. this._numberOfTilesHeight = 3;
  12460. this._numberOfTilesWidth = 3;
  12461. this._amplitude = 9.0;
  12462. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12463. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12464. this.updateShaderUniforms();
  12465. this.refreshRate = 0;
  12466. }
  12467. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  12468. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  12469. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  12470. this.setFloat("amplitude", this._amplitude);
  12471. this.setColor3("marbleColor", this._marbleColor);
  12472. this.setColor3("jointColor", this._jointColor);
  12473. };
  12474. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  12475. get: function () {
  12476. return this._numberOfTilesHeight;
  12477. },
  12478. set: function (value) {
  12479. this._numberOfTilesHeight = value;
  12480. this.updateShaderUniforms();
  12481. },
  12482. enumerable: true,
  12483. configurable: true
  12484. });
  12485. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  12486. get: function () {
  12487. return this._numberOfTilesWidth;
  12488. },
  12489. set: function (value) {
  12490. this._numberOfTilesWidth = value;
  12491. this.updateShaderUniforms();
  12492. },
  12493. enumerable: true,
  12494. configurable: true
  12495. });
  12496. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  12497. get: function () {
  12498. return this._jointColor;
  12499. },
  12500. set: function (value) {
  12501. this._jointColor = value;
  12502. this.updateShaderUniforms();
  12503. },
  12504. enumerable: true,
  12505. configurable: true
  12506. });
  12507. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  12508. get: function () {
  12509. return this._marbleColor;
  12510. },
  12511. set: function (value) {
  12512. this._marbleColor = value;
  12513. this.updateShaderUniforms();
  12514. },
  12515. enumerable: true,
  12516. configurable: true
  12517. });
  12518. return MarbleProceduralTexture;
  12519. })(BABYLON.ProceduralTexture);
  12520. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  12521. })(BABYLON || (BABYLON = {}));
  12522. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  12523. var BABYLON;
  12524. (function (BABYLON) {
  12525. var CustomProceduralTexture = (function (_super) {
  12526. __extends(CustomProceduralTexture, _super);
  12527. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  12528. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  12529. this._animate = true;
  12530. this._time = 0;
  12531. this._texturePath = texturePath;
  12532. //Try to load json
  12533. this.loadJson(texturePath);
  12534. this.refreshRate = 1;
  12535. }
  12536. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  12537. var _this = this;
  12538. var that = this;
  12539. function noConfigFile() {
  12540. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  12541. try {
  12542. that.setFragment(that._texturePath);
  12543. }
  12544. catch (ex) {
  12545. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  12546. }
  12547. }
  12548. var configFileUrl = jsonUrl + "/config.json";
  12549. var xhr = new XMLHttpRequest();
  12550. xhr.open("GET", configFileUrl, true);
  12551. xhr.addEventListener("load", function () {
  12552. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12553. try {
  12554. _this._config = JSON.parse(xhr.response);
  12555. _this.updateShaderUniforms();
  12556. _this.updateTextures();
  12557. _this.setFragment(_this._texturePath + "/custom");
  12558. _this._animate = _this._config.animate;
  12559. _this.refreshRate = _this._config.refreshrate;
  12560. }
  12561. catch (ex) {
  12562. noConfigFile();
  12563. }
  12564. }
  12565. else {
  12566. noConfigFile();
  12567. }
  12568. }, false);
  12569. xhr.addEventListener("error", function (event) {
  12570. noConfigFile();
  12571. }, false);
  12572. try {
  12573. xhr.send();
  12574. }
  12575. catch (ex) {
  12576. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  12577. }
  12578. };
  12579. CustomProceduralTexture.prototype.isReady = function () {
  12580. if (!_super.prototype.isReady.call(this)) {
  12581. return false;
  12582. }
  12583. for (var name in this._textures) {
  12584. var texture = this._textures[name];
  12585. if (!texture.isReady()) {
  12586. return false;
  12587. }
  12588. }
  12589. return true;
  12590. };
  12591. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12592. if (this._animate) {
  12593. this._time += this.getScene().getAnimationRatio() * 0.03;
  12594. this.updateShaderUniforms();
  12595. }
  12596. _super.prototype.render.call(this, useCameraPostProcess);
  12597. };
  12598. CustomProceduralTexture.prototype.updateTextures = function () {
  12599. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  12600. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  12601. }
  12602. };
  12603. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  12604. if (this._config) {
  12605. for (var j = 0; j < this._config.uniforms.length; j++) {
  12606. var uniform = this._config.uniforms[j];
  12607. switch (uniform.type) {
  12608. case "float":
  12609. this.setFloat(uniform.name, uniform.value);
  12610. break;
  12611. case "color3":
  12612. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  12613. break;
  12614. case "color4":
  12615. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  12616. break;
  12617. case "vector2":
  12618. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  12619. break;
  12620. case "vector3":
  12621. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  12622. break;
  12623. }
  12624. }
  12625. }
  12626. this.setFloat("time", this._time);
  12627. };
  12628. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  12629. get: function () {
  12630. return this._animate;
  12631. },
  12632. set: function (value) {
  12633. this._animate = value;
  12634. },
  12635. enumerable: true,
  12636. configurable: true
  12637. });
  12638. return CustomProceduralTexture;
  12639. })(BABYLON.ProceduralTexture);
  12640. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  12641. })(BABYLON || (BABYLON = {}));
  12642. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  12643. var BABYLON;
  12644. (function (BABYLON) {
  12645. var MirrorTexture = (function (_super) {
  12646. __extends(MirrorTexture, _super);
  12647. function MirrorTexture(name, size, scene, generateMipMaps) {
  12648. var _this = this;
  12649. _super.call(this, name, size, scene, generateMipMaps, true);
  12650. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  12651. this._transformMatrix = BABYLON.Matrix.Zero();
  12652. this._mirrorMatrix = BABYLON.Matrix.Zero();
  12653. this.onBeforeRender = function () {
  12654. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  12655. _this._savedViewMatrix = scene.getViewMatrix();
  12656. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  12657. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  12658. scene.clipPlane = _this.mirrorPlane;
  12659. scene.getEngine().cullBackFaces = false;
  12660. };
  12661. this.onAfterRender = function () {
  12662. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  12663. scene.getEngine().cullBackFaces = true;
  12664. delete scene.clipPlane;
  12665. };
  12666. }
  12667. MirrorTexture.prototype.clone = function () {
  12668. var textureSize = this.getSize();
  12669. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12670. // Base texture
  12671. newTexture.hasAlpha = this.hasAlpha;
  12672. newTexture.level = this.level;
  12673. // Mirror Texture
  12674. newTexture.mirrorPlane = this.mirrorPlane.clone();
  12675. newTexture.renderList = this.renderList.slice(0);
  12676. return newTexture;
  12677. };
  12678. return MirrorTexture;
  12679. })(BABYLON.RenderTargetTexture);
  12680. BABYLON.MirrorTexture = MirrorTexture;
  12681. })(BABYLON || (BABYLON = {}));
  12682. //# sourceMappingURL=babylon.mirrorTexture.js.map
  12683. var BABYLON;
  12684. (function (BABYLON) {
  12685. var DynamicTexture = (function (_super) {
  12686. __extends(DynamicTexture, _super);
  12687. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  12688. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12689. _super.call(this, null, scene, !generateMipMaps);
  12690. this.name = name;
  12691. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12692. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12693. this._generateMipMaps = generateMipMaps;
  12694. if (options.getContext) {
  12695. this._canvas = options;
  12696. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12697. }
  12698. else {
  12699. this._canvas = document.createElement("canvas");
  12700. if (options.width) {
  12701. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12702. }
  12703. else {
  12704. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  12705. }
  12706. }
  12707. var textureSize = this.getSize();
  12708. this._canvas.width = textureSize.width;
  12709. this._canvas.height = textureSize.height;
  12710. this._context = this._canvas.getContext("2d");
  12711. }
  12712. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  12713. get: function () {
  12714. return true;
  12715. },
  12716. enumerable: true,
  12717. configurable: true
  12718. });
  12719. DynamicTexture.prototype.scale = function (ratio) {
  12720. var textureSize = this.getSize();
  12721. textureSize.width *= ratio;
  12722. textureSize.height *= ratio;
  12723. this._canvas.width = textureSize.width;
  12724. this._canvas.height = textureSize.height;
  12725. this.releaseInternalTexture();
  12726. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  12727. };
  12728. DynamicTexture.prototype.getContext = function () {
  12729. return this._context;
  12730. };
  12731. DynamicTexture.prototype.clear = function () {
  12732. var size = this.getSize();
  12733. this._context.fillRect(0, 0, size.width, size.height);
  12734. };
  12735. DynamicTexture.prototype.update = function (invertY) {
  12736. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  12737. };
  12738. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  12739. if (update === void 0) { update = true; }
  12740. var size = this.getSize();
  12741. if (clearColor) {
  12742. this._context.fillStyle = clearColor;
  12743. this._context.fillRect(0, 0, size.width, size.height);
  12744. }
  12745. this._context.font = font;
  12746. if (x === null) {
  12747. var textSize = this._context.measureText(text);
  12748. x = (size.width - textSize.width) / 2;
  12749. }
  12750. this._context.fillStyle = color;
  12751. this._context.fillText(text, x, y);
  12752. if (update) {
  12753. this.update(invertY);
  12754. }
  12755. };
  12756. DynamicTexture.prototype.clone = function () {
  12757. var textureSize = this.getSize();
  12758. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12759. // Base texture
  12760. newTexture.hasAlpha = this.hasAlpha;
  12761. newTexture.level = this.level;
  12762. // Dynamic Texture
  12763. newTexture.wrapU = this.wrapU;
  12764. newTexture.wrapV = this.wrapV;
  12765. return newTexture;
  12766. };
  12767. return DynamicTexture;
  12768. })(BABYLON.Texture);
  12769. BABYLON.DynamicTexture = DynamicTexture;
  12770. })(BABYLON || (BABYLON = {}));
  12771. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12772. var BABYLON;
  12773. (function (BABYLON) {
  12774. var VideoTexture = (function (_super) {
  12775. __extends(VideoTexture, _super);
  12776. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12777. var _this = this;
  12778. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12779. _super.call(this, null, scene, !generateMipMaps, invertY);
  12780. this._autoLaunch = true;
  12781. this.name = name;
  12782. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12783. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12784. var requiredWidth = size.width || size;
  12785. var requiredHeight = size.height || size;
  12786. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12787. var textureSize = this.getSize();
  12788. this.video = document.createElement("video");
  12789. this.video.width = textureSize.width;
  12790. this.video.height = textureSize.height;
  12791. this.video.autoplay = false;
  12792. this.video.loop = true;
  12793. this.video.addEventListener("canplaythrough", function () {
  12794. if (_this._texture) {
  12795. _this._texture.isReady = true;
  12796. }
  12797. });
  12798. urls.forEach(function (url) {
  12799. var source = document.createElement("source");
  12800. source.src = url;
  12801. _this.video.appendChild(source);
  12802. });
  12803. this._lastUpdate = BABYLON.Tools.Now;
  12804. }
  12805. VideoTexture.prototype.update = function () {
  12806. if (this._autoLaunch) {
  12807. this._autoLaunch = false;
  12808. this.video.play();
  12809. }
  12810. var now = BABYLON.Tools.Now;
  12811. if (now - this._lastUpdate < 15) {
  12812. return false;
  12813. }
  12814. this._lastUpdate = now;
  12815. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  12816. return true;
  12817. };
  12818. return VideoTexture;
  12819. })(BABYLON.Texture);
  12820. BABYLON.VideoTexture = VideoTexture;
  12821. })(BABYLON || (BABYLON = {}));
  12822. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  12823. (function (BABYLON) {
  12824. var EffectFallbacks = (function () {
  12825. function EffectFallbacks() {
  12826. this._defines = {};
  12827. this._currentRank = 32;
  12828. this._maxRank = -1;
  12829. }
  12830. EffectFallbacks.prototype.addFallback = function (rank, define) {
  12831. if (!this._defines[rank]) {
  12832. if (rank < this._currentRank) {
  12833. this._currentRank = rank;
  12834. }
  12835. if (rank > this._maxRank) {
  12836. this._maxRank = rank;
  12837. }
  12838. this._defines[rank] = new Array();
  12839. }
  12840. this._defines[rank].push(define);
  12841. };
  12842. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  12843. get: function () {
  12844. return this._currentRank <= this._maxRank;
  12845. },
  12846. enumerable: true,
  12847. configurable: true
  12848. });
  12849. EffectFallbacks.prototype.reduce = function (currentDefines) {
  12850. var currentFallbacks = this._defines[this._currentRank];
  12851. for (var index = 0; index < currentFallbacks.length; index++) {
  12852. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  12853. }
  12854. this._currentRank++;
  12855. return currentDefines;
  12856. };
  12857. return EffectFallbacks;
  12858. })();
  12859. BABYLON.EffectFallbacks = EffectFallbacks;
  12860. var Effect = (function () {
  12861. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  12862. var _this = this;
  12863. this._isReady = false;
  12864. this._compilationError = "";
  12865. this._valueCache = [];
  12866. this._engine = engine;
  12867. this.name = baseName;
  12868. this.defines = defines;
  12869. this._uniformsNames = uniformsNames.concat(samplers);
  12870. this._samplers = samplers;
  12871. this._attributesNames = attributesNames;
  12872. this.onError = onError;
  12873. this.onCompiled = onCompiled;
  12874. var vertexSource;
  12875. var fragmentSource;
  12876. if (baseName.vertexElement) {
  12877. vertexSource = document.getElementById(baseName.vertexElement);
  12878. if (!vertexSource) {
  12879. vertexSource = baseName.vertexElement;
  12880. }
  12881. }
  12882. else {
  12883. vertexSource = baseName.vertex || baseName;
  12884. }
  12885. if (baseName.fragmentElement) {
  12886. fragmentSource = document.getElementById(baseName.fragmentElement);
  12887. if (!fragmentSource) {
  12888. fragmentSource = baseName.fragmentElement;
  12889. }
  12890. }
  12891. else {
  12892. fragmentSource = baseName.fragment || baseName;
  12893. }
  12894. this._loadVertexShader(vertexSource, function (vertexCode) {
  12895. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  12896. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  12897. });
  12898. });
  12899. }
  12900. // Properties
  12901. Effect.prototype.isReady = function () {
  12902. return this._isReady;
  12903. };
  12904. Effect.prototype.getProgram = function () {
  12905. return this._program;
  12906. };
  12907. Effect.prototype.getAttributesNames = function () {
  12908. return this._attributesNames;
  12909. };
  12910. Effect.prototype.getAttributeLocation = function (index) {
  12911. return this._attributes[index];
  12912. };
  12913. Effect.prototype.getAttributeLocationByName = function (name) {
  12914. var index = this._attributesNames.indexOf(name);
  12915. return this._attributes[index];
  12916. };
  12917. Effect.prototype.getAttributesCount = function () {
  12918. return this._attributes.length;
  12919. };
  12920. Effect.prototype.getUniformIndex = function (uniformName) {
  12921. return this._uniformsNames.indexOf(uniformName);
  12922. };
  12923. Effect.prototype.getUniform = function (uniformName) {
  12924. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  12925. };
  12926. Effect.prototype.getSamplers = function () {
  12927. return this._samplers;
  12928. };
  12929. Effect.prototype.getCompilationError = function () {
  12930. return this._compilationError;
  12931. };
  12932. // Methods
  12933. Effect.prototype._loadVertexShader = function (vertex, callback) {
  12934. // DOM element ?
  12935. if (vertex instanceof HTMLElement) {
  12936. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  12937. callback(vertexCode);
  12938. return;
  12939. }
  12940. // Is in local store ?
  12941. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  12942. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  12943. return;
  12944. }
  12945. var vertexShaderUrl;
  12946. if (vertex[0] === ".") {
  12947. vertexShaderUrl = vertex;
  12948. }
  12949. else {
  12950. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  12951. }
  12952. // Vertex shader
  12953. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  12954. };
  12955. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  12956. // DOM element ?
  12957. if (fragment instanceof HTMLElement) {
  12958. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  12959. callback(fragmentCode);
  12960. return;
  12961. }
  12962. // Is in local store ?
  12963. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  12964. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  12965. return;
  12966. }
  12967. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  12968. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  12969. return;
  12970. }
  12971. var fragmentShaderUrl;
  12972. if (fragment[0] === ".") {
  12973. fragmentShaderUrl = fragment;
  12974. }
  12975. else {
  12976. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  12977. }
  12978. // Fragment shader
  12979. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  12980. };
  12981. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  12982. try {
  12983. var engine = this._engine;
  12984. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  12985. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  12986. this._attributes = engine.getAttributes(this._program, attributesNames);
  12987. for (var index = 0; index < this._samplers.length; index++) {
  12988. var sampler = this.getUniform(this._samplers[index]);
  12989. if (sampler == null) {
  12990. this._samplers.splice(index, 1);
  12991. index--;
  12992. }
  12993. }
  12994. engine.bindSamplers(this);
  12995. this._isReady = true;
  12996. if (this.onCompiled) {
  12997. this.onCompiled(this);
  12998. }
  12999. }
  13000. catch (e) {
  13001. // Is it a problem with precision?
  13002. if (e.message.indexOf("highp") !== -1) {
  13003. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  13004. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  13005. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13006. return;
  13007. }
  13008. // Let's go through fallbacks then
  13009. if (fallbacks && fallbacks.isMoreFallbacks) {
  13010. defines = fallbacks.reduce(defines);
  13011. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13012. }
  13013. else {
  13014. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  13015. BABYLON.Tools.Error("Defines: " + defines);
  13016. BABYLON.Tools.Error("Error: " + e.message);
  13017. this._compilationError = e.message;
  13018. if (this.onError) {
  13019. this.onError(this, this._compilationError);
  13020. }
  13021. }
  13022. }
  13023. };
  13024. Effect.prototype._bindTexture = function (channel, texture) {
  13025. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  13026. };
  13027. Effect.prototype.setTexture = function (channel, texture) {
  13028. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  13029. };
  13030. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13031. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  13032. };
  13033. //public _cacheMatrix(uniformName, matrix) {
  13034. // if (!this._valueCache[uniformName]) {
  13035. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13036. // }
  13037. // for (var index = 0; index < 16; index++) {
  13038. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13039. // }
  13040. //};
  13041. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13042. if (!this._valueCache[uniformName]) {
  13043. this._valueCache[uniformName] = [x, y];
  13044. return;
  13045. }
  13046. this._valueCache[uniformName][0] = x;
  13047. this._valueCache[uniformName][1] = y;
  13048. };
  13049. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13050. if (!this._valueCache[uniformName]) {
  13051. this._valueCache[uniformName] = [x, y, z];
  13052. return;
  13053. }
  13054. this._valueCache[uniformName][0] = x;
  13055. this._valueCache[uniformName][1] = y;
  13056. this._valueCache[uniformName][2] = z;
  13057. };
  13058. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13059. if (!this._valueCache[uniformName]) {
  13060. this._valueCache[uniformName] = [x, y, z, w];
  13061. return;
  13062. }
  13063. this._valueCache[uniformName][0] = x;
  13064. this._valueCache[uniformName][1] = y;
  13065. this._valueCache[uniformName][2] = z;
  13066. this._valueCache[uniformName][3] = w;
  13067. };
  13068. Effect.prototype.setArray = function (uniformName, array) {
  13069. this._engine.setArray(this.getUniform(uniformName), array);
  13070. return this;
  13071. };
  13072. Effect.prototype.setArray2 = function (uniformName, array) {
  13073. this._engine.setArray2(this.getUniform(uniformName), array);
  13074. return this;
  13075. };
  13076. Effect.prototype.setArray3 = function (uniformName, array) {
  13077. this._engine.setArray3(this.getUniform(uniformName), array);
  13078. return this;
  13079. };
  13080. Effect.prototype.setArray4 = function (uniformName, array) {
  13081. this._engine.setArray4(this.getUniform(uniformName), array);
  13082. return this;
  13083. };
  13084. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13085. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13086. return this;
  13087. };
  13088. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13089. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13090. // return;
  13091. //this._cacheMatrix(uniformName, matrix);
  13092. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13093. return this;
  13094. };
  13095. Effect.prototype.setFloat = function (uniformName, value) {
  13096. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13097. return this;
  13098. this._valueCache[uniformName] = value;
  13099. this._engine.setFloat(this.getUniform(uniformName), value);
  13100. return this;
  13101. };
  13102. Effect.prototype.setBool = function (uniformName, bool) {
  13103. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13104. return this;
  13105. this._valueCache[uniformName] = bool;
  13106. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13107. return this;
  13108. };
  13109. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13110. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13111. return this;
  13112. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13113. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13114. return this;
  13115. };
  13116. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13117. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13118. return this;
  13119. this._cacheFloat2(uniformName, x, y);
  13120. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13121. return this;
  13122. };
  13123. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13124. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13125. return this;
  13126. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13127. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13128. return this;
  13129. };
  13130. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13131. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13132. return this;
  13133. this._cacheFloat3(uniformName, x, y, z);
  13134. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13135. return this;
  13136. };
  13137. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13138. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13139. return this;
  13140. this._cacheFloat4(uniformName, x, y, z, w);
  13141. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13142. return this;
  13143. };
  13144. Effect.prototype.setColor3 = function (uniformName, color3) {
  13145. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13146. return this;
  13147. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13148. this._engine.setColor3(this.getUniform(uniformName), color3);
  13149. return this;
  13150. };
  13151. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13152. 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)
  13153. return this;
  13154. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13155. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13156. return this;
  13157. };
  13158. // Statics
  13159. 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}",
  13160. 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}",
  13161. 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}",
  13162. 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}",
  13163. 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}",
  13164. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13165. 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}",
  13166. 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}",
  13167. 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}",
  13168. 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}",
  13169. 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}",
  13170. 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}",
  13171. 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}",
  13172. 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}",
  13173. 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}",
  13174. 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}",
  13175. 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}",
  13176. 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}",
  13177. 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}",
  13178. 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}",
  13179. 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}",
  13180. 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}",
  13181. 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}",
  13182. 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}",
  13183. 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}",
  13184. 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}",
  13185. 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}",
  13186. 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}",
  13187. 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}",
  13188. 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}",
  13189. 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}",
  13190. 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}",
  13191. 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}",
  13192. 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}",
  13193. 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}",
  13194. 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}",
  13195. 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}",
  13196. 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}",
  13197. 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}",
  13198. 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}",
  13199. 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}",
  13200. };
  13201. return Effect;
  13202. })();
  13203. BABYLON.Effect = Effect;
  13204. })(BABYLON || (BABYLON = {}));
  13205. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13206. (function (BABYLON) {
  13207. var Material = (function () {
  13208. function Material(name, scene, doNotAdd) {
  13209. this.name = name;
  13210. this.checkReadyOnEveryCall = true;
  13211. this.checkReadyOnlyOnce = false;
  13212. this.state = "";
  13213. this.alpha = 1.0;
  13214. this.backFaceCulling = true;
  13215. this._wasPreviouslyReady = false;
  13216. this._fillMode = Material.TriangleFillMode;
  13217. this.pointSize = 1.0;
  13218. this.id = name;
  13219. this._scene = scene;
  13220. if (!doNotAdd) {
  13221. scene.materials.push(this);
  13222. }
  13223. }
  13224. Object.defineProperty(Material, "TriangleFillMode", {
  13225. get: function () {
  13226. return Material._TriangleFillMode;
  13227. },
  13228. enumerable: true,
  13229. configurable: true
  13230. });
  13231. Object.defineProperty(Material, "WireFrameFillMode", {
  13232. get: function () {
  13233. return Material._WireFrameFillMode;
  13234. },
  13235. enumerable: true,
  13236. configurable: true
  13237. });
  13238. Object.defineProperty(Material, "PointFillMode", {
  13239. get: function () {
  13240. return Material._PointFillMode;
  13241. },
  13242. enumerable: true,
  13243. configurable: true
  13244. });
  13245. Object.defineProperty(Material.prototype, "wireframe", {
  13246. get: function () {
  13247. return this._fillMode === Material.WireFrameFillMode;
  13248. },
  13249. set: function (value) {
  13250. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13251. },
  13252. enumerable: true,
  13253. configurable: true
  13254. });
  13255. Object.defineProperty(Material.prototype, "pointsCloud", {
  13256. get: function () {
  13257. return this._fillMode === Material.PointFillMode;
  13258. },
  13259. set: function (value) {
  13260. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13261. },
  13262. enumerable: true,
  13263. configurable: true
  13264. });
  13265. Object.defineProperty(Material.prototype, "fillMode", {
  13266. get: function () {
  13267. return this._fillMode;
  13268. },
  13269. set: function (value) {
  13270. this._fillMode = value;
  13271. },
  13272. enumerable: true,
  13273. configurable: true
  13274. });
  13275. Material.prototype.isReady = function (mesh, useInstances) {
  13276. return true;
  13277. };
  13278. Material.prototype.getEffect = function () {
  13279. return this._effect;
  13280. };
  13281. Material.prototype.getScene = function () {
  13282. return this._scene;
  13283. };
  13284. Material.prototype.needAlphaBlending = function () {
  13285. return (this.alpha < 1.0);
  13286. };
  13287. Material.prototype.needAlphaTesting = function () {
  13288. return false;
  13289. };
  13290. Material.prototype.getAlphaTestTexture = function () {
  13291. return null;
  13292. };
  13293. Material.prototype.trackCreation = function (onCompiled, onError) {
  13294. };
  13295. Material.prototype._preBind = function () {
  13296. var engine = this._scene.getEngine();
  13297. engine.enableEffect(this._effect);
  13298. engine.setState(this.backFaceCulling);
  13299. };
  13300. Material.prototype.bind = function (world, mesh) {
  13301. this._scene._cachedMaterial = this;
  13302. if (this.onBind) {
  13303. this.onBind(this);
  13304. }
  13305. };
  13306. Material.prototype.bindOnlyWorldMatrix = function (world) {
  13307. };
  13308. Material.prototype.unbind = function () {
  13309. };
  13310. Material.prototype.dispose = function (forceDisposeEffect) {
  13311. // Remove from scene
  13312. var index = this._scene.materials.indexOf(this);
  13313. this._scene.materials.splice(index, 1);
  13314. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  13315. if (forceDisposeEffect && this._effect) {
  13316. this._scene.getEngine()._releaseEffect(this._effect);
  13317. this._effect = null;
  13318. }
  13319. // Callback
  13320. if (this.onDispose) {
  13321. this.onDispose();
  13322. }
  13323. };
  13324. Material._TriangleFillMode = 0;
  13325. Material._WireFrameFillMode = 1;
  13326. Material._PointFillMode = 2;
  13327. return Material;
  13328. })();
  13329. BABYLON.Material = Material;
  13330. })(BABYLON || (BABYLON = {}));
  13331. //# sourceMappingURL=babylon.material.js.map
  13332. var BABYLON;
  13333. (function (BABYLON) {
  13334. var maxSimultaneousLights = 4;
  13335. var FresnelParameters = (function () {
  13336. function FresnelParameters() {
  13337. this.isEnabled = true;
  13338. this.leftColor = BABYLON.Color3.White();
  13339. this.rightColor = BABYLON.Color3.Black();
  13340. this.bias = 0;
  13341. this.power = 1;
  13342. }
  13343. return FresnelParameters;
  13344. })();
  13345. BABYLON.FresnelParameters = FresnelParameters;
  13346. var StandardMaterial = (function (_super) {
  13347. __extends(StandardMaterial, _super);
  13348. function StandardMaterial(name, scene) {
  13349. var _this = this;
  13350. _super.call(this, name, scene);
  13351. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13352. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  13353. this.specularColor = new BABYLON.Color3(1, 1, 1);
  13354. this.specularPower = 64;
  13355. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  13356. this.useAlphaFromDiffuseTexture = false;
  13357. this.useSpecularOverAlpha = true;
  13358. this.fogEnabled = true;
  13359. this._cachedDefines = null;
  13360. this._renderTargets = new BABYLON.SmartArray(16);
  13361. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  13362. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  13363. this._scaledDiffuse = new BABYLON.Color3();
  13364. this._scaledSpecular = new BABYLON.Color3();
  13365. this.getRenderTargetTextures = function () {
  13366. _this._renderTargets.reset();
  13367. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  13368. _this._renderTargets.push(_this.reflectionTexture);
  13369. }
  13370. return _this._renderTargets;
  13371. };
  13372. }
  13373. StandardMaterial.prototype.needAlphaBlending = function () {
  13374. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  13375. };
  13376. StandardMaterial.prototype.needAlphaTesting = function () {
  13377. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  13378. };
  13379. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  13380. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  13381. };
  13382. StandardMaterial.prototype.getAlphaTestTexture = function () {
  13383. return this.diffuseTexture;
  13384. };
  13385. // Methods
  13386. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  13387. if (this.checkReadyOnlyOnce) {
  13388. if (this._wasPreviouslyReady) {
  13389. return true;
  13390. }
  13391. }
  13392. var scene = this.getScene();
  13393. if (!this.checkReadyOnEveryCall) {
  13394. if (this._renderId === scene.getRenderId()) {
  13395. return true;
  13396. }
  13397. }
  13398. var engine = scene.getEngine();
  13399. var defines = [];
  13400. var fallbacks = new BABYLON.EffectFallbacks();
  13401. // Textures
  13402. if (scene.texturesEnabled) {
  13403. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13404. if (!this.diffuseTexture.isReady()) {
  13405. return false;
  13406. }
  13407. else {
  13408. defines.push("#define DIFFUSE");
  13409. }
  13410. }
  13411. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13412. if (!this.ambientTexture.isReady()) {
  13413. return false;
  13414. }
  13415. else {
  13416. defines.push("#define AMBIENT");
  13417. }
  13418. }
  13419. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13420. if (!this.opacityTexture.isReady()) {
  13421. return false;
  13422. }
  13423. else {
  13424. defines.push("#define OPACITY");
  13425. if (this.opacityTexture.getAlphaFromRGB) {
  13426. defines.push("#define OPACITYRGB");
  13427. }
  13428. }
  13429. }
  13430. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13431. if (!this.reflectionTexture.isReady()) {
  13432. return false;
  13433. }
  13434. else {
  13435. defines.push("#define REFLECTION");
  13436. fallbacks.addFallback(0, "REFLECTION");
  13437. }
  13438. }
  13439. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13440. if (!this.emissiveTexture.isReady()) {
  13441. return false;
  13442. }
  13443. else {
  13444. defines.push("#define EMISSIVE");
  13445. }
  13446. }
  13447. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13448. if (!this.specularTexture.isReady()) {
  13449. return false;
  13450. }
  13451. else {
  13452. defines.push("#define SPECULAR");
  13453. fallbacks.addFallback(0, "SPECULAR");
  13454. }
  13455. }
  13456. }
  13457. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  13458. if (!this.bumpTexture.isReady()) {
  13459. return false;
  13460. }
  13461. else {
  13462. defines.push("#define BUMP");
  13463. fallbacks.addFallback(0, "BUMP");
  13464. }
  13465. }
  13466. // Effect
  13467. if (this.useSpecularOverAlpha) {
  13468. defines.push("#define SPECULAROVERALPHA");
  13469. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  13470. }
  13471. if (scene.clipPlane) {
  13472. defines.push("#define CLIPPLANE");
  13473. }
  13474. if (engine.getAlphaTesting()) {
  13475. defines.push("#define ALPHATEST");
  13476. }
  13477. if (this._shouldUseAlphaFromDiffuseTexture()) {
  13478. defines.push("#define ALPHAFROMDIFFUSE");
  13479. }
  13480. // Point size
  13481. if (this.pointsCloud || scene.forcePointsCloud) {
  13482. defines.push("#define POINTSIZE");
  13483. }
  13484. // Fog
  13485. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13486. defines.push("#define FOG");
  13487. fallbacks.addFallback(1, "FOG");
  13488. }
  13489. var shadowsActivated = false;
  13490. var lightIndex = 0;
  13491. if (scene.lightsEnabled) {
  13492. for (var index = 0; index < scene.lights.length; index++) {
  13493. var light = scene.lights[index];
  13494. if (!light.isEnabled()) {
  13495. continue;
  13496. }
  13497. // Excluded check
  13498. if (light._excludedMeshesIds.length > 0) {
  13499. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  13500. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  13501. if (excludedMesh) {
  13502. light.excludedMeshes.push(excludedMesh);
  13503. }
  13504. }
  13505. light._excludedMeshesIds = [];
  13506. }
  13507. // Included check
  13508. if (light._includedOnlyMeshesIds.length > 0) {
  13509. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  13510. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  13511. if (includedOnlyMesh) {
  13512. light.includedOnlyMeshes.push(includedOnlyMesh);
  13513. }
  13514. }
  13515. light._includedOnlyMeshesIds = [];
  13516. }
  13517. if (!light.canAffectMesh(mesh)) {
  13518. continue;
  13519. }
  13520. defines.push("#define LIGHT" + lightIndex);
  13521. if (lightIndex > 0) {
  13522. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  13523. }
  13524. var type;
  13525. if (light instanceof BABYLON.SpotLight) {
  13526. type = "#define SPOTLIGHT" + lightIndex;
  13527. }
  13528. else if (light instanceof BABYLON.HemisphericLight) {
  13529. type = "#define HEMILIGHT" + lightIndex;
  13530. }
  13531. else {
  13532. type = "#define POINTDIRLIGHT" + lightIndex;
  13533. }
  13534. defines.push(type);
  13535. if (lightIndex > 0) {
  13536. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  13537. }
  13538. // Shadows
  13539. if (scene.shadowsEnabled) {
  13540. var shadowGenerator = light.getShadowGenerator();
  13541. if (mesh && mesh.receiveShadows && shadowGenerator) {
  13542. defines.push("#define SHADOW" + lightIndex);
  13543. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  13544. if (!shadowsActivated) {
  13545. defines.push("#define SHADOWS");
  13546. shadowsActivated = true;
  13547. }
  13548. if (shadowGenerator.useVarianceShadowMap) {
  13549. defines.push("#define SHADOWVSM" + lightIndex);
  13550. if (lightIndex > 0) {
  13551. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  13552. }
  13553. }
  13554. if (shadowGenerator.usePoissonSampling) {
  13555. defines.push("#define SHADOWPCF" + lightIndex);
  13556. if (lightIndex > 0) {
  13557. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  13558. }
  13559. }
  13560. }
  13561. }
  13562. lightIndex++;
  13563. if (lightIndex === maxSimultaneousLights)
  13564. break;
  13565. }
  13566. }
  13567. if (StandardMaterial.FresnelEnabled) {
  13568. // Fresnel
  13569. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13570. var fresnelRank = 1;
  13571. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13572. defines.push("#define DIFFUSEFRESNEL");
  13573. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  13574. fresnelRank++;
  13575. }
  13576. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13577. defines.push("#define OPACITYFRESNEL");
  13578. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  13579. fresnelRank++;
  13580. }
  13581. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13582. defines.push("#define REFLECTIONFRESNEL");
  13583. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  13584. fresnelRank++;
  13585. }
  13586. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13587. defines.push("#define EMISSIVEFRESNEL");
  13588. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  13589. fresnelRank++;
  13590. }
  13591. defines.push("#define FRESNEL");
  13592. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  13593. }
  13594. }
  13595. // Attribs
  13596. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  13597. if (mesh) {
  13598. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13599. attribs.push(BABYLON.VertexBuffer.UVKind);
  13600. defines.push("#define UV1");
  13601. }
  13602. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13603. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  13604. defines.push("#define UV2");
  13605. }
  13606. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13607. attribs.push(BABYLON.VertexBuffer.ColorKind);
  13608. defines.push("#define VERTEXCOLOR");
  13609. if (mesh.hasVertexAlpha) {
  13610. defines.push("#define VERTEXALPHA");
  13611. }
  13612. }
  13613. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13614. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13615. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13616. defines.push("#define BONES");
  13617. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13618. defines.push("#define BONES4");
  13619. fallbacks.addFallback(0, "BONES4");
  13620. }
  13621. // Instances
  13622. if (useInstances) {
  13623. defines.push("#define INSTANCES");
  13624. attribs.push("world0");
  13625. attribs.push("world1");
  13626. attribs.push("world2");
  13627. attribs.push("world3");
  13628. }
  13629. }
  13630. // Get correct effect
  13631. var join = defines.join("\n");
  13632. if (this._cachedDefines !== join) {
  13633. this._cachedDefines = join;
  13634. scene.resetCachedMaterial();
  13635. // Legacy browser patch
  13636. var shaderName = "default";
  13637. if (!scene.getEngine().getCaps().standardDerivatives) {
  13638. shaderName = "legacydefault";
  13639. }
  13640. 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);
  13641. }
  13642. if (!this._effect.isReady()) {
  13643. return false;
  13644. }
  13645. this._renderId = scene.getRenderId();
  13646. this._wasPreviouslyReady = true;
  13647. return true;
  13648. };
  13649. StandardMaterial.prototype.unbind = function () {
  13650. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  13651. this._effect.setTexture("reflection2DSampler", null);
  13652. }
  13653. };
  13654. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  13655. this._effect.setMatrix("world", world);
  13656. };
  13657. StandardMaterial.prototype.bind = function (world, mesh) {
  13658. var scene = this.getScene();
  13659. // Matrices
  13660. this.bindOnlyWorldMatrix(world);
  13661. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  13662. // Bones
  13663. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13664. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  13665. }
  13666. if (scene.getCachedMaterial() !== this) {
  13667. if (StandardMaterial.FresnelEnabled) {
  13668. // Fresnel
  13669. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13670. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  13671. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  13672. }
  13673. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13674. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  13675. }
  13676. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13677. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  13678. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  13679. }
  13680. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13681. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  13682. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  13683. }
  13684. }
  13685. // Textures
  13686. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13687. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  13688. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  13689. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  13690. }
  13691. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13692. this._effect.setTexture("ambientSampler", this.ambientTexture);
  13693. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  13694. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  13695. }
  13696. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13697. this._effect.setTexture("opacitySampler", this.opacityTexture);
  13698. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  13699. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  13700. }
  13701. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13702. if (this.reflectionTexture.isCube) {
  13703. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  13704. }
  13705. else {
  13706. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  13707. }
  13708. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  13709. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  13710. }
  13711. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13712. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  13713. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  13714. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  13715. }
  13716. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13717. this._effect.setTexture("specularSampler", this.specularTexture);
  13718. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  13719. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  13720. }
  13721. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  13722. this._effect.setTexture("bumpSampler", this.bumpTexture);
  13723. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  13724. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  13725. }
  13726. // Clip plane
  13727. if (scene.clipPlane) {
  13728. var clipPlane = scene.clipPlane;
  13729. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13730. }
  13731. // Point size
  13732. if (this.pointsCloud) {
  13733. this._effect.setFloat("pointSize", this.pointSize);
  13734. }
  13735. // Colors
  13736. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  13737. // Scaling down color according to emissive
  13738. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13739. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13740. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13741. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  13742. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  13743. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  13744. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  13745. }
  13746. // Scaling down color according to emissive
  13747. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13748. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13749. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13750. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  13751. if (scene.lightsEnabled) {
  13752. var lightIndex = 0;
  13753. for (var index = 0; index < scene.lights.length; index++) {
  13754. var light = scene.lights[index];
  13755. if (!light.isEnabled()) {
  13756. continue;
  13757. }
  13758. if (!light.canAffectMesh(mesh)) {
  13759. continue;
  13760. }
  13761. if (light instanceof BABYLON.PointLight) {
  13762. // Point Light
  13763. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13764. }
  13765. else if (light instanceof BABYLON.DirectionalLight) {
  13766. // Directional Light
  13767. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13768. }
  13769. else if (light instanceof BABYLON.SpotLight) {
  13770. // Spot Light
  13771. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  13772. }
  13773. else if (light instanceof BABYLON.HemisphericLight) {
  13774. // Hemispheric Light
  13775. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  13776. }
  13777. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  13778. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  13779. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  13780. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  13781. // Shadows
  13782. if (scene.shadowsEnabled) {
  13783. var shadowGenerator = light.getShadowGenerator();
  13784. if (mesh.receiveShadows && shadowGenerator) {
  13785. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13786. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13787. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13788. }
  13789. }
  13790. lightIndex++;
  13791. if (lightIndex === maxSimultaneousLights)
  13792. break;
  13793. }
  13794. }
  13795. // View
  13796. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13797. this._effect.setMatrix("view", scene.getViewMatrix());
  13798. }
  13799. // Fog
  13800. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13801. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13802. this._effect.setColor3("vFogColor", scene.fogColor);
  13803. }
  13804. _super.prototype.bind.call(this, world, mesh);
  13805. };
  13806. StandardMaterial.prototype.getAnimatables = function () {
  13807. var results = [];
  13808. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  13809. results.push(this.diffuseTexture);
  13810. }
  13811. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  13812. results.push(this.ambientTexture);
  13813. }
  13814. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  13815. results.push(this.opacityTexture);
  13816. }
  13817. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  13818. results.push(this.reflectionTexture);
  13819. }
  13820. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  13821. results.push(this.emissiveTexture);
  13822. }
  13823. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  13824. results.push(this.specularTexture);
  13825. }
  13826. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  13827. results.push(this.bumpTexture);
  13828. }
  13829. return results;
  13830. };
  13831. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  13832. if (this.diffuseTexture) {
  13833. this.diffuseTexture.dispose();
  13834. }
  13835. if (this.ambientTexture) {
  13836. this.ambientTexture.dispose();
  13837. }
  13838. if (this.opacityTexture) {
  13839. this.opacityTexture.dispose();
  13840. }
  13841. if (this.reflectionTexture) {
  13842. this.reflectionTexture.dispose();
  13843. }
  13844. if (this.emissiveTexture) {
  13845. this.emissiveTexture.dispose();
  13846. }
  13847. if (this.specularTexture) {
  13848. this.specularTexture.dispose();
  13849. }
  13850. if (this.bumpTexture) {
  13851. this.bumpTexture.dispose();
  13852. }
  13853. _super.prototype.dispose.call(this, forceDisposeEffect);
  13854. };
  13855. StandardMaterial.prototype.clone = function (name) {
  13856. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  13857. // Base material
  13858. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  13859. newStandardMaterial.alpha = this.alpha;
  13860. newStandardMaterial.fillMode = this.fillMode;
  13861. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  13862. // Standard material
  13863. if (this.diffuseTexture && this.diffuseTexture.clone) {
  13864. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  13865. }
  13866. if (this.ambientTexture && this.ambientTexture.clone) {
  13867. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  13868. }
  13869. if (this.opacityTexture && this.opacityTexture.clone) {
  13870. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  13871. }
  13872. if (this.reflectionTexture && this.reflectionTexture.clone) {
  13873. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  13874. }
  13875. if (this.emissiveTexture && this.emissiveTexture.clone) {
  13876. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  13877. }
  13878. if (this.specularTexture && this.specularTexture.clone) {
  13879. newStandardMaterial.specularTexture = this.specularTexture.clone();
  13880. }
  13881. if (this.bumpTexture && this.bumpTexture.clone) {
  13882. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  13883. }
  13884. newStandardMaterial.ambientColor = this.ambientColor.clone();
  13885. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  13886. newStandardMaterial.specularColor = this.specularColor.clone();
  13887. newStandardMaterial.specularPower = this.specularPower;
  13888. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  13889. return newStandardMaterial;
  13890. };
  13891. // Statics
  13892. // Flags used to enable or disable a type of texture for all Standard Materials
  13893. StandardMaterial.DiffuseTextureEnabled = true;
  13894. StandardMaterial.AmbientTextureEnabled = true;
  13895. StandardMaterial.OpacityTextureEnabled = true;
  13896. StandardMaterial.ReflectionTextureEnabled = true;
  13897. StandardMaterial.EmissiveTextureEnabled = true;
  13898. StandardMaterial.SpecularTextureEnabled = true;
  13899. StandardMaterial.BumpTextureEnabled = true;
  13900. StandardMaterial.FresnelEnabled = true;
  13901. return StandardMaterial;
  13902. })(BABYLON.Material);
  13903. BABYLON.StandardMaterial = StandardMaterial;
  13904. })(BABYLON || (BABYLON = {}));
  13905. //# sourceMappingURL=babylon.standardMaterial.js.map
  13906. var BABYLON;
  13907. (function (BABYLON) {
  13908. var MultiMaterial = (function (_super) {
  13909. __extends(MultiMaterial, _super);
  13910. function MultiMaterial(name, scene) {
  13911. _super.call(this, name, scene, true);
  13912. this.subMaterials = new Array();
  13913. scene.multiMaterials.push(this);
  13914. }
  13915. // Properties
  13916. MultiMaterial.prototype.getSubMaterial = function (index) {
  13917. if (index < 0 || index >= this.subMaterials.length) {
  13918. return this.getScene().defaultMaterial;
  13919. }
  13920. return this.subMaterials[index];
  13921. };
  13922. // Methods
  13923. MultiMaterial.prototype.isReady = function (mesh) {
  13924. for (var index = 0; index < this.subMaterials.length; index++) {
  13925. var subMaterial = this.subMaterials[index];
  13926. if (subMaterial) {
  13927. if (!this.subMaterials[index].isReady(mesh)) {
  13928. return false;
  13929. }
  13930. }
  13931. }
  13932. return true;
  13933. };
  13934. return MultiMaterial;
  13935. })(BABYLON.Material);
  13936. BABYLON.MultiMaterial = MultiMaterial;
  13937. })(BABYLON || (BABYLON = {}));
  13938. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  13939. (function (BABYLON) {
  13940. var Database = (function () {
  13941. function Database(urlToScene, callbackManifestChecked) {
  13942. // Handling various flavors of prefixed version of IndexedDB
  13943. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  13944. this.callbackManifestChecked = callbackManifestChecked;
  13945. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  13946. this.db = null;
  13947. this.enableSceneOffline = false;
  13948. this.enableTexturesOffline = false;
  13949. this.manifestVersionFound = 0;
  13950. this.mustUpdateRessources = false;
  13951. this.hasReachedQuota = false;
  13952. this.checkManifestFile();
  13953. }
  13954. Database.prototype.checkManifestFile = function () {
  13955. var _this = this;
  13956. function noManifestFile() {
  13957. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  13958. that.enableSceneOffline = false;
  13959. that.enableTexturesOffline = false;
  13960. that.callbackManifestChecked(false);
  13961. }
  13962. var that = this;
  13963. var manifestURL = this.currentSceneUrl + ".manifest";
  13964. var xhr = new XMLHttpRequest();
  13965. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  13966. xhr.open("GET", manifestURLTimeStamped, true);
  13967. xhr.addEventListener("load", function () {
  13968. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13969. try {
  13970. var manifestFile = JSON.parse(xhr.response);
  13971. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  13972. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  13973. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  13974. _this.manifestVersionFound = manifestFile.version;
  13975. }
  13976. if (_this.callbackManifestChecked) {
  13977. _this.callbackManifestChecked(true);
  13978. }
  13979. }
  13980. catch (ex) {
  13981. noManifestFile();
  13982. }
  13983. }
  13984. else {
  13985. noManifestFile();
  13986. }
  13987. }, false);
  13988. xhr.addEventListener("error", function (event) {
  13989. noManifestFile();
  13990. }, false);
  13991. try {
  13992. xhr.send();
  13993. }
  13994. catch (ex) {
  13995. BABYLON.Tools.Error("Error on XHR send request.");
  13996. that.callbackManifestChecked(false);
  13997. }
  13998. };
  13999. Database.prototype.openAsync = function (successCallback, errorCallback) {
  14000. var _this = this;
  14001. function handleError() {
  14002. that.isSupported = false;
  14003. if (errorCallback)
  14004. errorCallback();
  14005. }
  14006. var that = this;
  14007. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  14008. // Your browser doesn't support IndexedDB
  14009. this.isSupported = false;
  14010. if (errorCallback)
  14011. errorCallback();
  14012. }
  14013. else {
  14014. // If the DB hasn't been opened or created yet
  14015. if (!this.db) {
  14016. this.hasReachedQuota = false;
  14017. this.isSupported = true;
  14018. var request = this.idbFactory.open("babylonjs", 1);
  14019. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  14020. request.onerror = function (event) {
  14021. handleError();
  14022. };
  14023. // executes when a version change transaction cannot complete due to other active transactions
  14024. request.onblocked = function (event) {
  14025. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  14026. handleError();
  14027. };
  14028. // DB has been opened successfully
  14029. request.onsuccess = function (event) {
  14030. _this.db = request.result;
  14031. successCallback();
  14032. };
  14033. // Initialization of the DB. Creating Scenes & Textures stores
  14034. request.onupgradeneeded = function (event) {
  14035. _this.db = (event.target).result;
  14036. try {
  14037. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  14038. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  14039. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  14040. }
  14041. catch (ex) {
  14042. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  14043. handleError();
  14044. }
  14045. };
  14046. }
  14047. else {
  14048. if (successCallback)
  14049. successCallback();
  14050. }
  14051. }
  14052. };
  14053. Database.prototype.loadImageFromDB = function (url, image) {
  14054. var _this = this;
  14055. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  14056. var saveAndLoadImage = function () {
  14057. if (!_this.hasReachedQuota && _this.db !== null) {
  14058. // the texture is not yet in the DB, let's try to save it
  14059. _this._saveImageIntoDBAsync(completeURL, image);
  14060. }
  14061. else {
  14062. image.src = url;
  14063. }
  14064. };
  14065. if (!this.mustUpdateRessources) {
  14066. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14067. }
  14068. else {
  14069. saveAndLoadImage();
  14070. }
  14071. };
  14072. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14073. if (this.isSupported && this.db !== null) {
  14074. var texture;
  14075. var transaction = this.db.transaction(["textures"]);
  14076. transaction.onabort = function (event) {
  14077. image.src = url;
  14078. };
  14079. transaction.oncomplete = function (event) {
  14080. var blobTextureURL;
  14081. if (texture) {
  14082. var URL = window.URL || window.webkitURL;
  14083. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14084. image.onerror = function () {
  14085. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14086. image.src = url;
  14087. };
  14088. image.src = blobTextureURL;
  14089. }
  14090. else {
  14091. notInDBCallback();
  14092. }
  14093. };
  14094. var getRequest = transaction.objectStore("textures").get(url);
  14095. getRequest.onsuccess = function (event) {
  14096. texture = (event.target).result;
  14097. };
  14098. getRequest.onerror = function (event) {
  14099. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14100. image.src = url;
  14101. };
  14102. }
  14103. else {
  14104. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14105. image.src = url;
  14106. }
  14107. };
  14108. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14109. var _this = this;
  14110. if (this.isSupported) {
  14111. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14112. var generateBlobUrl = function () {
  14113. var blobTextureURL;
  14114. if (blob) {
  14115. var URL = window.URL || window.webkitURL;
  14116. try {
  14117. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14118. }
  14119. catch (ex) {
  14120. blobTextureURL = URL.createObjectURL(blob);
  14121. }
  14122. }
  14123. image.src = blobTextureURL;
  14124. };
  14125. if (BABYLON.Database.isUASupportingBlobStorage) {
  14126. var xhr = new XMLHttpRequest(), blob;
  14127. xhr.open("GET", url, true);
  14128. xhr.responseType = "blob";
  14129. xhr.addEventListener("load", function () {
  14130. if (xhr.status === 200) {
  14131. // Blob as response (XHR2)
  14132. blob = xhr.response;
  14133. var transaction = _this.db.transaction(["textures"], "readwrite");
  14134. // the transaction could abort because of a QuotaExceededError error
  14135. transaction.onabort = function (event) {
  14136. try {
  14137. if (event.srcElement.error.name === "QuotaExceededError") {
  14138. this.hasReachedQuota = true;
  14139. }
  14140. }
  14141. catch (ex) {
  14142. }
  14143. generateBlobUrl();
  14144. };
  14145. transaction.oncomplete = function (event) {
  14146. generateBlobUrl();
  14147. };
  14148. var newTexture = { textureUrl: url, data: blob };
  14149. try {
  14150. // Put the blob into the dabase
  14151. var addRequest = transaction.objectStore("textures").put(newTexture);
  14152. addRequest.onsuccess = function (event) {
  14153. };
  14154. addRequest.onerror = function (event) {
  14155. generateBlobUrl();
  14156. };
  14157. }
  14158. catch (ex) {
  14159. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14160. if (ex.code === 25) {
  14161. BABYLON.Database.isUASupportingBlobStorage = false;
  14162. }
  14163. image.src = url;
  14164. }
  14165. }
  14166. else {
  14167. image.src = url;
  14168. }
  14169. }, false);
  14170. xhr.addEventListener("error", function (event) {
  14171. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14172. image.src = url;
  14173. }, false);
  14174. xhr.send();
  14175. }
  14176. else {
  14177. image.src = url;
  14178. }
  14179. }
  14180. else {
  14181. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14182. image.src = url;
  14183. }
  14184. };
  14185. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14186. var _this = this;
  14187. var updateVersion = function (event) {
  14188. // the version is not yet in the DB or we need to update it
  14189. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14190. };
  14191. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14192. };
  14193. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14194. var _this = this;
  14195. if (this.isSupported) {
  14196. var version;
  14197. try {
  14198. var transaction = this.db.transaction(["versions"]);
  14199. transaction.oncomplete = function (event) {
  14200. if (version) {
  14201. // If the version in the JSON file is > than the version in DB
  14202. if (_this.manifestVersionFound > version.data) {
  14203. _this.mustUpdateRessources = true;
  14204. updateInDBCallback();
  14205. }
  14206. else {
  14207. callback(version.data);
  14208. }
  14209. }
  14210. else {
  14211. _this.mustUpdateRessources = true;
  14212. updateInDBCallback();
  14213. }
  14214. };
  14215. transaction.onabort = function (event) {
  14216. callback(-1);
  14217. };
  14218. var getRequest = transaction.objectStore("versions").get(url);
  14219. getRequest.onsuccess = function (event) {
  14220. version = (event.target).result;
  14221. };
  14222. getRequest.onerror = function (event) {
  14223. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14224. callback(-1);
  14225. };
  14226. }
  14227. catch (ex) {
  14228. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14229. callback(-1);
  14230. }
  14231. }
  14232. else {
  14233. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14234. callback(-1);
  14235. }
  14236. };
  14237. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14238. var _this = this;
  14239. if (this.isSupported && !this.hasReachedQuota) {
  14240. try {
  14241. // Open a transaction to the database
  14242. var transaction = this.db.transaction(["versions"], "readwrite");
  14243. // the transaction could abort because of a QuotaExceededError error
  14244. transaction.onabort = function (event) {
  14245. try {
  14246. if (event.srcElement.error.name === "QuotaExceededError") {
  14247. _this.hasReachedQuota = true;
  14248. }
  14249. }
  14250. catch (ex) {
  14251. }
  14252. callback(-1);
  14253. };
  14254. transaction.oncomplete = function (event) {
  14255. callback(_this.manifestVersionFound);
  14256. };
  14257. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14258. // Put the scene into the database
  14259. var addRequest = transaction.objectStore("versions").put(newVersion);
  14260. addRequest.onsuccess = function (event) {
  14261. };
  14262. addRequest.onerror = function (event) {
  14263. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14264. };
  14265. }
  14266. catch (ex) {
  14267. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14268. callback(-1);
  14269. }
  14270. }
  14271. else {
  14272. callback(-1);
  14273. }
  14274. };
  14275. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  14276. var _this = this;
  14277. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  14278. var saveAndLoadFile = function (event) {
  14279. // the scene is not yet in the DB, let's try to save it
  14280. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  14281. };
  14282. this._checkVersionFromDB(completeUrl, function (version) {
  14283. if (version !== -1) {
  14284. if (!_this.mustUpdateRessources) {
  14285. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  14286. }
  14287. else {
  14288. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  14289. }
  14290. }
  14291. else {
  14292. errorCallback();
  14293. }
  14294. });
  14295. };
  14296. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  14297. if (this.isSupported) {
  14298. var targetStore;
  14299. if (url.indexOf(".babylon") !== -1) {
  14300. targetStore = "scenes";
  14301. }
  14302. else {
  14303. targetStore = "textures";
  14304. }
  14305. var file;
  14306. var transaction = this.db.transaction([targetStore]);
  14307. transaction.oncomplete = function (event) {
  14308. if (file) {
  14309. callback(file.data);
  14310. }
  14311. else {
  14312. notInDBCallback();
  14313. }
  14314. };
  14315. transaction.onabort = function (event) {
  14316. notInDBCallback();
  14317. };
  14318. var getRequest = transaction.objectStore(targetStore).get(url);
  14319. getRequest.onsuccess = function (event) {
  14320. file = (event.target).result;
  14321. };
  14322. getRequest.onerror = function (event) {
  14323. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  14324. notInDBCallback();
  14325. };
  14326. }
  14327. else {
  14328. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14329. callback();
  14330. }
  14331. };
  14332. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  14333. var _this = this;
  14334. if (this.isSupported) {
  14335. var targetStore;
  14336. if (url.indexOf(".babylon") !== -1) {
  14337. targetStore = "scenes";
  14338. }
  14339. else {
  14340. targetStore = "textures";
  14341. }
  14342. // Create XHR
  14343. var xhr = new XMLHttpRequest(), fileData;
  14344. xhr.open("GET", url, true);
  14345. if (useArrayBuffer) {
  14346. xhr.responseType = "arraybuffer";
  14347. }
  14348. xhr.onprogress = progressCallback;
  14349. xhr.addEventListener("load", function () {
  14350. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  14351. // Blob as response (XHR2)
  14352. //fileData = xhr.responseText;
  14353. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  14354. if (!_this.hasReachedQuota) {
  14355. // Open a transaction to the database
  14356. var transaction = _this.db.transaction([targetStore], "readwrite");
  14357. // the transaction could abort because of a QuotaExceededError error
  14358. transaction.onabort = function (event) {
  14359. try {
  14360. if (event.srcElement.error.name === "QuotaExceededError") {
  14361. this.hasReachedQuota = true;
  14362. }
  14363. }
  14364. catch (ex) {
  14365. }
  14366. callback(fileData);
  14367. };
  14368. transaction.oncomplete = function (event) {
  14369. callback(fileData);
  14370. };
  14371. var newFile;
  14372. if (targetStore === "scenes") {
  14373. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  14374. }
  14375. else {
  14376. newFile = { textureUrl: url, data: fileData };
  14377. }
  14378. try {
  14379. // Put the scene into the database
  14380. var addRequest = transaction.objectStore(targetStore).put(newFile);
  14381. addRequest.onsuccess = function (event) {
  14382. };
  14383. addRequest.onerror = function (event) {
  14384. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  14385. };
  14386. }
  14387. catch (ex) {
  14388. callback(fileData);
  14389. }
  14390. }
  14391. else {
  14392. callback(fileData);
  14393. }
  14394. }
  14395. else {
  14396. callback();
  14397. }
  14398. }, false);
  14399. xhr.addEventListener("error", function (event) {
  14400. BABYLON.Tools.Error("error on XHR request.");
  14401. callback();
  14402. }, false);
  14403. xhr.send();
  14404. }
  14405. else {
  14406. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14407. callback();
  14408. }
  14409. };
  14410. Database.isUASupportingBlobStorage = true;
  14411. Database.parseURL = function (url) {
  14412. var a = document.createElement('a');
  14413. a.href = url;
  14414. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  14415. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  14416. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  14417. return absLocation;
  14418. };
  14419. Database.ReturnFullUrlLocation = function (url) {
  14420. if (url.indexOf("http:/") === -1) {
  14421. return (BABYLON.Database.parseURL(window.location.href) + url);
  14422. }
  14423. else {
  14424. return url;
  14425. }
  14426. };
  14427. return Database;
  14428. })();
  14429. BABYLON.Database = Database;
  14430. })(BABYLON || (BABYLON = {}));
  14431. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  14432. (function (BABYLON) {
  14433. var SpriteManager = (function () {
  14434. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  14435. this.name = name;
  14436. this.cellSize = cellSize;
  14437. this.sprites = new Array();
  14438. this.renderingGroupId = 0;
  14439. this.fogEnabled = true;
  14440. this._vertexDeclaration = [3, 4, 4, 4];
  14441. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  14442. this._capacity = capacity;
  14443. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  14444. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14445. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14446. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  14447. this._scene = scene;
  14448. this._scene.spriteManagers.push(this);
  14449. // VBO
  14450. this._vertexDeclaration = [3, 4, 4, 4];
  14451. this._vertexStrideSize = 15 * 4;
  14452. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14453. var indices = [];
  14454. var index = 0;
  14455. for (var count = 0; count < capacity; count++) {
  14456. indices.push(index);
  14457. indices.push(index + 1);
  14458. indices.push(index + 2);
  14459. indices.push(index);
  14460. indices.push(index + 2);
  14461. indices.push(index + 3);
  14462. index += 4;
  14463. }
  14464. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14465. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14466. // Effects
  14467. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  14468. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  14469. }
  14470. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  14471. var arrayOffset = index * 15;
  14472. if (offsetX == 0)
  14473. offsetX = this._epsilon;
  14474. else if (offsetX == 1)
  14475. offsetX = 1 - this._epsilon;
  14476. if (offsetY == 0)
  14477. offsetY = this._epsilon;
  14478. else if (offsetY == 1)
  14479. offsetY = 1 - this._epsilon;
  14480. this._vertices[arrayOffset] = sprite.position.x;
  14481. this._vertices[arrayOffset + 1] = sprite.position.y;
  14482. this._vertices[arrayOffset + 2] = sprite.position.z;
  14483. this._vertices[arrayOffset + 3] = sprite.angle;
  14484. this._vertices[arrayOffset + 4] = sprite.size;
  14485. this._vertices[arrayOffset + 5] = offsetX;
  14486. this._vertices[arrayOffset + 6] = offsetY;
  14487. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  14488. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  14489. var offset = (sprite.cellIndex / rowSize) >> 0;
  14490. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  14491. this._vertices[arrayOffset + 10] = offset;
  14492. // Color
  14493. this._vertices[arrayOffset + 11] = sprite.color.r;
  14494. this._vertices[arrayOffset + 12] = sprite.color.g;
  14495. this._vertices[arrayOffset + 13] = sprite.color.b;
  14496. this._vertices[arrayOffset + 14] = sprite.color.a;
  14497. };
  14498. SpriteManager.prototype.render = function () {
  14499. // Check
  14500. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  14501. return;
  14502. var engine = this._scene.getEngine();
  14503. var baseSize = this._spriteTexture.getBaseSize();
  14504. // Sprites
  14505. var deltaTime = engine.getDeltaTime();
  14506. var max = Math.min(this._capacity, this.sprites.length);
  14507. var rowSize = baseSize.width / this.cellSize;
  14508. var offset = 0;
  14509. for (var index = 0; index < max; index++) {
  14510. var sprite = this.sprites[index];
  14511. if (!sprite) {
  14512. continue;
  14513. }
  14514. sprite._animate(deltaTime);
  14515. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  14516. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  14517. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  14518. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  14519. }
  14520. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14521. // Render
  14522. var effect = this._effectBase;
  14523. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14524. effect = this._effectFog;
  14525. }
  14526. engine.enableEffect(effect);
  14527. var viewMatrix = this._scene.getViewMatrix();
  14528. effect.setTexture("diffuseSampler", this._spriteTexture);
  14529. effect.setMatrix("view", viewMatrix);
  14530. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14531. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  14532. // Fog
  14533. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14534. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  14535. effect.setColor3("vFogColor", this._scene.fogColor);
  14536. }
  14537. // VBOs
  14538. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14539. // Draw order
  14540. effect.setBool("alphaTest", true);
  14541. engine.setColorWrite(false);
  14542. engine.draw(true, 0, max * 6);
  14543. engine.setColorWrite(true);
  14544. effect.setBool("alphaTest", false);
  14545. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14546. engine.draw(true, 0, max * 6);
  14547. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14548. };
  14549. SpriteManager.prototype.dispose = function () {
  14550. if (this._vertexBuffer) {
  14551. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14552. this._vertexBuffer = null;
  14553. }
  14554. if (this._indexBuffer) {
  14555. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14556. this._indexBuffer = null;
  14557. }
  14558. if (this._spriteTexture) {
  14559. this._spriteTexture.dispose();
  14560. this._spriteTexture = null;
  14561. }
  14562. // Remove from scene
  14563. var index = this._scene.spriteManagers.indexOf(this);
  14564. this._scene.spriteManagers.splice(index, 1);
  14565. // Callback
  14566. if (this.onDispose) {
  14567. this.onDispose();
  14568. }
  14569. };
  14570. return SpriteManager;
  14571. })();
  14572. BABYLON.SpriteManager = SpriteManager;
  14573. })(BABYLON || (BABYLON = {}));
  14574. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  14575. (function (BABYLON) {
  14576. var Sprite = (function () {
  14577. function Sprite(name, manager) {
  14578. this.name = name;
  14579. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14580. this.size = 1.0;
  14581. this.angle = 0;
  14582. this.cellIndex = 0;
  14583. this.invertU = 0;
  14584. this.invertV = 0;
  14585. this.animations = new Array();
  14586. this._animationStarted = false;
  14587. this._loopAnimation = false;
  14588. this._fromIndex = 0;
  14589. this._toIndex = 0;
  14590. this._delay = 0;
  14591. this._direction = 1;
  14592. this._frameCount = 0;
  14593. this._time = 0;
  14594. this._manager = manager;
  14595. this._manager.sprites.push(this);
  14596. this.position = BABYLON.Vector3.Zero();
  14597. }
  14598. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  14599. this._fromIndex = from;
  14600. this._toIndex = to;
  14601. this._loopAnimation = loop;
  14602. this._delay = delay;
  14603. this._animationStarted = true;
  14604. this._direction = from < to ? 1 : -1;
  14605. this.cellIndex = from;
  14606. this._time = 0;
  14607. };
  14608. Sprite.prototype.stopAnimation = function () {
  14609. this._animationStarted = false;
  14610. };
  14611. Sprite.prototype._animate = function (deltaTime) {
  14612. if (!this._animationStarted)
  14613. return;
  14614. this._time += deltaTime;
  14615. if (this._time > this._delay) {
  14616. this._time = this._time % this._delay;
  14617. this.cellIndex += this._direction;
  14618. if (this.cellIndex == this._toIndex) {
  14619. if (this._loopAnimation) {
  14620. this.cellIndex = this._fromIndex;
  14621. }
  14622. else {
  14623. this._animationStarted = false;
  14624. if (this.disposeWhenFinishedAnimating) {
  14625. this.dispose();
  14626. }
  14627. }
  14628. }
  14629. }
  14630. };
  14631. Sprite.prototype.dispose = function () {
  14632. for (var i = 0; i < this._manager.sprites.length; i++) {
  14633. if (this._manager.sprites[i] == this) {
  14634. this._manager.sprites.splice(i, 1);
  14635. }
  14636. }
  14637. };
  14638. return Sprite;
  14639. })();
  14640. BABYLON.Sprite = Sprite;
  14641. })(BABYLON || (BABYLON = {}));
  14642. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  14643. (function (BABYLON) {
  14644. var Layer = (function () {
  14645. function Layer(name, imgUrl, scene, isBackground, color) {
  14646. this.name = name;
  14647. this._vertexDeclaration = [2];
  14648. this._vertexStrideSize = 2 * 4;
  14649. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  14650. this.isBackground = isBackground === undefined ? true : isBackground;
  14651. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  14652. this._scene = scene;
  14653. this._scene.layers.push(this);
  14654. // VBO
  14655. var vertices = [];
  14656. vertices.push(1, 1);
  14657. vertices.push(-1, 1);
  14658. vertices.push(-1, -1);
  14659. vertices.push(1, -1);
  14660. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14661. // Indices
  14662. var indices = [];
  14663. indices.push(0);
  14664. indices.push(1);
  14665. indices.push(2);
  14666. indices.push(0);
  14667. indices.push(2);
  14668. indices.push(3);
  14669. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14670. // Effects
  14671. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  14672. }
  14673. Layer.prototype.render = function () {
  14674. // Check
  14675. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  14676. return;
  14677. var engine = this._scene.getEngine();
  14678. // Render
  14679. engine.enableEffect(this._effect);
  14680. engine.setState(false);
  14681. // Texture
  14682. this._effect.setTexture("textureSampler", this.texture);
  14683. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  14684. // Color
  14685. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  14686. // VBOs
  14687. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14688. // Draw order
  14689. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14690. engine.draw(true, 0, 6);
  14691. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14692. };
  14693. Layer.prototype.dispose = function () {
  14694. if (this._vertexBuffer) {
  14695. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14696. this._vertexBuffer = null;
  14697. }
  14698. if (this._indexBuffer) {
  14699. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14700. this._indexBuffer = null;
  14701. }
  14702. if (this.texture) {
  14703. this.texture.dispose();
  14704. this.texture = null;
  14705. }
  14706. // Remove from scene
  14707. var index = this._scene.layers.indexOf(this);
  14708. this._scene.layers.splice(index, 1);
  14709. // Callback
  14710. if (this.onDispose) {
  14711. this.onDispose();
  14712. }
  14713. };
  14714. return Layer;
  14715. })();
  14716. BABYLON.Layer = Layer;
  14717. })(BABYLON || (BABYLON = {}));
  14718. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  14719. (function (BABYLON) {
  14720. var Particle = (function () {
  14721. function Particle() {
  14722. this.position = BABYLON.Vector3.Zero();
  14723. this.direction = BABYLON.Vector3.Zero();
  14724. this.color = new BABYLON.Color4(0, 0, 0, 0);
  14725. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  14726. this.lifeTime = 1.0;
  14727. this.age = 0;
  14728. this.size = 0;
  14729. this.angle = 0;
  14730. this.angularSpeed = 0;
  14731. }
  14732. Particle.prototype.copyTo = function (other) {
  14733. other.position.copyFrom(this.position);
  14734. other.direction.copyFrom(this.direction);
  14735. other.color.copyFrom(this.color);
  14736. other.colorStep.copyFrom(this.colorStep);
  14737. other.lifeTime = this.lifeTime;
  14738. other.age = this.age;
  14739. other.size = this.size;
  14740. other.angle = this.angle;
  14741. other.angularSpeed = this.angularSpeed;
  14742. };
  14743. return Particle;
  14744. })();
  14745. BABYLON.Particle = Particle;
  14746. })(BABYLON || (BABYLON = {}));
  14747. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  14748. (function (BABYLON) {
  14749. var randomNumber = function (min, max) {
  14750. if (min === max) {
  14751. return (min);
  14752. }
  14753. var random = Math.random();
  14754. return ((random * (max - min)) + min);
  14755. };
  14756. var ParticleSystem = (function () {
  14757. function ParticleSystem(name, capacity, scene, customEffect) {
  14758. var _this = this;
  14759. this.name = name;
  14760. this.renderingGroupId = 0;
  14761. this.emitter = null;
  14762. this.emitRate = 10;
  14763. this.manualEmitCount = -1;
  14764. this.updateSpeed = 0.01;
  14765. this.targetStopDuration = 0;
  14766. this.disposeOnStop = false;
  14767. this.minEmitPower = 1;
  14768. this.maxEmitPower = 1;
  14769. this.minLifeTime = 1;
  14770. this.maxLifeTime = 1;
  14771. this.minSize = 1;
  14772. this.maxSize = 1;
  14773. this.minAngularSpeed = 0;
  14774. this.maxAngularSpeed = 0;
  14775. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  14776. this.forceDepthWrite = false;
  14777. this.gravity = BABYLON.Vector3.Zero();
  14778. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  14779. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  14780. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  14781. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14782. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14783. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14784. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  14785. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14786. this.particles = new Array();
  14787. this._vertexDeclaration = [3, 4, 4];
  14788. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  14789. this._stockParticles = new Array();
  14790. this._newPartsExcess = 0;
  14791. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  14792. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  14793. this._scaledDirection = BABYLON.Vector3.Zero();
  14794. this._scaledGravity = BABYLON.Vector3.Zero();
  14795. this._currentRenderId = -1;
  14796. this._started = false;
  14797. this._stopped = false;
  14798. this._actualFrame = 0;
  14799. this.id = name;
  14800. this._capacity = capacity;
  14801. this._scene = scene;
  14802. this._customEffect = customEffect;
  14803. scene.particleSystems.push(this);
  14804. // VBO
  14805. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14806. var indices = [];
  14807. var index = 0;
  14808. for (var count = 0; count < capacity; count++) {
  14809. indices.push(index);
  14810. indices.push(index + 1);
  14811. indices.push(index + 2);
  14812. indices.push(index);
  14813. indices.push(index + 2);
  14814. indices.push(index + 3);
  14815. index += 4;
  14816. }
  14817. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14818. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14819. // Default behaviors
  14820. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  14821. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  14822. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  14823. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  14824. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  14825. };
  14826. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  14827. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  14828. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  14829. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  14830. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  14831. };
  14832. this.updateFunction = function (particles) {
  14833. for (var index = 0; index < particles.length; index++) {
  14834. var particle = particles[index];
  14835. particle.age += _this._scaledUpdateSpeed;
  14836. if (particle.age >= particle.lifeTime) {
  14837. _this.recycleParticle(particle);
  14838. index--;
  14839. continue;
  14840. }
  14841. else {
  14842. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  14843. particle.color.addInPlace(_this._scaledColorStep);
  14844. if (particle.color.a < 0)
  14845. particle.color.a = 0;
  14846. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  14847. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  14848. particle.position.addInPlace(_this._scaledDirection);
  14849. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  14850. particle.direction.addInPlace(_this._scaledGravity);
  14851. }
  14852. }
  14853. };
  14854. }
  14855. ParticleSystem.prototype.recycleParticle = function (particle) {
  14856. var lastParticle = this.particles.pop();
  14857. if (lastParticle !== particle) {
  14858. lastParticle.copyTo(particle);
  14859. this._stockParticles.push(lastParticle);
  14860. }
  14861. };
  14862. ParticleSystem.prototype.getCapacity = function () {
  14863. return this._capacity;
  14864. };
  14865. ParticleSystem.prototype.isAlive = function () {
  14866. return this._alive;
  14867. };
  14868. ParticleSystem.prototype.isStarted = function () {
  14869. return this._started;
  14870. };
  14871. ParticleSystem.prototype.start = function () {
  14872. this._started = true;
  14873. this._stopped = false;
  14874. this._actualFrame = 0;
  14875. };
  14876. ParticleSystem.prototype.stop = function () {
  14877. this._stopped = true;
  14878. };
  14879. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  14880. var offset = index * 11;
  14881. this._vertices[offset] = particle.position.x;
  14882. this._vertices[offset + 1] = particle.position.y;
  14883. this._vertices[offset + 2] = particle.position.z;
  14884. this._vertices[offset + 3] = particle.color.r;
  14885. this._vertices[offset + 4] = particle.color.g;
  14886. this._vertices[offset + 5] = particle.color.b;
  14887. this._vertices[offset + 6] = particle.color.a;
  14888. this._vertices[offset + 7] = particle.angle;
  14889. this._vertices[offset + 8] = particle.size;
  14890. this._vertices[offset + 9] = offsetX;
  14891. this._vertices[offset + 10] = offsetY;
  14892. };
  14893. ParticleSystem.prototype._update = function (newParticles) {
  14894. // Update current
  14895. this._alive = this.particles.length > 0;
  14896. this.updateFunction(this.particles);
  14897. // Add new ones
  14898. var worldMatrix;
  14899. if (this.emitter.position) {
  14900. worldMatrix = this.emitter.getWorldMatrix();
  14901. }
  14902. else {
  14903. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  14904. }
  14905. for (var index = 0; index < newParticles; index++) {
  14906. if (this.particles.length === this._capacity) {
  14907. break;
  14908. }
  14909. if (this._stockParticles.length !== 0) {
  14910. var particle = this._stockParticles.pop();
  14911. particle.age = 0;
  14912. }
  14913. else {
  14914. particle = new BABYLON.Particle();
  14915. }
  14916. this.particles.push(particle);
  14917. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  14918. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  14919. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  14920. particle.size = randomNumber(this.minSize, this.maxSize);
  14921. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  14922. this.startPositionFunction(worldMatrix, particle.position);
  14923. var step = randomNumber(0, 1.0);
  14924. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  14925. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  14926. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  14927. }
  14928. };
  14929. ParticleSystem.prototype._getEffect = function () {
  14930. if (this._customEffect) {
  14931. return this._customEffect;
  14932. }
  14933. ;
  14934. var defines = [];
  14935. if (this._scene.clipPlane) {
  14936. defines.push("#define CLIPPLANE");
  14937. }
  14938. // Effect
  14939. var join = defines.join("\n");
  14940. if (this._cachedDefines !== join) {
  14941. this._cachedDefines = join;
  14942. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  14943. }
  14944. return this._effect;
  14945. };
  14946. ParticleSystem.prototype.animate = function () {
  14947. if (!this._started)
  14948. return;
  14949. var effect = this._getEffect();
  14950. // Check
  14951. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  14952. return;
  14953. if (this._currentRenderId === this._scene.getRenderId()) {
  14954. return;
  14955. }
  14956. this._currentRenderId = this._scene.getRenderId();
  14957. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  14958. // determine the number of particles we need to create
  14959. var emitCout;
  14960. if (this.manualEmitCount > -1) {
  14961. emitCout = this.manualEmitCount;
  14962. this.manualEmitCount = 0;
  14963. }
  14964. else {
  14965. emitCout = this.emitRate;
  14966. }
  14967. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  14968. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  14969. if (this._newPartsExcess > 1.0) {
  14970. newParticles += this._newPartsExcess >> 0;
  14971. this._newPartsExcess -= this._newPartsExcess >> 0;
  14972. }
  14973. this._alive = false;
  14974. if (!this._stopped) {
  14975. this._actualFrame += this._scaledUpdateSpeed;
  14976. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  14977. this.stop();
  14978. }
  14979. else {
  14980. newParticles = 0;
  14981. }
  14982. this._update(newParticles);
  14983. // Stopped?
  14984. if (this._stopped) {
  14985. if (!this._alive) {
  14986. this._started = false;
  14987. if (this.disposeOnStop) {
  14988. this._scene._toBeDisposed.push(this);
  14989. }
  14990. }
  14991. }
  14992. // Update VBO
  14993. var offset = 0;
  14994. for (var index = 0; index < this.particles.length; index++) {
  14995. var particle = this.particles[index];
  14996. this._appendParticleVertex(offset++, particle, 0, 0);
  14997. this._appendParticleVertex(offset++, particle, 1, 0);
  14998. this._appendParticleVertex(offset++, particle, 1, 1);
  14999. this._appendParticleVertex(offset++, particle, 0, 1);
  15000. }
  15001. var engine = this._scene.getEngine();
  15002. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15003. };
  15004. ParticleSystem.prototype.render = function () {
  15005. var effect = this._getEffect();
  15006. // Check
  15007. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  15008. return 0;
  15009. var engine = this._scene.getEngine();
  15010. // Render
  15011. engine.enableEffect(effect);
  15012. engine.setState(false);
  15013. var viewMatrix = this._scene.getViewMatrix();
  15014. effect.setTexture("diffuseSampler", this.particleTexture);
  15015. effect.setMatrix("view", viewMatrix);
  15016. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15017. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  15018. if (this._scene.clipPlane) {
  15019. var clipPlane = this._scene.clipPlane;
  15020. var invView = viewMatrix.clone();
  15021. invView.invert();
  15022. effect.setMatrix("invView", invView);
  15023. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15024. }
  15025. // VBOs
  15026. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15027. // Draw order
  15028. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  15029. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15030. }
  15031. else {
  15032. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15033. }
  15034. if (this.forceDepthWrite) {
  15035. engine.setDepthWrite(true);
  15036. }
  15037. engine.draw(true, 0, this.particles.length * 6);
  15038. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15039. return this.particles.length;
  15040. };
  15041. ParticleSystem.prototype.dispose = function () {
  15042. if (this._vertexBuffer) {
  15043. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15044. this._vertexBuffer = null;
  15045. }
  15046. if (this._indexBuffer) {
  15047. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15048. this._indexBuffer = null;
  15049. }
  15050. if (this.particleTexture) {
  15051. this.particleTexture.dispose();
  15052. this.particleTexture = null;
  15053. }
  15054. // Remove from scene
  15055. var index = this._scene.particleSystems.indexOf(this);
  15056. this._scene.particleSystems.splice(index, 1);
  15057. // Callback
  15058. if (this.onDispose) {
  15059. this.onDispose();
  15060. }
  15061. };
  15062. // Clone
  15063. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15064. var result = new ParticleSystem(name, this._capacity, this._scene);
  15065. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15066. if (newEmitter === undefined) {
  15067. newEmitter = this.emitter;
  15068. }
  15069. result.emitter = newEmitter;
  15070. if (this.particleTexture) {
  15071. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15072. }
  15073. result.start();
  15074. return result;
  15075. };
  15076. // Statics
  15077. ParticleSystem.BLENDMODE_ONEONE = 0;
  15078. ParticleSystem.BLENDMODE_STANDARD = 1;
  15079. return ParticleSystem;
  15080. })();
  15081. BABYLON.ParticleSystem = ParticleSystem;
  15082. })(BABYLON || (BABYLON = {}));
  15083. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15084. (function (BABYLON) {
  15085. var Animation = (function () {
  15086. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15087. this.name = name;
  15088. this.targetProperty = targetProperty;
  15089. this.framePerSecond = framePerSecond;
  15090. this.dataType = dataType;
  15091. this.loopMode = loopMode;
  15092. this._offsetsCache = {};
  15093. this._highLimitsCache = {};
  15094. this._stopped = false;
  15095. this.targetPropertyPath = targetProperty.split(".");
  15096. this.dataType = dataType;
  15097. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15098. }
  15099. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15100. var dataType = undefined;
  15101. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15102. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15103. }
  15104. else if (from instanceof BABYLON.Quaternion) {
  15105. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15106. }
  15107. else if (from instanceof BABYLON.Vector3) {
  15108. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15109. }
  15110. else if (from instanceof BABYLON.Vector2) {
  15111. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15112. }
  15113. else if (from instanceof BABYLON.Color3) {
  15114. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15115. }
  15116. if (dataType == undefined) {
  15117. return;
  15118. }
  15119. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15120. var keys = [];
  15121. keys.push({ frame: 0, value: from });
  15122. keys.push({ frame: totalFrame, value: to });
  15123. animation.setKeys(keys);
  15124. mesh.animations.push(animation);
  15125. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15126. };
  15127. // Methods
  15128. Animation.prototype.isStopped = function () {
  15129. return this._stopped;
  15130. };
  15131. Animation.prototype.getKeys = function () {
  15132. return this._keys;
  15133. };
  15134. Animation.prototype.getEasingFunction = function () {
  15135. return this._easingFunction;
  15136. };
  15137. Animation.prototype.setEasingFunction = function (easingFunction) {
  15138. this._easingFunction = easingFunction;
  15139. };
  15140. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15141. return startValue + (endValue - startValue) * gradient;
  15142. };
  15143. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15144. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15145. };
  15146. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15147. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15148. };
  15149. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15150. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15151. };
  15152. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15153. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15154. };
  15155. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15156. var startScale = new BABYLON.Vector3(0, 0, 0);
  15157. var startRotation = new BABYLON.Quaternion();
  15158. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15159. startValue.decompose(startScale, startRotation, startTranslation);
  15160. var endScale = new BABYLON.Vector3(0, 0, 0);
  15161. var endRotation = new BABYLON.Quaternion();
  15162. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15163. endValue.decompose(endScale, endRotation, endTranslation);
  15164. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15165. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15166. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15167. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15168. return result;
  15169. };
  15170. Animation.prototype.clone = function () {
  15171. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15172. clone.setKeys(this._keys);
  15173. return clone;
  15174. };
  15175. Animation.prototype.setKeys = function (values) {
  15176. this._keys = values.slice(0);
  15177. this._offsetsCache = {};
  15178. this._highLimitsCache = {};
  15179. };
  15180. Animation.prototype._getKeyValue = function (value) {
  15181. if (typeof value === "function") {
  15182. return value();
  15183. }
  15184. return value;
  15185. };
  15186. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15187. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15188. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15189. }
  15190. this.currentFrame = currentFrame;
  15191. for (var key = 0; key < this._keys.length; key++) {
  15192. // for each frame, we need the key just before the frame superior
  15193. if (this._keys[key + 1].frame >= currentFrame) {
  15194. var startValue = this._getKeyValue(this._keys[key].value);
  15195. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15196. // gradient : percent of currentFrame between the frame inf and the frame sup
  15197. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15198. // check for easingFunction and correction of gradient
  15199. if (this._easingFunction != null) {
  15200. gradient = this._easingFunction.ease(gradient);
  15201. }
  15202. switch (this.dataType) {
  15203. case Animation.ANIMATIONTYPE_FLOAT:
  15204. switch (loopMode) {
  15205. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15206. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15207. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15208. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15209. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15210. }
  15211. break;
  15212. case Animation.ANIMATIONTYPE_QUATERNION:
  15213. var quaternion = null;
  15214. switch (loopMode) {
  15215. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15216. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15217. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15218. break;
  15219. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15220. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15221. break;
  15222. }
  15223. return quaternion;
  15224. case Animation.ANIMATIONTYPE_VECTOR3:
  15225. switch (loopMode) {
  15226. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15227. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15228. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15229. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15230. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15231. }
  15232. case Animation.ANIMATIONTYPE_VECTOR2:
  15233. switch (loopMode) {
  15234. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15235. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15236. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15237. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15238. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15239. }
  15240. case Animation.ANIMATIONTYPE_COLOR3:
  15241. switch (loopMode) {
  15242. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15243. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15244. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15245. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15246. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15247. }
  15248. case Animation.ANIMATIONTYPE_MATRIX:
  15249. switch (loopMode) {
  15250. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15251. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15252. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15253. return startValue;
  15254. }
  15255. default:
  15256. break;
  15257. }
  15258. break;
  15259. }
  15260. }
  15261. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15262. };
  15263. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15264. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15265. this._stopped = true;
  15266. return false;
  15267. }
  15268. var returnValue = true;
  15269. // Adding a start key at frame 0 if missing
  15270. if (this._keys[0].frame !== 0) {
  15271. var newKey = { frame: 0, value: this._keys[0].value };
  15272. this._keys.splice(0, 0, newKey);
  15273. }
  15274. // Check limits
  15275. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  15276. from = this._keys[0].frame;
  15277. }
  15278. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  15279. to = this._keys[this._keys.length - 1].frame;
  15280. }
  15281. // Compute ratio
  15282. var range = to - from;
  15283. var offsetValue;
  15284. // ratio represents the frame delta between from and to
  15285. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  15286. var highLimitValue = 0;
  15287. if (ratio > range && !loop) {
  15288. returnValue = false;
  15289. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  15290. }
  15291. else {
  15292. // Get max value if required
  15293. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  15294. var keyOffset = to.toString() + from.toString();
  15295. if (!this._offsetsCache[keyOffset]) {
  15296. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15297. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15298. switch (this.dataType) {
  15299. case Animation.ANIMATIONTYPE_FLOAT:
  15300. this._offsetsCache[keyOffset] = toValue - fromValue;
  15301. break;
  15302. case Animation.ANIMATIONTYPE_QUATERNION:
  15303. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15304. break;
  15305. case Animation.ANIMATIONTYPE_VECTOR3:
  15306. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15307. case Animation.ANIMATIONTYPE_VECTOR2:
  15308. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15309. case Animation.ANIMATIONTYPE_COLOR3:
  15310. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15311. default:
  15312. break;
  15313. }
  15314. this._highLimitsCache[keyOffset] = toValue;
  15315. }
  15316. highLimitValue = this._highLimitsCache[keyOffset];
  15317. offsetValue = this._offsetsCache[keyOffset];
  15318. }
  15319. }
  15320. if (offsetValue === undefined) {
  15321. switch (this.dataType) {
  15322. case Animation.ANIMATIONTYPE_FLOAT:
  15323. offsetValue = 0;
  15324. break;
  15325. case Animation.ANIMATIONTYPE_QUATERNION:
  15326. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  15327. break;
  15328. case Animation.ANIMATIONTYPE_VECTOR3:
  15329. offsetValue = BABYLON.Vector3.Zero();
  15330. break;
  15331. case Animation.ANIMATIONTYPE_VECTOR2:
  15332. offsetValue = BABYLON.Vector2.Zero();
  15333. break;
  15334. case Animation.ANIMATIONTYPE_COLOR3:
  15335. offsetValue = BABYLON.Color3.Black();
  15336. }
  15337. }
  15338. // Compute value
  15339. var repeatCount = (ratio / range) >> 0;
  15340. var currentFrame = returnValue ? from + ratio % range : to;
  15341. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  15342. // Set value
  15343. if (this.targetPropertyPath.length > 1) {
  15344. var property = this._target[this.targetPropertyPath[0]];
  15345. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  15346. property = property[this.targetPropertyPath[index]];
  15347. }
  15348. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  15349. }
  15350. else {
  15351. this._target[this.targetPropertyPath[0]] = currentValue;
  15352. }
  15353. if (this._target.markAsDirty) {
  15354. this._target.markAsDirty(this.targetProperty);
  15355. }
  15356. if (!returnValue) {
  15357. this._stopped = true;
  15358. }
  15359. return returnValue;
  15360. };
  15361. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  15362. get: function () {
  15363. return Animation._ANIMATIONTYPE_FLOAT;
  15364. },
  15365. enumerable: true,
  15366. configurable: true
  15367. });
  15368. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  15369. get: function () {
  15370. return Animation._ANIMATIONTYPE_VECTOR3;
  15371. },
  15372. enumerable: true,
  15373. configurable: true
  15374. });
  15375. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  15376. get: function () {
  15377. return Animation._ANIMATIONTYPE_VECTOR2;
  15378. },
  15379. enumerable: true,
  15380. configurable: true
  15381. });
  15382. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  15383. get: function () {
  15384. return Animation._ANIMATIONTYPE_QUATERNION;
  15385. },
  15386. enumerable: true,
  15387. configurable: true
  15388. });
  15389. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  15390. get: function () {
  15391. return Animation._ANIMATIONTYPE_MATRIX;
  15392. },
  15393. enumerable: true,
  15394. configurable: true
  15395. });
  15396. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  15397. get: function () {
  15398. return Animation._ANIMATIONTYPE_COLOR3;
  15399. },
  15400. enumerable: true,
  15401. configurable: true
  15402. });
  15403. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  15404. get: function () {
  15405. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  15406. },
  15407. enumerable: true,
  15408. configurable: true
  15409. });
  15410. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  15411. get: function () {
  15412. return Animation._ANIMATIONLOOPMODE_CYCLE;
  15413. },
  15414. enumerable: true,
  15415. configurable: true
  15416. });
  15417. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  15418. get: function () {
  15419. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  15420. },
  15421. enumerable: true,
  15422. configurable: true
  15423. });
  15424. // Statics
  15425. Animation._ANIMATIONTYPE_FLOAT = 0;
  15426. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  15427. Animation._ANIMATIONTYPE_QUATERNION = 2;
  15428. Animation._ANIMATIONTYPE_MATRIX = 3;
  15429. Animation._ANIMATIONTYPE_COLOR3 = 4;
  15430. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  15431. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  15432. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  15433. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  15434. return Animation;
  15435. })();
  15436. BABYLON.Animation = Animation;
  15437. })(BABYLON || (BABYLON = {}));
  15438. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  15439. (function (BABYLON) {
  15440. var Animatable = (function () {
  15441. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  15442. if (fromFrame === void 0) { fromFrame = 0; }
  15443. if (toFrame === void 0) { toFrame = 100; }
  15444. if (loopAnimation === void 0) { loopAnimation = false; }
  15445. if (speedRatio === void 0) { speedRatio = 1.0; }
  15446. this.target = target;
  15447. this.fromFrame = fromFrame;
  15448. this.toFrame = toFrame;
  15449. this.loopAnimation = loopAnimation;
  15450. this.speedRatio = speedRatio;
  15451. this.onAnimationEnd = onAnimationEnd;
  15452. this._animations = new Array();
  15453. this._paused = false;
  15454. this.animationStarted = false;
  15455. if (animations) {
  15456. this.appendAnimations(target, animations);
  15457. }
  15458. this._scene = scene;
  15459. scene._activeAnimatables.push(this);
  15460. }
  15461. // Methods
  15462. Animatable.prototype.appendAnimations = function (target, animations) {
  15463. for (var index = 0; index < animations.length; index++) {
  15464. var animation = animations[index];
  15465. animation._target = target;
  15466. this._animations.push(animation);
  15467. }
  15468. };
  15469. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  15470. var animations = this._animations;
  15471. for (var index = 0; index < animations.length; index++) {
  15472. if (animations[index].targetProperty === property) {
  15473. return animations[index];
  15474. }
  15475. }
  15476. return null;
  15477. };
  15478. Animatable.prototype.pause = function () {
  15479. if (this._paused) {
  15480. return;
  15481. }
  15482. this._paused = true;
  15483. };
  15484. Animatable.prototype.restart = function () {
  15485. this._paused = false;
  15486. };
  15487. Animatable.prototype.stop = function () {
  15488. var index = this._scene._activeAnimatables.indexOf(this);
  15489. if (index > -1) {
  15490. this._scene._activeAnimatables.splice(index, 1);
  15491. }
  15492. if (this.onAnimationEnd) {
  15493. this.onAnimationEnd();
  15494. }
  15495. };
  15496. Animatable.prototype._animate = function (delay) {
  15497. if (this._paused) {
  15498. if (!this._pausedDelay) {
  15499. this._pausedDelay = delay;
  15500. }
  15501. return true;
  15502. }
  15503. if (!this._localDelayOffset) {
  15504. this._localDelayOffset = delay;
  15505. }
  15506. else if (this._pausedDelay) {
  15507. this._localDelayOffset += delay - this._pausedDelay;
  15508. this._pausedDelay = null;
  15509. }
  15510. // Animating
  15511. var running = false;
  15512. var animations = this._animations;
  15513. for (var index = 0; index < animations.length; index++) {
  15514. var animation = animations[index];
  15515. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  15516. running = running || isRunning;
  15517. }
  15518. if (!running && this.onAnimationEnd) {
  15519. this.onAnimationEnd();
  15520. }
  15521. return running;
  15522. };
  15523. return Animatable;
  15524. })();
  15525. BABYLON.Animatable = Animatable;
  15526. })(BABYLON || (BABYLON = {}));
  15527. //# sourceMappingURL=babylon.animatable.js.map
  15528. var BABYLON;
  15529. (function (BABYLON) {
  15530. var EasingFunction = (function () {
  15531. function EasingFunction() {
  15532. // Properties
  15533. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  15534. }
  15535. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  15536. get: function () {
  15537. return EasingFunction._EASINGMODE_EASEIN;
  15538. },
  15539. enumerable: true,
  15540. configurable: true
  15541. });
  15542. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  15543. get: function () {
  15544. return EasingFunction._EASINGMODE_EASEOUT;
  15545. },
  15546. enumerable: true,
  15547. configurable: true
  15548. });
  15549. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  15550. get: function () {
  15551. return EasingFunction._EASINGMODE_EASEINOUT;
  15552. },
  15553. enumerable: true,
  15554. configurable: true
  15555. });
  15556. EasingFunction.prototype.setEasingMode = function (easingMode) {
  15557. var n = Math.min(Math.max(easingMode, 0), 2);
  15558. this._easingMode = n;
  15559. };
  15560. EasingFunction.prototype.getEasingMode = function () {
  15561. return this._easingMode;
  15562. };
  15563. EasingFunction.prototype.easeInCore = function (gradient) {
  15564. throw new Error('You must implement this method');
  15565. };
  15566. EasingFunction.prototype.ease = function (gradient) {
  15567. switch (this._easingMode) {
  15568. case EasingFunction.EASINGMODE_EASEIN:
  15569. return this.easeInCore(gradient);
  15570. case EasingFunction.EASINGMODE_EASEOUT:
  15571. return (1 - this.easeInCore(1 - gradient));
  15572. }
  15573. if (gradient >= 0.5) {
  15574. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  15575. }
  15576. return (this.easeInCore(gradient * 2) * 0.5);
  15577. };
  15578. //Statics
  15579. EasingFunction._EASINGMODE_EASEIN = 0;
  15580. EasingFunction._EASINGMODE_EASEOUT = 1;
  15581. EasingFunction._EASINGMODE_EASEINOUT = 2;
  15582. return EasingFunction;
  15583. })();
  15584. BABYLON.EasingFunction = EasingFunction;
  15585. var CircleEase = (function (_super) {
  15586. __extends(CircleEase, _super);
  15587. function CircleEase() {
  15588. _super.apply(this, arguments);
  15589. }
  15590. CircleEase.prototype.easeInCore = function (gradient) {
  15591. gradient = Math.max(0, Math.min(1, gradient));
  15592. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  15593. };
  15594. return CircleEase;
  15595. })(EasingFunction);
  15596. BABYLON.CircleEase = CircleEase;
  15597. var BackEase = (function (_super) {
  15598. __extends(BackEase, _super);
  15599. function BackEase(amplitude) {
  15600. if (amplitude === void 0) { amplitude = 1; }
  15601. _super.call(this);
  15602. this.amplitude = amplitude;
  15603. }
  15604. BackEase.prototype.easeInCore = function (gradient) {
  15605. var num = Math.max(0, this.amplitude);
  15606. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  15607. };
  15608. return BackEase;
  15609. })(EasingFunction);
  15610. BABYLON.BackEase = BackEase;
  15611. var BounceEase = (function (_super) {
  15612. __extends(BounceEase, _super);
  15613. function BounceEase(bounces, bounciness) {
  15614. if (bounces === void 0) { bounces = 3; }
  15615. if (bounciness === void 0) { bounciness = 2; }
  15616. _super.call(this);
  15617. this.bounces = bounces;
  15618. this.bounciness = bounciness;
  15619. }
  15620. BounceEase.prototype.easeInCore = function (gradient) {
  15621. var y = Math.max(0.0, this.bounces);
  15622. var bounciness = this.bounciness;
  15623. if (bounciness <= 1.0) {
  15624. bounciness = 1.001;
  15625. }
  15626. var num9 = Math.pow(bounciness, y);
  15627. var num5 = 1.0 - bounciness;
  15628. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  15629. var num15 = gradient * num4;
  15630. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  15631. var num3 = Math.floor(num65);
  15632. var num13 = num3 + 1.0;
  15633. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  15634. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  15635. var num7 = (num8 + num12) * 0.5;
  15636. var num6 = gradient - num7;
  15637. var num2 = num7 - num8;
  15638. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  15639. };
  15640. return BounceEase;
  15641. })(EasingFunction);
  15642. BABYLON.BounceEase = BounceEase;
  15643. var CubicEase = (function (_super) {
  15644. __extends(CubicEase, _super);
  15645. function CubicEase() {
  15646. _super.apply(this, arguments);
  15647. }
  15648. CubicEase.prototype.easeInCore = function (gradient) {
  15649. return (gradient * gradient * gradient);
  15650. };
  15651. return CubicEase;
  15652. })(EasingFunction);
  15653. BABYLON.CubicEase = CubicEase;
  15654. var ElasticEase = (function (_super) {
  15655. __extends(ElasticEase, _super);
  15656. function ElasticEase(oscillations, springiness) {
  15657. if (oscillations === void 0) { oscillations = 3; }
  15658. if (springiness === void 0) { springiness = 3; }
  15659. _super.call(this);
  15660. this.oscillations = oscillations;
  15661. this.springiness = springiness;
  15662. }
  15663. ElasticEase.prototype.easeInCore = function (gradient) {
  15664. var num2;
  15665. var num3 = Math.max(0.0, this.oscillations);
  15666. var num = Math.max(0.0, this.springiness);
  15667. if (num == 0) {
  15668. num2 = gradient;
  15669. }
  15670. else {
  15671. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  15672. }
  15673. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  15674. };
  15675. return ElasticEase;
  15676. })(EasingFunction);
  15677. BABYLON.ElasticEase = ElasticEase;
  15678. var ExponentialEase = (function (_super) {
  15679. __extends(ExponentialEase, _super);
  15680. function ExponentialEase(exponent) {
  15681. if (exponent === void 0) { exponent = 2; }
  15682. _super.call(this);
  15683. this.exponent = exponent;
  15684. }
  15685. ExponentialEase.prototype.easeInCore = function (gradient) {
  15686. if (this.exponent <= 0) {
  15687. return gradient;
  15688. }
  15689. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  15690. };
  15691. return ExponentialEase;
  15692. })(EasingFunction);
  15693. BABYLON.ExponentialEase = ExponentialEase;
  15694. var PowerEase = (function (_super) {
  15695. __extends(PowerEase, _super);
  15696. function PowerEase(power) {
  15697. if (power === void 0) { power = 2; }
  15698. _super.call(this);
  15699. this.power = power;
  15700. }
  15701. PowerEase.prototype.easeInCore = function (gradient) {
  15702. var y = Math.max(0.0, this.power);
  15703. return Math.pow(gradient, y);
  15704. };
  15705. return PowerEase;
  15706. })(EasingFunction);
  15707. BABYLON.PowerEase = PowerEase;
  15708. var QuadraticEase = (function (_super) {
  15709. __extends(QuadraticEase, _super);
  15710. function QuadraticEase() {
  15711. _super.apply(this, arguments);
  15712. }
  15713. QuadraticEase.prototype.easeInCore = function (gradient) {
  15714. return (gradient * gradient);
  15715. };
  15716. return QuadraticEase;
  15717. })(EasingFunction);
  15718. BABYLON.QuadraticEase = QuadraticEase;
  15719. var QuarticEase = (function (_super) {
  15720. __extends(QuarticEase, _super);
  15721. function QuarticEase() {
  15722. _super.apply(this, arguments);
  15723. }
  15724. QuarticEase.prototype.easeInCore = function (gradient) {
  15725. return (gradient * gradient * gradient * gradient);
  15726. };
  15727. return QuarticEase;
  15728. })(EasingFunction);
  15729. BABYLON.QuarticEase = QuarticEase;
  15730. var QuinticEase = (function (_super) {
  15731. __extends(QuinticEase, _super);
  15732. function QuinticEase() {
  15733. _super.apply(this, arguments);
  15734. }
  15735. QuinticEase.prototype.easeInCore = function (gradient) {
  15736. return (gradient * gradient * gradient * gradient * gradient);
  15737. };
  15738. return QuinticEase;
  15739. })(EasingFunction);
  15740. BABYLON.QuinticEase = QuinticEase;
  15741. var SineEase = (function (_super) {
  15742. __extends(SineEase, _super);
  15743. function SineEase() {
  15744. _super.apply(this, arguments);
  15745. }
  15746. SineEase.prototype.easeInCore = function (gradient) {
  15747. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  15748. };
  15749. return SineEase;
  15750. })(EasingFunction);
  15751. BABYLON.SineEase = SineEase;
  15752. var BezierCurveEase = (function (_super) {
  15753. __extends(BezierCurveEase, _super);
  15754. function BezierCurveEase(x1, y1, x2, y2) {
  15755. if (x1 === void 0) { x1 = 0; }
  15756. if (y1 === void 0) { y1 = 0; }
  15757. if (x2 === void 0) { x2 = 1; }
  15758. if (y2 === void 0) { y2 = 1; }
  15759. _super.call(this);
  15760. this.x1 = x1;
  15761. this.y1 = y1;
  15762. this.x2 = x2;
  15763. this.y2 = y2;
  15764. }
  15765. BezierCurveEase.prototype.easeInCore = function (gradient) {
  15766. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  15767. };
  15768. return BezierCurveEase;
  15769. })(EasingFunction);
  15770. BABYLON.BezierCurveEase = BezierCurveEase;
  15771. })(BABYLON || (BABYLON = {}));
  15772. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  15773. (function (BABYLON) {
  15774. var Octree = (function () {
  15775. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  15776. if (maxDepth === void 0) { maxDepth = 2; }
  15777. this.maxDepth = maxDepth;
  15778. this.dynamicContent = new Array();
  15779. this._maxBlockCapacity = maxBlockCapacity || 64;
  15780. this._selectionContent = new BABYLON.SmartArray(1024);
  15781. this._creationFunc = creationFunc;
  15782. }
  15783. // Methods
  15784. Octree.prototype.update = function (worldMin, worldMax, entries) {
  15785. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  15786. };
  15787. Octree.prototype.addMesh = function (entry) {
  15788. for (var index = 0; index < this.blocks.length; index++) {
  15789. var block = this.blocks[index];
  15790. block.addEntry(entry);
  15791. }
  15792. };
  15793. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  15794. this._selectionContent.reset();
  15795. for (var index = 0; index < this.blocks.length; index++) {
  15796. var block = this.blocks[index];
  15797. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  15798. }
  15799. if (allowDuplicate) {
  15800. this._selectionContent.concat(this.dynamicContent);
  15801. }
  15802. else {
  15803. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15804. }
  15805. return this._selectionContent;
  15806. };
  15807. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  15808. this._selectionContent.reset();
  15809. for (var index = 0; index < this.blocks.length; index++) {
  15810. var block = this.blocks[index];
  15811. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  15812. }
  15813. if (allowDuplicate) {
  15814. this._selectionContent.concat(this.dynamicContent);
  15815. }
  15816. else {
  15817. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15818. }
  15819. return this._selectionContent;
  15820. };
  15821. Octree.prototype.intersectsRay = function (ray) {
  15822. this._selectionContent.reset();
  15823. for (var index = 0; index < this.blocks.length; index++) {
  15824. var block = this.blocks[index];
  15825. block.intersectsRay(ray, this._selectionContent);
  15826. }
  15827. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15828. return this._selectionContent;
  15829. };
  15830. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  15831. target.blocks = new Array();
  15832. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  15833. for (var x = 0; x < 2; x++) {
  15834. for (var y = 0; y < 2; y++) {
  15835. for (var z = 0; z < 2; z++) {
  15836. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  15837. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  15838. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  15839. block.addEntries(entries);
  15840. target.blocks.push(block);
  15841. }
  15842. }
  15843. }
  15844. };
  15845. Octree.CreationFuncForMeshes = function (entry, block) {
  15846. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15847. block.entries.push(entry);
  15848. }
  15849. };
  15850. Octree.CreationFuncForSubMeshes = function (entry, block) {
  15851. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15852. block.entries.push(entry);
  15853. }
  15854. };
  15855. return Octree;
  15856. })();
  15857. BABYLON.Octree = Octree;
  15858. })(BABYLON || (BABYLON = {}));
  15859. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  15860. (function (BABYLON) {
  15861. var OctreeBlock = (function () {
  15862. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  15863. this.entries = new Array();
  15864. this._boundingVectors = new Array();
  15865. this._capacity = capacity;
  15866. this._depth = depth;
  15867. this._maxDepth = maxDepth;
  15868. this._creationFunc = creationFunc;
  15869. this._minPoint = minPoint;
  15870. this._maxPoint = maxPoint;
  15871. this._boundingVectors.push(minPoint.clone());
  15872. this._boundingVectors.push(maxPoint.clone());
  15873. this._boundingVectors.push(minPoint.clone());
  15874. this._boundingVectors[2].x = maxPoint.x;
  15875. this._boundingVectors.push(minPoint.clone());
  15876. this._boundingVectors[3].y = maxPoint.y;
  15877. this._boundingVectors.push(minPoint.clone());
  15878. this._boundingVectors[4].z = maxPoint.z;
  15879. this._boundingVectors.push(maxPoint.clone());
  15880. this._boundingVectors[5].z = minPoint.z;
  15881. this._boundingVectors.push(maxPoint.clone());
  15882. this._boundingVectors[6].x = minPoint.x;
  15883. this._boundingVectors.push(maxPoint.clone());
  15884. this._boundingVectors[7].y = minPoint.y;
  15885. }
  15886. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  15887. // Property
  15888. get: function () {
  15889. return this._capacity;
  15890. },
  15891. enumerable: true,
  15892. configurable: true
  15893. });
  15894. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  15895. get: function () {
  15896. return this._minPoint;
  15897. },
  15898. enumerable: true,
  15899. configurable: true
  15900. });
  15901. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  15902. get: function () {
  15903. return this._maxPoint;
  15904. },
  15905. enumerable: true,
  15906. configurable: true
  15907. });
  15908. // Methods
  15909. OctreeBlock.prototype.addEntry = function (entry) {
  15910. if (this.blocks) {
  15911. for (var index = 0; index < this.blocks.length; index++) {
  15912. var block = this.blocks[index];
  15913. block.addEntry(entry);
  15914. }
  15915. return;
  15916. }
  15917. this._creationFunc(entry, this);
  15918. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  15919. this.createInnerBlocks();
  15920. }
  15921. };
  15922. OctreeBlock.prototype.addEntries = function (entries) {
  15923. for (var index = 0; index < entries.length; index++) {
  15924. var mesh = entries[index];
  15925. this.addEntry(mesh);
  15926. }
  15927. };
  15928. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  15929. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  15930. if (this.blocks) {
  15931. for (var index = 0; index < this.blocks.length; index++) {
  15932. var block = this.blocks[index];
  15933. block.select(frustumPlanes, selection, allowDuplicate);
  15934. }
  15935. return;
  15936. }
  15937. if (allowDuplicate) {
  15938. selection.concat(this.entries);
  15939. }
  15940. else {
  15941. selection.concatWithNoDuplicate(this.entries);
  15942. }
  15943. }
  15944. };
  15945. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  15946. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  15947. if (this.blocks) {
  15948. for (var index = 0; index < this.blocks.length; index++) {
  15949. var block = this.blocks[index];
  15950. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  15951. }
  15952. return;
  15953. }
  15954. if (allowDuplicate) {
  15955. selection.concat(this.entries);
  15956. }
  15957. else {
  15958. selection.concatWithNoDuplicate(this.entries);
  15959. }
  15960. }
  15961. };
  15962. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  15963. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  15964. if (this.blocks) {
  15965. for (var index = 0; index < this.blocks.length; index++) {
  15966. var block = this.blocks[index];
  15967. block.intersectsRay(ray, selection);
  15968. }
  15969. return;
  15970. }
  15971. selection.concatWithNoDuplicate(this.entries);
  15972. }
  15973. };
  15974. OctreeBlock.prototype.createInnerBlocks = function () {
  15975. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  15976. };
  15977. return OctreeBlock;
  15978. })();
  15979. BABYLON.OctreeBlock = OctreeBlock;
  15980. })(BABYLON || (BABYLON = {}));
  15981. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  15982. (function (BABYLON) {
  15983. var Bone = (function () {
  15984. function Bone(name, skeleton, parentBone, matrix) {
  15985. this.name = name;
  15986. this.children = new Array();
  15987. this.animations = new Array();
  15988. this._worldTransform = new BABYLON.Matrix();
  15989. this._absoluteTransform = new BABYLON.Matrix();
  15990. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  15991. this._skeleton = skeleton;
  15992. this._matrix = matrix;
  15993. this._baseMatrix = matrix;
  15994. skeleton.bones.push(this);
  15995. if (parentBone) {
  15996. this._parent = parentBone;
  15997. parentBone.children.push(this);
  15998. }
  15999. else {
  16000. this._parent = null;
  16001. }
  16002. this._updateDifferenceMatrix();
  16003. }
  16004. // Members
  16005. Bone.prototype.getParent = function () {
  16006. return this._parent;
  16007. };
  16008. Bone.prototype.getLocalMatrix = function () {
  16009. return this._matrix;
  16010. };
  16011. Bone.prototype.getBaseMatrix = function () {
  16012. return this._baseMatrix;
  16013. };
  16014. Bone.prototype.getWorldMatrix = function () {
  16015. return this._worldTransform;
  16016. };
  16017. Bone.prototype.getInvertedAbsoluteTransform = function () {
  16018. return this._invertedAbsoluteTransform;
  16019. };
  16020. Bone.prototype.getAbsoluteMatrix = function () {
  16021. var matrix = this._matrix.clone();
  16022. var parent = this._parent;
  16023. while (parent) {
  16024. matrix = matrix.multiply(parent.getLocalMatrix());
  16025. parent = parent.getParent();
  16026. }
  16027. return matrix;
  16028. };
  16029. // Methods
  16030. Bone.prototype.updateMatrix = function (matrix) {
  16031. this._matrix = matrix;
  16032. this._skeleton._markAsDirty();
  16033. this._updateDifferenceMatrix();
  16034. };
  16035. Bone.prototype._updateDifferenceMatrix = function () {
  16036. if (this._parent) {
  16037. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  16038. }
  16039. else {
  16040. this._absoluteTransform.copyFrom(this._matrix);
  16041. }
  16042. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  16043. for (var index = 0; index < this.children.length; index++) {
  16044. this.children[index]._updateDifferenceMatrix();
  16045. }
  16046. };
  16047. Bone.prototype.markAsDirty = function () {
  16048. this._skeleton._markAsDirty();
  16049. };
  16050. return Bone;
  16051. })();
  16052. BABYLON.Bone = Bone;
  16053. })(BABYLON || (BABYLON = {}));
  16054. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16055. (function (BABYLON) {
  16056. var Skeleton = (function () {
  16057. function Skeleton(name, id, scene) {
  16058. this.name = name;
  16059. this.id = id;
  16060. this.bones = new Array();
  16061. this._isDirty = true;
  16062. this._identity = BABYLON.Matrix.Identity();
  16063. this.bones = [];
  16064. this._scene = scene;
  16065. scene.skeletons.push(this);
  16066. }
  16067. // Members
  16068. Skeleton.prototype.getTransformMatrices = function () {
  16069. return this._transformMatrices;
  16070. };
  16071. // Methods
  16072. Skeleton.prototype._markAsDirty = function () {
  16073. this._isDirty = true;
  16074. };
  16075. Skeleton.prototype.prepare = function () {
  16076. if (!this._isDirty) {
  16077. return;
  16078. }
  16079. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16080. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16081. }
  16082. for (var index = 0; index < this.bones.length; index++) {
  16083. var bone = this.bones[index];
  16084. var parentBone = bone.getParent();
  16085. if (parentBone) {
  16086. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16087. }
  16088. else {
  16089. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16090. }
  16091. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16092. }
  16093. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16094. this._isDirty = false;
  16095. };
  16096. Skeleton.prototype.getAnimatables = function () {
  16097. if (!this._animatables || this._animatables.length != this.bones.length) {
  16098. this._animatables = [];
  16099. for (var index = 0; index < this.bones.length; index++) {
  16100. this._animatables.push(this.bones[index]);
  16101. }
  16102. }
  16103. return this._animatables;
  16104. };
  16105. Skeleton.prototype.clone = function (name, id) {
  16106. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  16107. for (var index = 0; index < this.bones.length; index++) {
  16108. var source = this.bones[index];
  16109. var parentBone = null;
  16110. if (source.getParent()) {
  16111. var parentIndex = this.bones.indexOf(source.getParent());
  16112. parentBone = result.bones[parentIndex];
  16113. }
  16114. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16115. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16116. }
  16117. return result;
  16118. };
  16119. return Skeleton;
  16120. })();
  16121. BABYLON.Skeleton = Skeleton;
  16122. })(BABYLON || (BABYLON = {}));
  16123. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16124. (function (BABYLON) {
  16125. var PostProcess = (function () {
  16126. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  16127. this.name = name;
  16128. this.width = -1;
  16129. this.height = -1;
  16130. this._reusable = false;
  16131. this._textures = new BABYLON.SmartArray(2);
  16132. this._currentRenderTextureInd = 0;
  16133. if (camera != null) {
  16134. this._camera = camera;
  16135. this._scene = camera.getScene();
  16136. camera.attachPostProcess(this);
  16137. this._engine = this._scene.getEngine();
  16138. }
  16139. else {
  16140. this._engine = engine;
  16141. }
  16142. this._renderRatio = ratio;
  16143. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16144. this._reusable = reusable || false;
  16145. samplers = samplers || [];
  16146. samplers.push("textureSampler");
  16147. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  16148. }
  16149. PostProcess.prototype.isReusable = function () {
  16150. return this._reusable;
  16151. };
  16152. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16153. camera = camera || this._camera;
  16154. var scene = camera.getScene();
  16155. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16156. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16157. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16158. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16159. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16160. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16161. if (this._textures.length > 0) {
  16162. for (var i = 0; i < this._textures.length; i++) {
  16163. this._engine._releaseTexture(this._textures.data[i]);
  16164. }
  16165. this._textures.reset();
  16166. }
  16167. this.width = desiredWidth;
  16168. this.height = desiredHeight;
  16169. 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 }));
  16170. if (this._reusable) {
  16171. 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 }));
  16172. }
  16173. if (this.onSizeChanged) {
  16174. this.onSizeChanged();
  16175. }
  16176. }
  16177. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16178. if (this.onActivate) {
  16179. this.onActivate(camera);
  16180. }
  16181. // Clear
  16182. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16183. if (this._reusable) {
  16184. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16185. }
  16186. };
  16187. PostProcess.prototype.apply = function () {
  16188. // Check
  16189. if (!this._effect.isReady())
  16190. return null;
  16191. // States
  16192. this._engine.enableEffect(this._effect);
  16193. this._engine.setState(false);
  16194. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16195. this._engine.setDepthBuffer(false);
  16196. this._engine.setDepthWrite(false);
  16197. // Texture
  16198. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16199. // Parameters
  16200. if (this.onApply) {
  16201. this.onApply(this._effect);
  16202. }
  16203. return this._effect;
  16204. };
  16205. PostProcess.prototype.dispose = function (camera) {
  16206. camera = camera || this._camera;
  16207. if (this._textures.length > 0) {
  16208. for (var i = 0; i < this._textures.length; i++) {
  16209. this._engine._releaseTexture(this._textures.data[i]);
  16210. }
  16211. this._textures.reset();
  16212. }
  16213. camera.detachPostProcess(this);
  16214. var index = camera._postProcesses.indexOf(this);
  16215. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  16216. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  16217. }
  16218. };
  16219. return PostProcess;
  16220. })();
  16221. BABYLON.PostProcess = PostProcess;
  16222. })(BABYLON || (BABYLON = {}));
  16223. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  16224. (function (BABYLON) {
  16225. var PostProcessManager = (function () {
  16226. function PostProcessManager(scene) {
  16227. this._vertexDeclaration = [2];
  16228. this._vertexStrideSize = 2 * 4;
  16229. this._scene = scene;
  16230. // VBO
  16231. var vertices = [];
  16232. vertices.push(1, 1);
  16233. vertices.push(-1, 1);
  16234. vertices.push(-1, -1);
  16235. vertices.push(1, -1);
  16236. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16237. // Indices
  16238. var indices = [];
  16239. indices.push(0);
  16240. indices.push(1);
  16241. indices.push(2);
  16242. indices.push(0);
  16243. indices.push(2);
  16244. indices.push(3);
  16245. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16246. }
  16247. // Methods
  16248. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16249. var postProcesses = this._scene.activeCamera._postProcesses;
  16250. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16251. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16252. return false;
  16253. }
  16254. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16255. return true;
  16256. };
  16257. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  16258. var postProcesses = this._scene.activeCamera._postProcesses;
  16259. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16260. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16261. return;
  16262. }
  16263. var engine = this._scene.getEngine();
  16264. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  16265. if (index < postProcessesTakenIndices.length - 1) {
  16266. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  16267. }
  16268. else {
  16269. if (targetTexture) {
  16270. engine.bindFramebuffer(targetTexture);
  16271. }
  16272. else {
  16273. engine.restoreDefaultFramebuffer();
  16274. }
  16275. }
  16276. if (doNotPresent) {
  16277. break;
  16278. }
  16279. var pp = postProcesses[postProcessesTakenIndices[index]];
  16280. var effect = pp.apply();
  16281. if (effect) {
  16282. if (pp.onBeforeRender) {
  16283. pp.onBeforeRender(effect);
  16284. }
  16285. // VBOs
  16286. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16287. // Draw order
  16288. engine.draw(true, 0, 6);
  16289. }
  16290. }
  16291. // Restore depth buffer
  16292. engine.setDepthBuffer(true);
  16293. engine.setDepthWrite(true);
  16294. };
  16295. PostProcessManager.prototype.dispose = function () {
  16296. if (this._vertexBuffer) {
  16297. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16298. this._vertexBuffer = null;
  16299. }
  16300. if (this._indexBuffer) {
  16301. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16302. this._indexBuffer = null;
  16303. }
  16304. };
  16305. return PostProcessManager;
  16306. })();
  16307. BABYLON.PostProcessManager = PostProcessManager;
  16308. })(BABYLON || (BABYLON = {}));
  16309. //# sourceMappingURL=babylon.postProcessManager.js.map
  16310. var BABYLON;
  16311. (function (BABYLON) {
  16312. var PassPostProcess = (function (_super) {
  16313. __extends(PassPostProcess, _super);
  16314. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16315. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  16316. }
  16317. return PassPostProcess;
  16318. })(BABYLON.PostProcess);
  16319. BABYLON.PassPostProcess = PassPostProcess;
  16320. })(BABYLON || (BABYLON = {}));
  16321. //# sourceMappingURL=babylon.passPostProcess.js.map
  16322. var BABYLON;
  16323. (function (BABYLON) {
  16324. var BlurPostProcess = (function (_super) {
  16325. __extends(BlurPostProcess, _super);
  16326. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  16327. var _this = this;
  16328. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  16329. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  16330. this.direction = direction;
  16331. this.blurWidth = blurWidth;
  16332. this.onApply = function (effect) {
  16333. effect.setFloat2("screenSize", _this.width, _this.height);
  16334. effect.setVector2("direction", _this.direction);
  16335. effect.setFloat("blurWidth", _this.blurWidth);
  16336. };
  16337. }
  16338. return BlurPostProcess;
  16339. })(BABYLON.PostProcess);
  16340. BABYLON.BlurPostProcess = BlurPostProcess;
  16341. })(BABYLON || (BABYLON = {}));
  16342. //# sourceMappingURL=babylon.blurPostProcess.js.map
  16343. var BABYLON;
  16344. (function (BABYLON) {
  16345. var FilterPostProcess = (function (_super) {
  16346. __extends(FilterPostProcess, _super);
  16347. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  16348. var _this = this;
  16349. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  16350. this.kernelMatrix = kernelMatrix;
  16351. this.onApply = function (effect) {
  16352. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  16353. };
  16354. }
  16355. return FilterPostProcess;
  16356. })(BABYLON.PostProcess);
  16357. BABYLON.FilterPostProcess = FilterPostProcess;
  16358. })(BABYLON || (BABYLON = {}));
  16359. //# sourceMappingURL=babylon.filterPostProcess.js.map
  16360. var BABYLON;
  16361. (function (BABYLON) {
  16362. var RefractionPostProcess = (function (_super) {
  16363. __extends(RefractionPostProcess, _super);
  16364. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  16365. var _this = this;
  16366. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  16367. this.color = color;
  16368. this.depth = depth;
  16369. this.colorLevel = colorLevel;
  16370. this.onActivate = function (cam) {
  16371. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  16372. };
  16373. this.onApply = function (effect) {
  16374. effect.setColor3("baseColor", _this.color);
  16375. effect.setFloat("depth", _this.depth);
  16376. effect.setFloat("colorLevel", _this.colorLevel);
  16377. effect.setTexture("refractionSampler", _this._refRexture);
  16378. };
  16379. }
  16380. // Methods
  16381. RefractionPostProcess.prototype.dispose = function (camera) {
  16382. if (this._refRexture) {
  16383. this._refRexture.dispose();
  16384. }
  16385. _super.prototype.dispose.call(this, camera);
  16386. };
  16387. return RefractionPostProcess;
  16388. })(BABYLON.PostProcess);
  16389. BABYLON.RefractionPostProcess = RefractionPostProcess;
  16390. })(BABYLON || (BABYLON = {}));
  16391. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  16392. var BABYLON;
  16393. (function (BABYLON) {
  16394. var BlackAndWhitePostProcess = (function (_super) {
  16395. __extends(BlackAndWhitePostProcess, _super);
  16396. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16397. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  16398. }
  16399. return BlackAndWhitePostProcess;
  16400. })(BABYLON.PostProcess);
  16401. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  16402. })(BABYLON || (BABYLON = {}));
  16403. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  16404. var BABYLON;
  16405. (function (BABYLON) {
  16406. var ConvolutionPostProcess = (function (_super) {
  16407. __extends(ConvolutionPostProcess, _super);
  16408. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  16409. var _this = this;
  16410. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  16411. this.kernel = kernel;
  16412. this.onApply = function (effect) {
  16413. effect.setFloat2("screenSize", _this.width, _this.height);
  16414. effect.setArray("kernel", _this.kernel);
  16415. };
  16416. }
  16417. // Statics
  16418. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  16419. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  16420. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  16421. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  16422. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  16423. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  16424. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  16425. return ConvolutionPostProcess;
  16426. })(BABYLON.PostProcess);
  16427. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  16428. })(BABYLON || (BABYLON = {}));
  16429. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  16430. var BABYLON;
  16431. (function (BABYLON) {
  16432. var FxaaPostProcess = (function (_super) {
  16433. __extends(FxaaPostProcess, _super);
  16434. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16435. var _this = this;
  16436. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  16437. this.onSizeChanged = function () {
  16438. _this.texelWidth = 1.0 / _this.width;
  16439. _this.texelHeight = 1.0 / _this.height;
  16440. };
  16441. this.onApply = function (effect) {
  16442. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  16443. };
  16444. }
  16445. return FxaaPostProcess;
  16446. })(BABYLON.PostProcess);
  16447. BABYLON.FxaaPostProcess = FxaaPostProcess;
  16448. })(BABYLON || (BABYLON = {}));
  16449. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  16450. (function (BABYLON) {
  16451. var LensFlare = (function () {
  16452. function LensFlare(size, position, color, imgUrl, system) {
  16453. this.size = size;
  16454. this.position = position;
  16455. this.dispose = function () {
  16456. if (this.texture) {
  16457. this.texture.dispose();
  16458. }
  16459. // Remove from scene
  16460. var index = this._system.lensFlares.indexOf(this);
  16461. this._system.lensFlares.splice(index, 1);
  16462. };
  16463. this.color = color || new BABYLON.Color3(1, 1, 1);
  16464. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  16465. this._system = system;
  16466. system.lensFlares.push(this);
  16467. }
  16468. return LensFlare;
  16469. })();
  16470. BABYLON.LensFlare = LensFlare;
  16471. })(BABYLON || (BABYLON = {}));
  16472. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  16473. (function (BABYLON) {
  16474. var LensFlareSystem = (function () {
  16475. function LensFlareSystem(name, emitter, scene) {
  16476. this.name = name;
  16477. this.lensFlares = new Array();
  16478. this.borderLimit = 300;
  16479. this._vertexDeclaration = [2];
  16480. this._vertexStrideSize = 2 * 4;
  16481. this._isEnabled = true;
  16482. this._scene = scene;
  16483. this._emitter = emitter;
  16484. scene.lensFlareSystems.push(this);
  16485. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  16486. // VBO
  16487. var vertices = [];
  16488. vertices.push(1, 1);
  16489. vertices.push(-1, 1);
  16490. vertices.push(-1, -1);
  16491. vertices.push(1, -1);
  16492. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16493. // Indices
  16494. var indices = [];
  16495. indices.push(0);
  16496. indices.push(1);
  16497. indices.push(2);
  16498. indices.push(0);
  16499. indices.push(2);
  16500. indices.push(3);
  16501. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16502. // Effects
  16503. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  16504. }
  16505. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  16506. get: function () {
  16507. return this._isEnabled;
  16508. },
  16509. set: function (value) {
  16510. this._isEnabled = value;
  16511. },
  16512. enumerable: true,
  16513. configurable: true
  16514. });
  16515. LensFlareSystem.prototype.getScene = function () {
  16516. return this._scene;
  16517. };
  16518. LensFlareSystem.prototype.getEmitter = function () {
  16519. return this._emitter;
  16520. };
  16521. LensFlareSystem.prototype.getEmitterPosition = function () {
  16522. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  16523. };
  16524. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  16525. var position = this.getEmitterPosition();
  16526. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  16527. this._positionX = position.x;
  16528. this._positionY = position.y;
  16529. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  16530. if (position.z > 0) {
  16531. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  16532. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  16533. return true;
  16534. }
  16535. }
  16536. return false;
  16537. };
  16538. LensFlareSystem.prototype._isVisible = function () {
  16539. if (!this._isEnabled) {
  16540. return false;
  16541. }
  16542. var emitterPosition = this.getEmitterPosition();
  16543. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  16544. var distance = direction.length();
  16545. direction.normalize();
  16546. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  16547. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  16548. return !pickInfo.hit || pickInfo.distance > distance;
  16549. };
  16550. LensFlareSystem.prototype.render = function () {
  16551. if (!this._effect.isReady())
  16552. return false;
  16553. var engine = this._scene.getEngine();
  16554. var viewport = this._scene.activeCamera.viewport;
  16555. var globalViewport = viewport.toGlobal(engine);
  16556. // Position
  16557. if (!this.computeEffectivePosition(globalViewport)) {
  16558. return false;
  16559. }
  16560. // Visibility
  16561. if (!this._isVisible()) {
  16562. return false;
  16563. }
  16564. // Intensity
  16565. var awayX;
  16566. var awayY;
  16567. if (this._positionX < this.borderLimit + globalViewport.x) {
  16568. awayX = this.borderLimit + globalViewport.x - this._positionX;
  16569. }
  16570. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  16571. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  16572. }
  16573. else {
  16574. awayX = 0;
  16575. }
  16576. if (this._positionY < this.borderLimit + globalViewport.y) {
  16577. awayY = this.borderLimit + globalViewport.y - this._positionY;
  16578. }
  16579. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  16580. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  16581. }
  16582. else {
  16583. awayY = 0;
  16584. }
  16585. var away = (awayX > awayY) ? awayX : awayY;
  16586. if (away > this.borderLimit) {
  16587. away = this.borderLimit;
  16588. }
  16589. var intensity = 1.0 - (away / this.borderLimit);
  16590. if (intensity < 0) {
  16591. return false;
  16592. }
  16593. if (intensity > 1.0) {
  16594. intensity = 1.0;
  16595. }
  16596. // Position
  16597. var centerX = globalViewport.x + globalViewport.width / 2;
  16598. var centerY = globalViewport.y + globalViewport.height / 2;
  16599. var distX = centerX - this._positionX;
  16600. var distY = centerY - this._positionY;
  16601. // Effects
  16602. engine.enableEffect(this._effect);
  16603. engine.setState(false);
  16604. engine.setDepthBuffer(false);
  16605. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16606. // VBOs
  16607. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16608. for (var index = 0; index < this.lensFlares.length; index++) {
  16609. var flare = this.lensFlares[index];
  16610. var x = centerX - (distX * flare.position);
  16611. var y = centerY - (distY * flare.position);
  16612. var cw = flare.size;
  16613. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  16614. var cx = 2 * (x / globalViewport.width) - 1.0;
  16615. var cy = 1.0 - 2 * (y / globalViewport.height);
  16616. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  16617. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  16618. // Texture
  16619. this._effect.setTexture("textureSampler", flare.texture);
  16620. // Color
  16621. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  16622. // Draw order
  16623. engine.draw(true, 0, 6);
  16624. }
  16625. engine.setDepthBuffer(true);
  16626. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16627. return true;
  16628. };
  16629. LensFlareSystem.prototype.dispose = function () {
  16630. if (this._vertexBuffer) {
  16631. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16632. this._vertexBuffer = null;
  16633. }
  16634. if (this._indexBuffer) {
  16635. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16636. this._indexBuffer = null;
  16637. }
  16638. while (this.lensFlares.length) {
  16639. this.lensFlares[0].dispose();
  16640. }
  16641. // Remove from scene
  16642. var index = this._scene.lensFlareSystems.indexOf(this);
  16643. this._scene.lensFlareSystems.splice(index, 1);
  16644. };
  16645. return LensFlareSystem;
  16646. })();
  16647. BABYLON.LensFlareSystem = LensFlareSystem;
  16648. })(BABYLON || (BABYLON = {}));
  16649. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  16650. (function (BABYLON) {
  16651. var IntersectionInfo = (function () {
  16652. function IntersectionInfo(bu, bv, distance) {
  16653. this.bu = bu;
  16654. this.bv = bv;
  16655. this.distance = distance;
  16656. this.faceId = 0;
  16657. }
  16658. return IntersectionInfo;
  16659. })();
  16660. BABYLON.IntersectionInfo = IntersectionInfo;
  16661. var PickingInfo = (function () {
  16662. function PickingInfo() {
  16663. this.hit = false;
  16664. this.distance = 0;
  16665. this.pickedPoint = null;
  16666. this.pickedMesh = null;
  16667. this.bu = 0;
  16668. this.bv = 0;
  16669. this.faceId = -1;
  16670. }
  16671. // Methods
  16672. PickingInfo.prototype.getNormal = function () {
  16673. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16674. return null;
  16675. }
  16676. var indices = this.pickedMesh.getIndices();
  16677. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16678. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  16679. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  16680. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  16681. normal0 = normal0.scale(this.bu);
  16682. normal1 = normal1.scale(this.bv);
  16683. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  16684. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  16685. };
  16686. PickingInfo.prototype.getTextureCoordinates = function () {
  16687. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16688. return null;
  16689. }
  16690. var indices = this.pickedMesh.getIndices();
  16691. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16692. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  16693. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  16694. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  16695. uv0 = uv0.scale(this.bu);
  16696. uv1 = uv1.scale(this.bv);
  16697. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  16698. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  16699. };
  16700. return PickingInfo;
  16701. })();
  16702. BABYLON.PickingInfo = PickingInfo;
  16703. })(BABYLON || (BABYLON = {}));
  16704. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  16705. (function (BABYLON) {
  16706. var FilesInput = (function () {
  16707. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  16708. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  16709. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  16710. this.engine = p_engine;
  16711. this.canvas = p_canvas;
  16712. this.currentScene = p_scene;
  16713. this.sceneLoadedCallback = p_sceneLoadedCallback;
  16714. this.progressCallback = p_progressCallback;
  16715. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  16716. this.textureLoadingCallback = p_textureLoadingCallback;
  16717. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  16718. }
  16719. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  16720. var _this = this;
  16721. if (p_elementToMonitor) {
  16722. this.elementToMonitor = p_elementToMonitor;
  16723. this.elementToMonitor.addEventListener("dragenter", function (e) {
  16724. _this.drag(e);
  16725. }, false);
  16726. this.elementToMonitor.addEventListener("dragover", function (e) {
  16727. _this.drag(e);
  16728. }, false);
  16729. this.elementToMonitor.addEventListener("drop", function (e) {
  16730. _this.drop(e);
  16731. }, false);
  16732. }
  16733. };
  16734. FilesInput.prototype.renderFunction = function () {
  16735. if (this.additionnalRenderLoopLogicCallback) {
  16736. this.additionnalRenderLoopLogicCallback();
  16737. }
  16738. if (this.currentScene) {
  16739. if (this.textureLoadingCallback) {
  16740. var remaining = this.currentScene.getWaitingItemsCount();
  16741. if (remaining > 0) {
  16742. this.textureLoadingCallback(remaining);
  16743. }
  16744. }
  16745. this.currentScene.render();
  16746. }
  16747. };
  16748. FilesInput.prototype.drag = function (e) {
  16749. e.stopPropagation();
  16750. e.preventDefault();
  16751. };
  16752. FilesInput.prototype.drop = function (eventDrop) {
  16753. eventDrop.stopPropagation();
  16754. eventDrop.preventDefault();
  16755. this.loadFiles(eventDrop);
  16756. };
  16757. FilesInput.prototype.loadFiles = function (event) {
  16758. var _this = this;
  16759. var that = this;
  16760. if (this.startingProcessingFilesCallback)
  16761. this.startingProcessingFilesCallback();
  16762. var sceneFileToLoad;
  16763. var filesToLoad;
  16764. // Handling data transfer via drag'n'drop
  16765. if (event && event.dataTransfer && event.dataTransfer.files) {
  16766. filesToLoad = event.dataTransfer.files;
  16767. }
  16768. // Handling files from input files
  16769. if (event && event.target && event.target.files) {
  16770. filesToLoad = event.target.files;
  16771. }
  16772. if (filesToLoad && filesToLoad.length > 0) {
  16773. for (var i = 0; i < filesToLoad.length; i++) {
  16774. switch (filesToLoad[i].type) {
  16775. case "image/jpeg":
  16776. case "image/png":
  16777. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  16778. break;
  16779. case "image/targa":
  16780. case "image/vnd.ms-dds":
  16781. case "audio/wav":
  16782. case "audio/x-wav":
  16783. case "audio/mpeg":
  16784. case "audio/mpeg3":
  16785. case "audio/x-mpeg-3":
  16786. case "audio/ogg":
  16787. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  16788. break;
  16789. default:
  16790. 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) {
  16791. sceneFileToLoad = filesToLoad[i];
  16792. }
  16793. break;
  16794. }
  16795. }
  16796. // If a ".babylon" file has been provided
  16797. if (sceneFileToLoad) {
  16798. if (this.currentScene) {
  16799. this.engine.stopRenderLoop();
  16800. this.currentScene.dispose();
  16801. }
  16802. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  16803. that.currentScene = newScene;
  16804. // Wait for textures and shaders to be ready
  16805. that.currentScene.executeWhenReady(function () {
  16806. // Attach camera to canvas inputs
  16807. if (that.currentScene.activeCamera) {
  16808. that.currentScene.activeCamera.attachControl(that.canvas);
  16809. }
  16810. if (that.sceneLoadedCallback) {
  16811. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  16812. }
  16813. that.engine.runRenderLoop(function () {
  16814. that.renderFunction();
  16815. });
  16816. });
  16817. }, function (progress) {
  16818. if (_this.progressCallback) {
  16819. _this.progressCallback(progress);
  16820. }
  16821. });
  16822. }
  16823. else {
  16824. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  16825. }
  16826. }
  16827. };
  16828. FilesInput.FilesTextures = new Array();
  16829. FilesInput.FilesToLoad = new Array();
  16830. return FilesInput;
  16831. })();
  16832. BABYLON.FilesInput = FilesInput;
  16833. })(BABYLON || (BABYLON = {}));
  16834. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  16835. (function (BABYLON) {
  16836. var OimoJSPlugin = (function () {
  16837. function OimoJSPlugin() {
  16838. this._registeredMeshes = [];
  16839. /**
  16840. * Update the body position according to the mesh position
  16841. * @param mesh
  16842. */
  16843. this.updateBodyPosition = function (mesh) {
  16844. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16845. var registeredMesh = this._registeredMeshes[index];
  16846. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16847. var body = registeredMesh.body.body;
  16848. mesh.computeWorldMatrix(true);
  16849. var center = mesh.getBoundingInfo().boundingBox.center;
  16850. body.setPosition(center.x, center.y, center.z);
  16851. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  16852. return;
  16853. }
  16854. // Case where the parent has been updated
  16855. if (registeredMesh.mesh.parent === mesh) {
  16856. mesh.computeWorldMatrix(true);
  16857. registeredMesh.mesh.computeWorldMatrix(true);
  16858. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  16859. var absoluteRotation = mesh.rotation;
  16860. body = registeredMesh.body.body;
  16861. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  16862. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  16863. return;
  16864. }
  16865. }
  16866. };
  16867. }
  16868. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  16869. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  16870. };
  16871. OimoJSPlugin.prototype.initialize = function (iterations) {
  16872. this._world = new OIMO.World();
  16873. this._world.clear();
  16874. };
  16875. OimoJSPlugin.prototype.setGravity = function (gravity) {
  16876. this._world.gravity = gravity;
  16877. };
  16878. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  16879. var body = null;
  16880. this.unregisterMesh(mesh);
  16881. mesh.computeWorldMatrix(true);
  16882. switch (impostor) {
  16883. case BABYLON.PhysicsEngine.SphereImpostor:
  16884. var initialRotation = null;
  16885. if (mesh.rotationQuaternion) {
  16886. initialRotation = mesh.rotationQuaternion.clone();
  16887. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16888. mesh.computeWorldMatrix(true);
  16889. }
  16890. var bbox = mesh.getBoundingInfo().boundingBox;
  16891. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16892. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16893. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16894. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16895. // The delta between the mesh position and the mesh bounding box center
  16896. var deltaPosition = mesh.position.subtract(bbox.center);
  16897. // Transform delta position with the rotation
  16898. if (initialRotation) {
  16899. var m = new BABYLON.Matrix();
  16900. initialRotation.toRotationMatrix(m);
  16901. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16902. }
  16903. body = new OIMO.Body({
  16904. type: 'sphere',
  16905. size: [size],
  16906. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16907. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16908. move: options.mass != 0,
  16909. config: [options.mass, options.friction, options.restitution],
  16910. world: this._world
  16911. });
  16912. // Restore rotation
  16913. if (initialRotation) {
  16914. body.setQuaternion(initialRotation);
  16915. }
  16916. this._registeredMeshes.push({
  16917. mesh: mesh,
  16918. body: body,
  16919. delta: deltaPosition
  16920. });
  16921. break;
  16922. case BABYLON.PhysicsEngine.PlaneImpostor:
  16923. case BABYLON.PhysicsEngine.BoxImpostor:
  16924. initialRotation = null;
  16925. if (mesh.rotationQuaternion) {
  16926. initialRotation = mesh.rotationQuaternion.clone();
  16927. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16928. mesh.computeWorldMatrix(true);
  16929. }
  16930. bbox = mesh.getBoundingInfo().boundingBox;
  16931. var min = bbox.minimumWorld;
  16932. var max = bbox.maximumWorld;
  16933. var box = max.subtract(min);
  16934. var sizeX = this._checkWithEpsilon(box.x);
  16935. var sizeY = this._checkWithEpsilon(box.y);
  16936. var sizeZ = this._checkWithEpsilon(box.z);
  16937. // The delta between the mesh position and the mesh boudning box center
  16938. deltaPosition = mesh.position.subtract(bbox.center);
  16939. // Transform delta position with the rotation
  16940. if (initialRotation) {
  16941. m = new BABYLON.Matrix();
  16942. initialRotation.toRotationMatrix(m);
  16943. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16944. }
  16945. body = new OIMO.Body({
  16946. type: 'box',
  16947. size: [sizeX, sizeY, sizeZ],
  16948. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16949. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16950. move: options.mass != 0,
  16951. config: [options.mass, options.friction, options.restitution],
  16952. world: this._world
  16953. });
  16954. if (initialRotation) {
  16955. body.setQuaternion(initialRotation);
  16956. }
  16957. this._registeredMeshes.push({
  16958. mesh: mesh,
  16959. body: body,
  16960. delta: deltaPosition
  16961. });
  16962. break;
  16963. }
  16964. return body;
  16965. };
  16966. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  16967. var types = [], sizes = [], positions = [], rotations = [];
  16968. var initialMesh = parts[0].mesh;
  16969. for (var index = 0; index < parts.length; index++) {
  16970. var part = parts[index];
  16971. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  16972. types.push(bodyParameters.type);
  16973. sizes.push.apply(sizes, bodyParameters.size);
  16974. positions.push.apply(positions, bodyParameters.pos);
  16975. rotations.push.apply(rotations, bodyParameters.rot);
  16976. }
  16977. var body = new OIMO.Body({
  16978. type: types,
  16979. size: sizes,
  16980. pos: positions,
  16981. rot: rotations,
  16982. move: options.mass != 0,
  16983. config: [options.mass, options.friction, options.restitution],
  16984. world: this._world
  16985. });
  16986. this._registeredMeshes.push({
  16987. mesh: initialMesh,
  16988. body: body
  16989. });
  16990. return body;
  16991. };
  16992. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  16993. var bodyParameters = null;
  16994. var mesh = part.mesh;
  16995. // We need the bounding box/sphere info to compute the physics body
  16996. mesh.computeWorldMatrix();
  16997. switch (part.impostor) {
  16998. case BABYLON.PhysicsEngine.SphereImpostor:
  16999. var bbox = mesh.getBoundingInfo().boundingBox;
  17000. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17001. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17002. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17003. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17004. bodyParameters = {
  17005. type: 'sphere',
  17006. /* bug with oimo : sphere needs 3 sizes in this case */
  17007. size: [size, -1, -1],
  17008. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  17009. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17010. };
  17011. break;
  17012. case BABYLON.PhysicsEngine.PlaneImpostor:
  17013. case BABYLON.PhysicsEngine.BoxImpostor:
  17014. bbox = mesh.getBoundingInfo().boundingBox;
  17015. var min = bbox.minimumWorld;
  17016. var max = bbox.maximumWorld;
  17017. var box = max.subtract(min);
  17018. var sizeX = this._checkWithEpsilon(box.x);
  17019. var sizeY = this._checkWithEpsilon(box.y);
  17020. var sizeZ = this._checkWithEpsilon(box.z);
  17021. var relativePosition = mesh.position;
  17022. bodyParameters = {
  17023. type: 'box',
  17024. size: [sizeX, sizeY, sizeZ],
  17025. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  17026. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17027. };
  17028. break;
  17029. }
  17030. return bodyParameters;
  17031. };
  17032. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  17033. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17034. var registeredMesh = this._registeredMeshes[index];
  17035. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17036. if (registeredMesh.body) {
  17037. this._world.removeRigidBody(registeredMesh.body.body);
  17038. this._unbindBody(registeredMesh.body);
  17039. }
  17040. this._registeredMeshes.splice(index, 1);
  17041. return;
  17042. }
  17043. }
  17044. };
  17045. OimoJSPlugin.prototype._unbindBody = function (body) {
  17046. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17047. var registeredMesh = this._registeredMeshes[index];
  17048. if (registeredMesh.body === body) {
  17049. registeredMesh.body = null;
  17050. }
  17051. }
  17052. };
  17053. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17054. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17055. var registeredMesh = this._registeredMeshes[index];
  17056. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17057. // Get object mass to have a behaviour similar to cannon.js
  17058. var mass = registeredMesh.body.body.massInfo.mass;
  17059. // The force is scaled with the mass of object
  17060. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17061. return;
  17062. }
  17063. }
  17064. };
  17065. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17066. var body1 = null, body2 = null;
  17067. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17068. var registeredMesh = this._registeredMeshes[index];
  17069. if (registeredMesh.mesh === mesh1) {
  17070. body1 = registeredMesh.body.body;
  17071. }
  17072. else if (registeredMesh.mesh === mesh2) {
  17073. body2 = registeredMesh.body.body;
  17074. }
  17075. }
  17076. if (!body1 || !body2) {
  17077. return false;
  17078. }
  17079. if (!options) {
  17080. options = {};
  17081. }
  17082. new OIMO.Link({
  17083. type: options.type,
  17084. body1: body1,
  17085. body2: body2,
  17086. min: options.min,
  17087. max: options.max,
  17088. axe1: options.axe1,
  17089. axe2: options.axe2,
  17090. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17091. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17092. collision: options.collision,
  17093. spring: options.spring,
  17094. world: this._world
  17095. });
  17096. return true;
  17097. };
  17098. OimoJSPlugin.prototype.dispose = function () {
  17099. this._world.clear();
  17100. while (this._registeredMeshes.length) {
  17101. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17102. }
  17103. };
  17104. OimoJSPlugin.prototype.isSupported = function () {
  17105. return OIMO !== undefined;
  17106. };
  17107. OimoJSPlugin.prototype._getLastShape = function (body) {
  17108. var lastShape = body.shapes;
  17109. while (lastShape.next) {
  17110. lastShape = lastShape.next;
  17111. }
  17112. return lastShape;
  17113. };
  17114. OimoJSPlugin.prototype.runOneStep = function (time) {
  17115. this._world.step();
  17116. // Update the position of all registered meshes
  17117. var i = this._registeredMeshes.length;
  17118. var m;
  17119. while (i--) {
  17120. var body = this._registeredMeshes[i].body.body;
  17121. var mesh = this._registeredMeshes[i].mesh;
  17122. var delta = this._registeredMeshes[i].delta;
  17123. if (!body.sleeping) {
  17124. if (body.shapes.next) {
  17125. var parentShape = this._getLastShape(body);
  17126. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17127. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17128. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17129. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17130. if (!mesh.rotationQuaternion) {
  17131. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17132. }
  17133. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17134. mesh.computeWorldMatrix();
  17135. }
  17136. else {
  17137. m = body.getMatrix();
  17138. mtx = BABYLON.Matrix.FromArray(m);
  17139. // Body position
  17140. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17141. if (!delta) {
  17142. mesh.position.x = bodyX;
  17143. mesh.position.y = bodyY;
  17144. mesh.position.z = bodyZ;
  17145. }
  17146. else {
  17147. mesh.position.x = bodyX + delta.x;
  17148. mesh.position.y = bodyY + delta.y;
  17149. mesh.position.z = bodyZ + delta.z;
  17150. }
  17151. if (!mesh.rotationQuaternion) {
  17152. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17153. }
  17154. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17155. mesh.computeWorldMatrix();
  17156. }
  17157. }
  17158. }
  17159. };
  17160. return OimoJSPlugin;
  17161. })();
  17162. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17163. })(BABYLON || (BABYLON = {}));
  17164. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17165. (function (BABYLON) {
  17166. var PhysicsEngine = (function () {
  17167. function PhysicsEngine(plugin) {
  17168. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17169. }
  17170. PhysicsEngine.prototype._initialize = function (gravity) {
  17171. this._currentPlugin.initialize();
  17172. this._setGravity(gravity);
  17173. };
  17174. PhysicsEngine.prototype._runOneStep = function (delta) {
  17175. if (delta > 0.1) {
  17176. delta = 0.1;
  17177. }
  17178. else if (delta <= 0) {
  17179. delta = 1.0 / 60.0;
  17180. }
  17181. this._currentPlugin.runOneStep(delta);
  17182. };
  17183. PhysicsEngine.prototype._setGravity = function (gravity) {
  17184. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17185. this._currentPlugin.setGravity(this.gravity);
  17186. };
  17187. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17188. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17189. };
  17190. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17191. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17192. };
  17193. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17194. this._currentPlugin.unregisterMesh(mesh);
  17195. };
  17196. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  17197. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  17198. };
  17199. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17200. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  17201. };
  17202. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  17203. this._currentPlugin.updateBodyPosition(mesh);
  17204. };
  17205. PhysicsEngine.prototype.dispose = function () {
  17206. this._currentPlugin.dispose();
  17207. };
  17208. PhysicsEngine.prototype.isSupported = function () {
  17209. return this._currentPlugin.isSupported();
  17210. };
  17211. // Statics
  17212. PhysicsEngine.NoImpostor = 0;
  17213. PhysicsEngine.SphereImpostor = 1;
  17214. PhysicsEngine.BoxImpostor = 2;
  17215. PhysicsEngine.PlaneImpostor = 3;
  17216. PhysicsEngine.MeshImpostor = 4;
  17217. PhysicsEngine.CapsuleImpostor = 5;
  17218. PhysicsEngine.ConeImpostor = 6;
  17219. PhysicsEngine.CylinderImpostor = 7;
  17220. PhysicsEngine.ConvexHullImpostor = 8;
  17221. PhysicsEngine.Epsilon = 0.001;
  17222. return PhysicsEngine;
  17223. })();
  17224. BABYLON.PhysicsEngine = PhysicsEngine;
  17225. })(BABYLON || (BABYLON = {}));
  17226. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  17227. (function (BABYLON) {
  17228. var serializeLight = function (light) {
  17229. var serializationObject = {};
  17230. serializationObject.name = light.name;
  17231. serializationObject.id = light.id;
  17232. serializationObject.tags = BABYLON.Tags.GetTags(light);
  17233. if (light instanceof BABYLON.PointLight) {
  17234. serializationObject.type = 0;
  17235. serializationObject.position = light.position.asArray();
  17236. }
  17237. else if (light instanceof BABYLON.DirectionalLight) {
  17238. serializationObject.type = 1;
  17239. var directionalLight = light;
  17240. serializationObject.position = directionalLight.position.asArray();
  17241. serializationObject.direction = directionalLight.direction.asArray();
  17242. }
  17243. else if (light instanceof BABYLON.SpotLight) {
  17244. serializationObject.type = 2;
  17245. var spotLight = light;
  17246. serializationObject.position = spotLight.position.asArray();
  17247. serializationObject.direction = spotLight.position.asArray();
  17248. serializationObject.angle = spotLight.angle;
  17249. serializationObject.exponent = spotLight.exponent;
  17250. }
  17251. else if (light instanceof BABYLON.HemisphericLight) {
  17252. serializationObject.type = 3;
  17253. var hemisphericLight = light;
  17254. serializationObject.direction = hemisphericLight.direction.asArray();
  17255. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  17256. }
  17257. if (light.intensity) {
  17258. serializationObject.intensity = light.intensity;
  17259. }
  17260. serializationObject.range = light.range;
  17261. serializationObject.diffuse = light.diffuse.asArray();
  17262. serializationObject.specular = light.specular.asArray();
  17263. return serializationObject;
  17264. };
  17265. var serializeFresnelParameter = function (fresnelParameter) {
  17266. var serializationObject = {};
  17267. serializationObject.isEnabled = fresnelParameter.isEnabled;
  17268. serializationObject.leftColor = fresnelParameter.leftColor;
  17269. serializationObject.rightColor = fresnelParameter.rightColor;
  17270. serializationObject.bias = fresnelParameter.bias;
  17271. serializationObject.power = fresnelParameter.power;
  17272. return serializationObject;
  17273. };
  17274. var serializeCamera = function (camera) {
  17275. var serializationObject = {};
  17276. serializationObject.name = camera.name;
  17277. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  17278. serializationObject.id = camera.id;
  17279. serializationObject.position = camera.position.asArray();
  17280. // Parent
  17281. if (camera.parent) {
  17282. serializationObject.parentId = camera.parent.id;
  17283. }
  17284. // Target
  17285. serializationObject.rotation = camera.rotation.asArray();
  17286. // Locked target
  17287. if (camera.lockedTarget && camera.lockedTarget.id) {
  17288. serializationObject.lockedTargetId = camera.lockedTarget.id;
  17289. }
  17290. serializationObject.fov = camera.fov;
  17291. serializationObject.minZ = camera.minZ;
  17292. serializationObject.maxZ = camera.maxZ;
  17293. serializationObject.speed = camera.speed;
  17294. serializationObject.inertia = camera.inertia;
  17295. serializationObject.checkCollisions = camera.checkCollisions;
  17296. serializationObject.applyGravity = camera.applyGravity;
  17297. if (camera.ellipsoid) {
  17298. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  17299. }
  17300. // Animations
  17301. appendAnimations(camera, serializationObject);
  17302. // Layer mask
  17303. serializationObject.layerMask = camera.layerMask;
  17304. return serializationObject;
  17305. };
  17306. var appendAnimations = function (source, destination) {
  17307. if (source.animations) {
  17308. destination.animations = [];
  17309. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  17310. var animation = source.animations[animationIndex];
  17311. destination.animations.push(serializeAnimation(animation));
  17312. }
  17313. }
  17314. };
  17315. var serializeAnimation = function (animation) {
  17316. var serializationObject = {};
  17317. serializationObject.name = animation.name;
  17318. serializationObject.property = animation.targetProperty;
  17319. serializationObject.framePerSecond = animation.framePerSecond;
  17320. serializationObject.dataType = animation.dataType;
  17321. serializationObject.loopBehavior = animation.loopMode;
  17322. var dataType = animation.dataType;
  17323. serializationObject.keys = [];
  17324. var keys = animation.getKeys();
  17325. for (var index = 0; index < keys.length; index++) {
  17326. var animationKey = keys[index];
  17327. var key = {};
  17328. key.frame = animationKey.frame;
  17329. switch (dataType) {
  17330. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17331. key.values = [animationKey.value];
  17332. break;
  17333. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17334. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17335. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17336. key.values = animationKey.value.asArray();
  17337. break;
  17338. }
  17339. serializationObject.keys.push(key);
  17340. }
  17341. return serializationObject;
  17342. };
  17343. var serializeMultiMaterial = function (material) {
  17344. var serializationObject = {};
  17345. serializationObject.name = material.name;
  17346. serializationObject.id = material.id;
  17347. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17348. serializationObject.materials = [];
  17349. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  17350. var subMat = material.subMaterials[matIndex];
  17351. if (subMat) {
  17352. serializationObject.materials.push(subMat.id);
  17353. }
  17354. else {
  17355. serializationObject.materials.push(null);
  17356. }
  17357. }
  17358. return serializationObject;
  17359. };
  17360. var serializeMaterial = function (material) {
  17361. var serializationObject = {};
  17362. serializationObject.name = material.name;
  17363. serializationObject.ambient = material.ambientColor.asArray();
  17364. serializationObject.diffuse = material.diffuseColor.asArray();
  17365. serializationObject.specular = material.specularColor.asArray();
  17366. serializationObject.specularPower = material.specularPower;
  17367. serializationObject.emissive = material.emissiveColor.asArray();
  17368. serializationObject.alpha = material.alpha;
  17369. serializationObject.id = material.id;
  17370. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17371. serializationObject.backFaceCulling = material.backFaceCulling;
  17372. if (material.diffuseTexture) {
  17373. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  17374. }
  17375. if (material.diffuseFresnelParameters) {
  17376. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  17377. }
  17378. if (material.ambientTexture) {
  17379. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  17380. }
  17381. if (material.opacityTexture) {
  17382. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  17383. }
  17384. if (material.opacityFresnelParameters) {
  17385. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  17386. }
  17387. if (material.reflectionTexture) {
  17388. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  17389. }
  17390. if (material.reflectionFresnelParameters) {
  17391. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  17392. }
  17393. if (material.emissiveTexture) {
  17394. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  17395. }
  17396. if (material.emissiveFresnelParameters) {
  17397. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  17398. }
  17399. if (material.specularTexture) {
  17400. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  17401. }
  17402. if (material.bumpTexture) {
  17403. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  17404. }
  17405. return serializationObject;
  17406. };
  17407. var serializeTexture = function (texture) {
  17408. var serializationObject = {};
  17409. if (!texture.name) {
  17410. return null;
  17411. }
  17412. if (texture instanceof BABYLON.CubeTexture) {
  17413. serializationObject.name = texture.name;
  17414. serializationObject.hasAlpha = texture.hasAlpha;
  17415. serializationObject.level = texture.level;
  17416. serializationObject.coordinatesMode = texture.coordinatesMode;
  17417. return serializationObject;
  17418. }
  17419. if (texture instanceof BABYLON.MirrorTexture) {
  17420. var mirrorTexture = texture;
  17421. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  17422. serializationObject.renderList = [];
  17423. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  17424. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  17425. }
  17426. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  17427. }
  17428. else if (texture instanceof BABYLON.RenderTargetTexture) {
  17429. var renderTargetTexture = texture;
  17430. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  17431. serializationObject.renderList = [];
  17432. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  17433. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  17434. }
  17435. }
  17436. var regularTexture = texture;
  17437. serializationObject.name = texture.name;
  17438. serializationObject.hasAlpha = texture.hasAlpha;
  17439. serializationObject.level = texture.level;
  17440. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  17441. serializationObject.coordinatesMode = texture.coordinatesMode;
  17442. serializationObject.uOffset = regularTexture.uOffset;
  17443. serializationObject.vOffset = regularTexture.vOffset;
  17444. serializationObject.uScale = regularTexture.uScale;
  17445. serializationObject.vScale = regularTexture.vScale;
  17446. serializationObject.uAng = regularTexture.uAng;
  17447. serializationObject.vAng = regularTexture.vAng;
  17448. serializationObject.wAng = regularTexture.wAng;
  17449. serializationObject.wrapU = texture.wrapU;
  17450. serializationObject.wrapV = texture.wrapV;
  17451. // Animations
  17452. appendAnimations(texture, serializationObject);
  17453. return serializationObject;
  17454. };
  17455. var serializeSkeleton = function (skeleton) {
  17456. var serializationObject = {};
  17457. serializationObject.name = skeleton.name;
  17458. serializationObject.id = skeleton.id;
  17459. serializationObject.bones = [];
  17460. for (var index = 0; index < skeleton.bones.length; index++) {
  17461. var bone = skeleton.bones[index];
  17462. var serializedBone = {
  17463. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  17464. name: bone.name,
  17465. matrix: bone.getLocalMatrix().toArray()
  17466. };
  17467. serializationObject.bones.push(serializedBone);
  17468. if (bone.animations && bone.animations.length > 0) {
  17469. serializedBone.animation = serializeAnimation(bone.animations[0]);
  17470. }
  17471. }
  17472. return serializationObject;
  17473. };
  17474. var serializeParticleSystem = function (particleSystem) {
  17475. var serializationObject = {};
  17476. serializationObject.emitterId = particleSystem.emitter.id;
  17477. serializationObject.capacity = particleSystem.getCapacity();
  17478. if (particleSystem.particleTexture) {
  17479. serializationObject.textureName = particleSystem.particleTexture.name;
  17480. }
  17481. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  17482. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  17483. serializationObject.minSize = particleSystem.minSize;
  17484. serializationObject.maxSize = particleSystem.maxSize;
  17485. serializationObject.minLifeTime = particleSystem.minLifeTime;
  17486. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  17487. serializationObject.emitRate = particleSystem.emitRate;
  17488. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  17489. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  17490. serializationObject.gravity = particleSystem.gravity.asArray();
  17491. serializationObject.direction1 = particleSystem.direction1.asArray();
  17492. serializationObject.direction2 = particleSystem.direction2.asArray();
  17493. serializationObject.color1 = particleSystem.color1.asArray();
  17494. serializationObject.color2 = particleSystem.color2.asArray();
  17495. serializationObject.colorDead = particleSystem.colorDead.asArray();
  17496. serializationObject.updateSpeed = particleSystem.updateSpeed;
  17497. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  17498. serializationObject.textureMask = particleSystem.textureMask.asArray();
  17499. serializationObject.blendMode = particleSystem.blendMode;
  17500. return serializationObject;
  17501. };
  17502. var serializeLensFlareSystem = function (lensFlareSystem) {
  17503. var serializationObject = {};
  17504. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  17505. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  17506. serializationObject.flares = [];
  17507. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  17508. var flare = lensFlareSystem.lensFlares[index];
  17509. serializationObject.flares.push({
  17510. size: flare.size,
  17511. position: flare.position,
  17512. color: flare.color.asArray(),
  17513. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  17514. });
  17515. }
  17516. return serializationObject;
  17517. };
  17518. var serializeShadowGenerator = function (light) {
  17519. var serializationObject = {};
  17520. var shadowGenerator = light.getShadowGenerator();
  17521. serializationObject.lightId = light.id;
  17522. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  17523. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  17524. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  17525. serializationObject.renderList = [];
  17526. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  17527. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  17528. serializationObject.renderList.push(mesh.id);
  17529. }
  17530. return serializationObject;
  17531. };
  17532. var serializedGeometries = [];
  17533. var serializeGeometry = function (geometry, serializationGeometries) {
  17534. if (serializedGeometries[geometry.id]) {
  17535. return;
  17536. }
  17537. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  17538. serializationGeometries.boxes.push(serializeBox(geometry));
  17539. }
  17540. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  17541. serializationGeometries.spheres.push(serializeSphere(geometry));
  17542. }
  17543. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  17544. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  17545. }
  17546. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  17547. serializationGeometries.toruses.push(serializeTorus(geometry));
  17548. }
  17549. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  17550. serializationGeometries.grounds.push(serializeGround(geometry));
  17551. }
  17552. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  17553. serializationGeometries.planes.push(serializePlane(geometry));
  17554. }
  17555. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  17556. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  17557. }
  17558. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  17559. throw new Error("Unknow primitive type");
  17560. }
  17561. else {
  17562. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  17563. }
  17564. serializedGeometries[geometry.id] = true;
  17565. };
  17566. var serializeGeometryBase = function (geometry) {
  17567. var serializationObject = {};
  17568. serializationObject.id = geometry.id;
  17569. if (BABYLON.Tags.HasTags(geometry)) {
  17570. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  17571. }
  17572. return serializationObject;
  17573. };
  17574. var serializeVertexData = function (vertexData) {
  17575. var serializationObject = serializeGeometryBase(vertexData);
  17576. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17577. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17578. }
  17579. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17580. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17581. }
  17582. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17583. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17584. }
  17585. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17586. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17587. }
  17588. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17589. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17590. }
  17591. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17592. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17593. serializationObject.matricesIndices._isExpanded = true;
  17594. }
  17595. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17596. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17597. }
  17598. serializationObject.indices = vertexData.getIndices();
  17599. return serializationObject;
  17600. };
  17601. var serializePrimitive = function (primitive) {
  17602. var serializationObject = serializeGeometryBase(primitive);
  17603. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  17604. return serializationObject;
  17605. };
  17606. var serializeBox = function (box) {
  17607. var serializationObject = serializePrimitive(box);
  17608. serializationObject.size = box.size;
  17609. return serializationObject;
  17610. };
  17611. var serializeSphere = function (sphere) {
  17612. var serializationObject = serializePrimitive(sphere);
  17613. serializationObject.segments = sphere.segments;
  17614. serializationObject.diameter = sphere.diameter;
  17615. return serializationObject;
  17616. };
  17617. var serializeCylinder = function (cylinder) {
  17618. var serializationObject = serializePrimitive(cylinder);
  17619. serializationObject.height = cylinder.height;
  17620. serializationObject.diameterTop = cylinder.diameterTop;
  17621. serializationObject.diameterBottom = cylinder.diameterBottom;
  17622. serializationObject.tessellation = cylinder.tessellation;
  17623. return serializationObject;
  17624. };
  17625. var serializeTorus = function (torus) {
  17626. var serializationObject = serializePrimitive(torus);
  17627. serializationObject.diameter = torus.diameter;
  17628. serializationObject.thickness = torus.thickness;
  17629. serializationObject.tessellation = torus.tessellation;
  17630. return serializationObject;
  17631. };
  17632. var serializeGround = function (ground) {
  17633. var serializationObject = serializePrimitive(ground);
  17634. serializationObject.width = ground.width;
  17635. serializationObject.height = ground.height;
  17636. serializationObject.subdivisions = ground.subdivisions;
  17637. return serializationObject;
  17638. };
  17639. var serializePlane = function (plane) {
  17640. var serializationObject = serializePrimitive(plane);
  17641. serializationObject.size = plane.size;
  17642. return serializationObject;
  17643. };
  17644. var serializeTorusKnot = function (torusKnot) {
  17645. var serializationObject = serializePrimitive(torusKnot);
  17646. serializationObject.radius = torusKnot.radius;
  17647. serializationObject.tube = torusKnot.tube;
  17648. serializationObject.radialSegments = torusKnot.radialSegments;
  17649. serializationObject.tubularSegments = torusKnot.tubularSegments;
  17650. serializationObject.p = torusKnot.p;
  17651. serializationObject.q = torusKnot.q;
  17652. return serializationObject;
  17653. };
  17654. var serializeMesh = function (mesh, serializationScene) {
  17655. var serializationObject = {};
  17656. serializationObject.name = mesh.name;
  17657. serializationObject.id = mesh.id;
  17658. if (BABYLON.Tags.HasTags(mesh)) {
  17659. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  17660. }
  17661. serializationObject.position = mesh.position.asArray();
  17662. if (mesh.rotationQuaternion) {
  17663. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  17664. }
  17665. else if (mesh.rotation) {
  17666. serializationObject.rotation = mesh.rotation.asArray();
  17667. }
  17668. serializationObject.scaling = mesh.scaling.asArray();
  17669. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  17670. serializationObject.isEnabled = mesh.isEnabled();
  17671. serializationObject.isVisible = mesh.isVisible;
  17672. serializationObject.infiniteDistance = mesh.infiniteDistance;
  17673. serializationObject.pickable = mesh.isPickable;
  17674. serializationObject.receiveShadows = mesh.receiveShadows;
  17675. serializationObject.billboardMode = mesh.billboardMode;
  17676. serializationObject.visibility = mesh.visibility;
  17677. serializationObject.checkCollisions = mesh.checkCollisions;
  17678. // Parent
  17679. if (mesh.parent) {
  17680. serializationObject.parentId = mesh.parent.id;
  17681. }
  17682. // Geometry
  17683. var geometry = mesh._geometry;
  17684. if (geometry) {
  17685. var geometryId = geometry.id;
  17686. serializationObject.geometryId = geometryId;
  17687. if (!mesh.getScene().getGeometryByID(geometryId)) {
  17688. // 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
  17689. serializeGeometry(geometry, serializationScene.geometries);
  17690. }
  17691. // SubMeshes
  17692. serializationObject.subMeshes = [];
  17693. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17694. var subMesh = mesh.subMeshes[subIndex];
  17695. serializationObject.subMeshes.push({
  17696. materialIndex: subMesh.materialIndex,
  17697. verticesStart: subMesh.verticesStart,
  17698. verticesCount: subMesh.verticesCount,
  17699. indexStart: subMesh.indexStart,
  17700. indexCount: subMesh.indexCount
  17701. });
  17702. }
  17703. }
  17704. // Material
  17705. if (mesh.material) {
  17706. serializationObject.materialId = mesh.material.id;
  17707. }
  17708. else {
  17709. mesh.material = null;
  17710. }
  17711. // Skeleton
  17712. if (mesh.skeleton) {
  17713. serializationObject.skeletonId = mesh.skeleton.id;
  17714. }
  17715. // Physics
  17716. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  17717. serializationObject.physicsMass = mesh.getPhysicsMass();
  17718. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  17719. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  17720. switch (mesh.getPhysicsImpostor()) {
  17721. case BABYLON.PhysicsEngine.BoxImpostor:
  17722. serializationObject.physicsImpostor = 1;
  17723. break;
  17724. case BABYLON.PhysicsEngine.SphereImpostor:
  17725. serializationObject.physicsImpostor = 2;
  17726. break;
  17727. }
  17728. }
  17729. // Instances
  17730. serializationObject.instances = [];
  17731. for (var index = 0; index < mesh.instances.length; index++) {
  17732. var instance = mesh.instances[index];
  17733. var serializationInstance = {
  17734. name: instance.name,
  17735. position: instance.position,
  17736. rotation: instance.rotation,
  17737. rotationQuaternion: instance.rotationQuaternion,
  17738. scaling: instance.scaling
  17739. };
  17740. serializationObject.instances.push(serializationInstance);
  17741. // Animations
  17742. appendAnimations(instance, serializationInstance);
  17743. }
  17744. // Animations
  17745. appendAnimations(mesh, serializationObject);
  17746. // Layer mask
  17747. serializationObject.layerMask = mesh.layerMask;
  17748. return serializationObject;
  17749. };
  17750. var SceneSerializer = (function () {
  17751. function SceneSerializer() {
  17752. }
  17753. SceneSerializer.Serialize = function (scene) {
  17754. var serializationObject = {};
  17755. // Scene
  17756. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  17757. serializationObject.autoClear = scene.autoClear;
  17758. serializationObject.clearColor = scene.clearColor.asArray();
  17759. serializationObject.ambientColor = scene.ambientColor.asArray();
  17760. serializationObject.gravity = scene.gravity.asArray();
  17761. // Fog
  17762. if (scene.fogMode && scene.fogMode !== 0) {
  17763. serializationObject.fogMode = scene.fogMode;
  17764. serializationObject.fogColor = scene.fogColor.asArray();
  17765. serializationObject.fogStart = scene.fogStart;
  17766. serializationObject.fogEnd = scene.fogEnd;
  17767. serializationObject.fogDensity = scene.fogDensity;
  17768. }
  17769. // Lights
  17770. serializationObject.lights = [];
  17771. for (var index = 0; index < scene.lights.length; index++) {
  17772. var light = scene.lights[index];
  17773. serializationObject.lights.push(serializeLight(light));
  17774. }
  17775. // Cameras
  17776. serializationObject.cameras = [];
  17777. for (index = 0; index < scene.cameras.length; index++) {
  17778. var camera = scene.cameras[index];
  17779. if (camera instanceof BABYLON.FreeCamera) {
  17780. serializationObject.cameras.push(serializeCamera(camera));
  17781. }
  17782. }
  17783. if (scene.activeCamera) {
  17784. serializationObject.activeCameraID = scene.activeCamera.id;
  17785. }
  17786. // Materials
  17787. serializationObject.materials = [];
  17788. serializationObject.multiMaterials = [];
  17789. for (index = 0; index < scene.materials.length; index++) {
  17790. var material = scene.materials[index];
  17791. if (material instanceof BABYLON.StandardMaterial) {
  17792. serializationObject.materials.push(serializeMaterial(material));
  17793. }
  17794. else if (material instanceof BABYLON.MultiMaterial) {
  17795. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  17796. }
  17797. }
  17798. // Skeletons
  17799. serializationObject.skeletons = [];
  17800. for (index = 0; index < scene.skeletons.length; index++) {
  17801. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  17802. }
  17803. // Geometries
  17804. serializationObject.geometries = {};
  17805. serializationObject.geometries.boxes = [];
  17806. serializationObject.geometries.spheres = [];
  17807. serializationObject.geometries.cylinders = [];
  17808. serializationObject.geometries.toruses = [];
  17809. serializationObject.geometries.grounds = [];
  17810. serializationObject.geometries.planes = [];
  17811. serializationObject.geometries.torusKnots = [];
  17812. serializationObject.geometries.vertexData = [];
  17813. serializedGeometries = [];
  17814. var geometries = scene.getGeometries();
  17815. for (var index = 0; index < geometries.length; index++) {
  17816. var geometry = geometries[index];
  17817. if (geometry.isReady()) {
  17818. serializeGeometry(geometry, serializationObject.geometries);
  17819. }
  17820. }
  17821. // Meshes
  17822. serializationObject.meshes = [];
  17823. for (index = 0; index < scene.meshes.length; index++) {
  17824. var abstractMesh = scene.meshes[index];
  17825. if (abstractMesh instanceof BABYLON.Mesh) {
  17826. var mesh = abstractMesh;
  17827. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  17828. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  17829. }
  17830. }
  17831. }
  17832. // Particles Systems
  17833. serializationObject.particleSystems = [];
  17834. for (index = 0; index < scene.particleSystems.length; index++) {
  17835. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  17836. }
  17837. // Lens flares
  17838. serializationObject.lensFlareSystems = [];
  17839. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  17840. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  17841. }
  17842. // Shadows
  17843. serializationObject.shadowGenerators = [];
  17844. for (index = 0; index < scene.lights.length; index++) {
  17845. light = scene.lights[index];
  17846. if (light.getShadowGenerator()) {
  17847. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  17848. }
  17849. }
  17850. return serializationObject;
  17851. };
  17852. return SceneSerializer;
  17853. })();
  17854. BABYLON.SceneSerializer = SceneSerializer;
  17855. })(BABYLON || (BABYLON = {}));
  17856. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  17857. (function (BABYLON) {
  17858. var SceneLoader = (function () {
  17859. function SceneLoader() {
  17860. }
  17861. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  17862. get: function () {
  17863. return SceneLoader._ForceFullSceneLoadingForIncremental;
  17864. },
  17865. set: function (value) {
  17866. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  17867. },
  17868. enumerable: true,
  17869. configurable: true
  17870. });
  17871. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  17872. get: function () {
  17873. return SceneLoader._ShowLoadingScreen;
  17874. },
  17875. set: function (value) {
  17876. SceneLoader._ShowLoadingScreen = value;
  17877. },
  17878. enumerable: true,
  17879. configurable: true
  17880. });
  17881. SceneLoader._getPluginForFilename = function (sceneFilename) {
  17882. var dotPosition = sceneFilename.lastIndexOf(".");
  17883. var queryStringPosition = sceneFilename.indexOf("?");
  17884. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17885. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17886. var plugin = this._registeredPlugins[index];
  17887. if (plugin.extensions.indexOf(extension) !== -1) {
  17888. return plugin;
  17889. }
  17890. }
  17891. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17892. };
  17893. // Public functions
  17894. SceneLoader.RegisterPlugin = function (plugin) {
  17895. plugin.extensions = plugin.extensions.toLowerCase();
  17896. SceneLoader._registeredPlugins.push(plugin);
  17897. };
  17898. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17899. var manifestChecked = function (success) {
  17900. scene.database = database;
  17901. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17902. var importMeshFromData = function (data) {
  17903. var meshes = [];
  17904. var particleSystems = [];
  17905. var skeletons = [];
  17906. try {
  17907. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17908. if (onerror) {
  17909. onerror(scene, 'unable to load the scene');
  17910. }
  17911. return;
  17912. }
  17913. }
  17914. catch (e) {
  17915. if (onerror) {
  17916. onerror(scene, e);
  17917. }
  17918. return;
  17919. }
  17920. if (onsuccess) {
  17921. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17922. onsuccess(meshes, particleSystems, skeletons);
  17923. }
  17924. };
  17925. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17926. // Direct load
  17927. importMeshFromData(sceneFilename.substr(5));
  17928. return;
  17929. }
  17930. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17931. importMeshFromData(data);
  17932. }, progressCallBack, database);
  17933. };
  17934. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17935. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17936. };
  17937. /**
  17938. * Load a scene
  17939. * @param rootUrl a string that defines the root url for scene and resources
  17940. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17941. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17942. */
  17943. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17944. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17945. };
  17946. /**
  17947. * Append a scene
  17948. * @param rootUrl a string that defines the root url for scene and resources
  17949. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17950. * @param scene is the instance of BABYLON.Scene to append to
  17951. */
  17952. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17953. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17954. var database;
  17955. if (SceneLoader.ShowLoadingScreen) {
  17956. scene.getEngine().displayLoadingUI();
  17957. }
  17958. var loadSceneFromData = function (data) {
  17959. scene.database = database;
  17960. if (!plugin.load(scene, data, rootUrl)) {
  17961. if (onerror) {
  17962. onerror(scene);
  17963. }
  17964. scene.getEngine().hideLoadingUI();
  17965. return;
  17966. }
  17967. if (onsuccess) {
  17968. onsuccess(scene);
  17969. }
  17970. if (SceneLoader.ShowLoadingScreen) {
  17971. scene.executeWhenReady(function () {
  17972. scene.getEngine().hideLoadingUI();
  17973. });
  17974. }
  17975. };
  17976. var manifestChecked = function (success) {
  17977. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17978. };
  17979. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17980. // Direct load
  17981. loadSceneFromData(sceneFilename.substr(5));
  17982. return;
  17983. }
  17984. if (rootUrl.indexOf("file:") === -1) {
  17985. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17986. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17987. }
  17988. else {
  17989. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17990. }
  17991. };
  17992. // Flags
  17993. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17994. SceneLoader._ShowLoadingScreen = true;
  17995. // Members
  17996. SceneLoader._registeredPlugins = new Array();
  17997. return SceneLoader;
  17998. })();
  17999. BABYLON.SceneLoader = SceneLoader;
  18000. ;
  18001. })(BABYLON || (BABYLON = {}));
  18002. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  18003. (function (BABYLON) {
  18004. var Internals;
  18005. (function (Internals) {
  18006. var checkColors4 = function (colors, count) {
  18007. // Check if color3 was used
  18008. if (colors.length === count * 3) {
  18009. var colors4 = [];
  18010. for (var index = 0; index < colors.length; index += 3) {
  18011. var newIndex = (index / 3) * 4;
  18012. colors4[newIndex] = colors[index];
  18013. colors4[newIndex + 1] = colors[index + 1];
  18014. colors4[newIndex + 2] = colors[index + 2];
  18015. colors4[newIndex + 3] = 1.0;
  18016. }
  18017. return colors4;
  18018. }
  18019. return colors;
  18020. };
  18021. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18022. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18023. texture.name = parsedTexture.name;
  18024. texture.hasAlpha = parsedTexture.hasAlpha;
  18025. texture.level = parsedTexture.level;
  18026. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18027. return texture;
  18028. };
  18029. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18030. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18031. return null;
  18032. }
  18033. if (parsedTexture.isCube) {
  18034. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18035. }
  18036. var texture;
  18037. if (parsedTexture.mirrorPlane) {
  18038. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18039. texture._waitingRenderList = parsedTexture.renderList;
  18040. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18041. }
  18042. else if (parsedTexture.isRenderTarget) {
  18043. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18044. texture._waitingRenderList = parsedTexture.renderList;
  18045. }
  18046. else {
  18047. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18048. }
  18049. texture.name = parsedTexture.name;
  18050. texture.hasAlpha = parsedTexture.hasAlpha;
  18051. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18052. texture.level = parsedTexture.level;
  18053. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18054. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18055. texture.uOffset = parsedTexture.uOffset;
  18056. texture.vOffset = parsedTexture.vOffset;
  18057. texture.uScale = parsedTexture.uScale;
  18058. texture.vScale = parsedTexture.vScale;
  18059. texture.uAng = parsedTexture.uAng;
  18060. texture.vAng = parsedTexture.vAng;
  18061. texture.wAng = parsedTexture.wAng;
  18062. texture.wrapU = parsedTexture.wrapU;
  18063. texture.wrapV = parsedTexture.wrapV;
  18064. // Animations
  18065. if (parsedTexture.animations) {
  18066. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18067. var parsedAnimation = parsedTexture.animations[animationIndex];
  18068. texture.animations.push(parseAnimation(parsedAnimation));
  18069. }
  18070. }
  18071. return texture;
  18072. };
  18073. var parseSkeleton = function (parsedSkeleton, scene) {
  18074. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18075. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18076. var parsedBone = parsedSkeleton.bones[index];
  18077. var parentBone = null;
  18078. if (parsedBone.parentBoneIndex > -1) {
  18079. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18080. }
  18081. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18082. if (parsedBone.animation) {
  18083. bone.animations.push(parseAnimation(parsedBone.animation));
  18084. }
  18085. }
  18086. return skeleton;
  18087. };
  18088. var parseFresnelParameters = function (parsedFresnelParameters) {
  18089. var fresnelParameters = new BABYLON.FresnelParameters();
  18090. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18091. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18092. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18093. fresnelParameters.bias = parsedFresnelParameters.bias;
  18094. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18095. return fresnelParameters;
  18096. };
  18097. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18098. var material;
  18099. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18100. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18101. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18102. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18103. material.specularPower = parsedMaterial.specularPower;
  18104. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18105. material.alpha = parsedMaterial.alpha;
  18106. material.id = parsedMaterial.id;
  18107. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18108. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18109. material.wireframe = parsedMaterial.wireframe;
  18110. if (parsedMaterial.diffuseTexture) {
  18111. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18112. }
  18113. if (parsedMaterial.diffuseFresnelParameters) {
  18114. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18115. }
  18116. if (parsedMaterial.ambientTexture) {
  18117. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18118. }
  18119. if (parsedMaterial.opacityTexture) {
  18120. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18121. }
  18122. if (parsedMaterial.opacityFresnelParameters) {
  18123. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18124. }
  18125. if (parsedMaterial.reflectionTexture) {
  18126. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18127. }
  18128. if (parsedMaterial.reflectionFresnelParameters) {
  18129. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18130. }
  18131. if (parsedMaterial.emissiveTexture) {
  18132. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18133. }
  18134. if (parsedMaterial.emissiveFresnelParameters) {
  18135. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18136. }
  18137. if (parsedMaterial.specularTexture) {
  18138. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18139. }
  18140. if (parsedMaterial.bumpTexture) {
  18141. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18142. }
  18143. return material;
  18144. };
  18145. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18146. for (var index = 0; index < parsedData.materials.length; index++) {
  18147. var parsedMaterial = parsedData.materials[index];
  18148. if (parsedMaterial.id === id) {
  18149. return parseMaterial(parsedMaterial, scene, rootUrl);
  18150. }
  18151. }
  18152. return null;
  18153. };
  18154. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18155. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18156. multiMaterial.id = parsedMultiMaterial.id;
  18157. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18158. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18159. var subMatId = parsedMultiMaterial.materials[matIndex];
  18160. if (subMatId) {
  18161. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18162. }
  18163. else {
  18164. multiMaterial.subMaterials.push(null);
  18165. }
  18166. }
  18167. return multiMaterial;
  18168. };
  18169. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18170. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18171. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18172. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18173. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18174. var parsedFlare = parsedLensFlareSystem.flares[index];
  18175. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18176. }
  18177. return lensFlareSystem;
  18178. };
  18179. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18180. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18181. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18182. if (parsedParticleSystem.textureName) {
  18183. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18184. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18185. }
  18186. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18187. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18188. particleSystem.minSize = parsedParticleSystem.minSize;
  18189. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18190. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18191. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18192. particleSystem.emitter = emitter;
  18193. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18194. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18195. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18196. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18197. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18198. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18199. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18200. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18201. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18202. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18203. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18204. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18205. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18206. particleSystem.start();
  18207. return particleSystem;
  18208. };
  18209. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18210. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18211. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18212. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18213. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18214. shadowGenerator.getShadowMap().renderList.push(mesh);
  18215. }
  18216. if (parsedShadowGenerator.usePoissonSampling) {
  18217. shadowGenerator.usePoissonSampling = true;
  18218. }
  18219. else {
  18220. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  18221. }
  18222. return shadowGenerator;
  18223. };
  18224. var parseAnimation = function (parsedAnimation) {
  18225. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18226. var dataType = parsedAnimation.dataType;
  18227. var keys = [];
  18228. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18229. var key = parsedAnimation.keys[index];
  18230. var data;
  18231. switch (dataType) {
  18232. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18233. data = key.values[0];
  18234. break;
  18235. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18236. data = BABYLON.Quaternion.FromArray(key.values);
  18237. break;
  18238. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18239. data = BABYLON.Matrix.FromArray(key.values);
  18240. break;
  18241. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18242. default:
  18243. data = BABYLON.Vector3.FromArray(key.values);
  18244. break;
  18245. }
  18246. keys.push({
  18247. frame: key.frame,
  18248. value: data
  18249. });
  18250. }
  18251. animation.setKeys(keys);
  18252. return animation;
  18253. };
  18254. var parseLight = function (parsedLight, scene) {
  18255. var light;
  18256. switch (parsedLight.type) {
  18257. case 0:
  18258. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18259. break;
  18260. case 1:
  18261. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18262. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  18263. break;
  18264. case 2:
  18265. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18266. break;
  18267. case 3:
  18268. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18269. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18270. break;
  18271. }
  18272. light.id = parsedLight.id;
  18273. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18274. if (parsedLight.intensity !== undefined) {
  18275. light.intensity = parsedLight.intensity;
  18276. }
  18277. if (parsedLight.range) {
  18278. light.range = parsedLight.range;
  18279. }
  18280. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18281. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18282. if (parsedLight.excludedMeshesIds) {
  18283. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18284. }
  18285. // Parent
  18286. if (parsedLight.parentId) {
  18287. light._waitingParentId = parsedLight.parentId;
  18288. }
  18289. if (parsedLight.includedOnlyMeshesIds) {
  18290. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18291. }
  18292. // Animations
  18293. if (parsedLight.animations) {
  18294. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18295. var parsedAnimation = parsedLight.animations[animationIndex];
  18296. light.animations.push(parseAnimation(parsedAnimation));
  18297. }
  18298. }
  18299. if (parsedLight.autoAnimate) {
  18300. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  18301. }
  18302. };
  18303. var parseCamera = function (parsedCamera, scene) {
  18304. var camera;
  18305. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  18306. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  18307. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  18308. var alpha = parsedCamera.alpha;
  18309. var beta = parsedCamera.beta;
  18310. var radius = parsedCamera.radius;
  18311. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18312. var eye_space = parsedCamera.eye_space;
  18313. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18314. }
  18315. else {
  18316. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18317. }
  18318. }
  18319. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18320. eye_space = parsedCamera.eye_space;
  18321. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18322. }
  18323. else if (parsedCamera.type === "DeviceOrientationCamera") {
  18324. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18325. }
  18326. else if (parsedCamera.type === "FollowCamera") {
  18327. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18328. camera.heightOffset = parsedCamera.heightOffset;
  18329. camera.radius = parsedCamera.radius;
  18330. camera.rotationOffset = parsedCamera.rotationOffset;
  18331. if (lockedTargetMesh)
  18332. camera.target = lockedTargetMesh;
  18333. }
  18334. else if (parsedCamera.type === "GamepadCamera") {
  18335. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  18336. }
  18337. else if (parsedCamera.type === "OculusCamera") {
  18338. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  18339. }
  18340. else if (parsedCamera.type === "OculusGamepadCamera") {
  18341. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  18342. }
  18343. else if (parsedCamera.type === "TouchCamera") {
  18344. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  18345. }
  18346. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  18347. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  18348. }
  18349. else if (parsedCamera.type === "WebVRCamera") {
  18350. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  18351. }
  18352. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  18353. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  18354. }
  18355. else {
  18356. // Free Camera is the default value
  18357. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  18358. }
  18359. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  18360. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  18361. camera.lockedTarget = lockedTargetMesh;
  18362. }
  18363. camera.id = parsedCamera.id;
  18364. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  18365. // Parent
  18366. if (parsedCamera.parentId) {
  18367. camera._waitingParentId = parsedCamera.parentId;
  18368. }
  18369. // Target
  18370. if (parsedCamera.target) {
  18371. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18372. }
  18373. else {
  18374. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  18375. }
  18376. camera.fov = parsedCamera.fov;
  18377. camera.minZ = parsedCamera.minZ;
  18378. camera.maxZ = parsedCamera.maxZ;
  18379. camera.speed = parsedCamera.speed;
  18380. camera.inertia = parsedCamera.inertia;
  18381. camera.checkCollisions = parsedCamera.checkCollisions;
  18382. camera.applyGravity = parsedCamera.applyGravity;
  18383. if (parsedCamera.ellipsoid) {
  18384. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  18385. }
  18386. // Animations
  18387. if (parsedCamera.animations) {
  18388. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18389. var parsedAnimation = parsedCamera.animations[animationIndex];
  18390. camera.animations.push(parseAnimation(parsedAnimation));
  18391. }
  18392. }
  18393. if (parsedCamera.autoAnimate) {
  18394. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  18395. }
  18396. // Layer Mask
  18397. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  18398. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  18399. }
  18400. else {
  18401. camera.layerMask = 0xFFFFFFFF;
  18402. }
  18403. return camera;
  18404. };
  18405. var parseGeometry = function (parsedGeometry, scene) {
  18406. var id = parsedGeometry.id;
  18407. return scene.getGeometryByID(id);
  18408. };
  18409. var parseBox = function (parsedBox, scene) {
  18410. if (parseGeometry(parsedBox, scene)) {
  18411. return null; // null since geometry could be something else than a box...
  18412. }
  18413. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  18414. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  18415. scene.pushGeometry(box, true);
  18416. return box;
  18417. };
  18418. var parseSphere = function (parsedSphere, scene) {
  18419. if (parseGeometry(parsedSphere, scene)) {
  18420. return null; // null since geometry could be something else than a sphere...
  18421. }
  18422. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18423. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18424. scene.pushGeometry(sphere, true);
  18425. return sphere;
  18426. };
  18427. var parseCylinder = function (parsedCylinder, scene) {
  18428. if (parseGeometry(parsedCylinder, scene)) {
  18429. return null; // null since geometry could be something else than a cylinder...
  18430. }
  18431. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18432. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18433. scene.pushGeometry(cylinder, true);
  18434. return cylinder;
  18435. };
  18436. var parseTorus = function (parsedTorus, scene) {
  18437. if (parseGeometry(parsedTorus, scene)) {
  18438. return null; // null since geometry could be something else than a torus...
  18439. }
  18440. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18441. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18442. scene.pushGeometry(torus, true);
  18443. return torus;
  18444. };
  18445. var parseGround = function (parsedGround, scene) {
  18446. if (parseGeometry(parsedGround, scene)) {
  18447. return null; // null since geometry could be something else than a ground...
  18448. }
  18449. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18450. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18451. scene.pushGeometry(ground, true);
  18452. return ground;
  18453. };
  18454. var parsePlane = function (parsedPlane, scene) {
  18455. if (parseGeometry(parsedPlane, scene)) {
  18456. return null; // null since geometry could be something else than a plane...
  18457. }
  18458. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18459. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18460. scene.pushGeometry(plane, true);
  18461. return plane;
  18462. };
  18463. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18464. if (parseGeometry(parsedTorusKnot, scene)) {
  18465. return null; // null since geometry could be something else than a torusKnot...
  18466. }
  18467. 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);
  18468. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18469. scene.pushGeometry(torusKnot, true);
  18470. return torusKnot;
  18471. };
  18472. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18473. if (parseGeometry(parsedVertexData, scene)) {
  18474. return null; // null since geometry could be a primitive
  18475. }
  18476. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18477. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18478. if (parsedVertexData.delayLoadingFile) {
  18479. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18480. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18481. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18482. geometry._delayInfo = [];
  18483. if (parsedVertexData.hasUVs) {
  18484. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18485. }
  18486. if (parsedVertexData.hasUVs2) {
  18487. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18488. }
  18489. if (parsedVertexData.hasColors) {
  18490. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18491. }
  18492. if (parsedVertexData.hasMatricesIndices) {
  18493. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18494. }
  18495. if (parsedVertexData.hasMatricesWeights) {
  18496. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18497. }
  18498. geometry._delayLoadingFunction = importVertexData;
  18499. }
  18500. else {
  18501. importVertexData(parsedVertexData, geometry);
  18502. }
  18503. scene.pushGeometry(geometry, true);
  18504. return geometry;
  18505. };
  18506. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18507. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18508. mesh.id = parsedMesh.id;
  18509. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18510. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18511. if (parsedMesh.rotationQuaternion) {
  18512. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18513. }
  18514. else if (parsedMesh.rotation) {
  18515. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18516. }
  18517. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18518. if (parsedMesh.localMatrix) {
  18519. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18520. }
  18521. else if (parsedMesh.pivotMatrix) {
  18522. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18523. }
  18524. mesh.setEnabled(parsedMesh.isEnabled);
  18525. mesh.isVisible = parsedMesh.isVisible;
  18526. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18527. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18528. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18529. if (parsedMesh.applyFog !== undefined) {
  18530. mesh.applyFog = parsedMesh.applyFog;
  18531. }
  18532. if (parsedMesh.pickable !== undefined) {
  18533. mesh.isPickable = parsedMesh.pickable;
  18534. }
  18535. if (parsedMesh.alphaIndex !== undefined) {
  18536. mesh.alphaIndex = parsedMesh.alphaIndex;
  18537. }
  18538. mesh.receiveShadows = parsedMesh.receiveShadows;
  18539. mesh.billboardMode = parsedMesh.billboardMode;
  18540. if (parsedMesh.visibility !== undefined) {
  18541. mesh.visibility = parsedMesh.visibility;
  18542. }
  18543. mesh.checkCollisions = parsedMesh.checkCollisions;
  18544. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18545. // Parent
  18546. if (parsedMesh.parentId) {
  18547. mesh._waitingParentId = parsedMesh.parentId;
  18548. }
  18549. // Actions
  18550. if (parsedMesh.actions !== undefined) {
  18551. mesh._waitingActions = parsedMesh.actions;
  18552. }
  18553. // Geometry
  18554. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18555. if (parsedMesh.delayLoadingFile) {
  18556. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18557. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18558. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18559. if (parsedMesh._binaryInfo) {
  18560. mesh._binaryInfo = parsedMesh._binaryInfo;
  18561. }
  18562. mesh._delayInfo = [];
  18563. if (parsedMesh.hasUVs) {
  18564. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18565. }
  18566. if (parsedMesh.hasUVs2) {
  18567. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18568. }
  18569. if (parsedMesh.hasColors) {
  18570. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18571. }
  18572. if (parsedMesh.hasMatricesIndices) {
  18573. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18574. }
  18575. if (parsedMesh.hasMatricesWeights) {
  18576. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18577. }
  18578. mesh._delayLoadingFunction = importGeometry;
  18579. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18580. mesh._checkDelayState();
  18581. }
  18582. }
  18583. else {
  18584. importGeometry(parsedMesh, mesh);
  18585. }
  18586. // Material
  18587. if (parsedMesh.materialId) {
  18588. mesh.setMaterialByID(parsedMesh.materialId);
  18589. }
  18590. else {
  18591. mesh.material = null;
  18592. }
  18593. // Skeleton
  18594. if (parsedMesh.skeletonId > -1) {
  18595. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18596. }
  18597. // Physics
  18598. if (parsedMesh.physicsImpostor) {
  18599. if (!scene.isPhysicsEnabled()) {
  18600. scene.enablePhysics();
  18601. }
  18602. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18603. }
  18604. // Animations
  18605. if (parsedMesh.animations) {
  18606. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18607. var parsedAnimation = parsedMesh.animations[animationIndex];
  18608. mesh.animations.push(parseAnimation(parsedAnimation));
  18609. }
  18610. }
  18611. if (parsedMesh.autoAnimate) {
  18612. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18613. }
  18614. // Layer Mask
  18615. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18616. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18617. }
  18618. else {
  18619. mesh.layerMask = 0xFFFFFFFF;
  18620. }
  18621. // Instances
  18622. if (parsedMesh.instances) {
  18623. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18624. var parsedInstance = parsedMesh.instances[index];
  18625. var instance = mesh.createInstance(parsedInstance.name);
  18626. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18627. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18628. if (parsedInstance.rotationQuaternion) {
  18629. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18630. }
  18631. else if (parsedInstance.rotation) {
  18632. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18633. }
  18634. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18635. instance.checkCollisions = mesh.checkCollisions;
  18636. if (parsedMesh.animations) {
  18637. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18638. parsedAnimation = parsedMesh.animations[animationIndex];
  18639. instance.animations.push(parseAnimation(parsedAnimation));
  18640. }
  18641. }
  18642. }
  18643. }
  18644. return mesh;
  18645. };
  18646. var parseActions = function (parsedActions, object, scene) {
  18647. var actionManager = new BABYLON.ActionManager(scene);
  18648. if (object === null)
  18649. scene.actionManager = actionManager;
  18650. else
  18651. object.actionManager = actionManager;
  18652. // instanciate a new object
  18653. var instanciate = function (name, params) {
  18654. var newInstance = Object.create(BABYLON[name].prototype);
  18655. newInstance.constructor.apply(newInstance, params);
  18656. return newInstance;
  18657. };
  18658. var parseParameter = function (name, value, target, propertyPath) {
  18659. if (propertyPath === null) {
  18660. // String, boolean or float
  18661. var floatValue = parseFloat(value);
  18662. if (value === "true" || value === "false")
  18663. return value === "true";
  18664. else
  18665. return isNaN(floatValue) ? value : floatValue;
  18666. }
  18667. var effectiveTarget = propertyPath.split(".");
  18668. var values = value.split(",");
  18669. for (var i = 0; i < effectiveTarget.length; i++) {
  18670. target = target[effectiveTarget[i]];
  18671. }
  18672. // Return appropriate value with its type
  18673. if (target instanceof Boolean)
  18674. return values[0] === "true";
  18675. if (target instanceof String)
  18676. return values[0];
  18677. // Parameters with multiple values such as Vector3 etc.
  18678. var split = new Array();
  18679. for (var i = 0; i < values.length; i++)
  18680. split.push(parseFloat(values[i]));
  18681. if (target instanceof BABYLON.Vector3)
  18682. return BABYLON.Vector3.FromArray(split);
  18683. if (target instanceof BABYLON.Vector4)
  18684. return BABYLON.Vector4.FromArray(split);
  18685. if (target instanceof BABYLON.Color3)
  18686. return BABYLON.Color3.FromArray(split);
  18687. if (target instanceof BABYLON.Color4)
  18688. return BABYLON.Color4.FromArray(split);
  18689. return parseFloat(values[0]);
  18690. };
  18691. // traverse graph per trigger
  18692. var traverse = function (parsedAction, trigger, condition, action) {
  18693. var parameters = new Array();
  18694. var target = null;
  18695. var propertyPath = null;
  18696. // Parameters
  18697. if (parsedAction.type === 2)
  18698. parameters.push(actionManager);
  18699. else
  18700. parameters.push(trigger);
  18701. for (var i = 0; i < parsedAction.properties.length; i++) {
  18702. var value = parsedAction.properties[i].value;
  18703. var name = parsedAction.properties[i].name;
  18704. if (name === "target")
  18705. value = target = scene.getNodeByName(value);
  18706. else if (name === "parent")
  18707. value = scene.getNodeByName(value);
  18708. else if (name !== "propertyPath") {
  18709. if (parsedAction.type === 2 && name === "operator")
  18710. value = BABYLON.ValueCondition[value];
  18711. else
  18712. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  18713. }
  18714. else {
  18715. propertyPath = value;
  18716. }
  18717. parameters.push(value);
  18718. }
  18719. parameters.push(condition);
  18720. // If interpolate value action
  18721. if (parsedAction.name === "InterpolateValueAction") {
  18722. var param = parameters[parameters.length - 2];
  18723. parameters[parameters.length - 1] = param;
  18724. parameters[parameters.length - 2] = condition;
  18725. }
  18726. // Action or condition(s)
  18727. var newAction = instanciate(parsedAction.name, parameters);
  18728. if (newAction instanceof BABYLON.Condition) {
  18729. condition = newAction;
  18730. newAction = action;
  18731. }
  18732. else {
  18733. condition = null;
  18734. if (action)
  18735. action.then(newAction);
  18736. else
  18737. actionManager.registerAction(newAction);
  18738. }
  18739. for (var i = 0; i < parsedAction.children.length; i++)
  18740. traverse(parsedAction.children[i], trigger, condition, newAction);
  18741. };
  18742. for (var i = 0; i < parsedActions.children.length; i++) {
  18743. var triggerParams;
  18744. var trigger = parsedActions.children[i];
  18745. if (trigger.properties.length > 0) {
  18746. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  18747. }
  18748. else
  18749. triggerParams = BABYLON.ActionManager[trigger.name];
  18750. for (var j = 0; j < trigger.children.length; j++)
  18751. traverse(trigger.children[j], triggerParams, null, null);
  18752. }
  18753. };
  18754. var parseSound = function (parsedSound, scene, rootUrl) {
  18755. var soundName = parsedSound.name;
  18756. var soundUrl = rootUrl + soundName;
  18757. var options = {
  18758. autoplay: parsedSound.autoplay,
  18759. loop: parsedSound.loop,
  18760. volume: parsedSound.volume,
  18761. spatialSound: parsedSound.spatialSound,
  18762. maxDistance: parsedSound.maxDistance,
  18763. rolloffFactor: parsedSound.rolloffFactor,
  18764. refDistance: parsedSound.refDistance,
  18765. distanceModel: parsedSound.distanceModel,
  18766. panningModel: parsedSound.panningModel,
  18767. playbackRate: parsedSound.playbackRate
  18768. };
  18769. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  18770. scene._removePendingData(newSound);
  18771. }, options);
  18772. scene._addPendingData(newSound);
  18773. if (parsedSound.position) {
  18774. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  18775. newSound.setPosition(soundPosition);
  18776. }
  18777. if (parsedSound.isDirectional) {
  18778. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  18779. if (parsedSound.localDirectionToMesh) {
  18780. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  18781. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  18782. }
  18783. }
  18784. if (parsedSound.connectedMeshId) {
  18785. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  18786. if (connectedMesh) {
  18787. newSound.attachToMesh(connectedMesh);
  18788. }
  18789. }
  18790. };
  18791. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18792. names = (names instanceof Array) ? names : [names];
  18793. for (var i in names) {
  18794. if (mesh.name === names[i]) {
  18795. hierarchyIds.push(mesh.id);
  18796. return true;
  18797. }
  18798. }
  18799. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18800. hierarchyIds.push(mesh.id);
  18801. return true;
  18802. }
  18803. return false;
  18804. };
  18805. var importVertexData = function (parsedVertexData, geometry) {
  18806. var vertexData = new BABYLON.VertexData();
  18807. // positions
  18808. var positions = parsedVertexData.positions;
  18809. if (positions) {
  18810. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18811. }
  18812. // normals
  18813. var normals = parsedVertexData.normals;
  18814. if (normals) {
  18815. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18816. }
  18817. // uvs
  18818. var uvs = parsedVertexData.uvs;
  18819. if (uvs) {
  18820. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  18821. }
  18822. // uv2s
  18823. var uv2s = parsedVertexData.uv2s;
  18824. if (uv2s) {
  18825. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  18826. }
  18827. // colors
  18828. var colors = parsedVertexData.colors;
  18829. if (colors) {
  18830. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  18831. }
  18832. // matricesIndices
  18833. var matricesIndices = parsedVertexData.matricesIndices;
  18834. if (matricesIndices) {
  18835. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  18836. }
  18837. // matricesWeights
  18838. var matricesWeights = parsedVertexData.matricesWeights;
  18839. if (matricesWeights) {
  18840. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  18841. }
  18842. // indices
  18843. var indices = parsedVertexData.indices;
  18844. if (indices) {
  18845. vertexData.indices = indices;
  18846. }
  18847. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  18848. };
  18849. var importGeometry = function (parsedGeometry, mesh) {
  18850. var scene = mesh.getScene();
  18851. // Geometry
  18852. var geometryId = parsedGeometry.geometryId;
  18853. if (geometryId) {
  18854. var geometry = scene.getGeometryByID(geometryId);
  18855. if (geometry) {
  18856. geometry.applyToMesh(mesh);
  18857. }
  18858. }
  18859. else if (parsedGeometry instanceof ArrayBuffer) {
  18860. var binaryInfo = mesh._binaryInfo;
  18861. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  18862. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  18863. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  18864. }
  18865. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  18866. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  18867. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  18868. }
  18869. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  18870. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  18871. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  18872. }
  18873. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  18874. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  18875. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  18876. }
  18877. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  18878. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  18879. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  18880. }
  18881. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  18882. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  18883. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  18884. }
  18885. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  18886. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  18887. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  18888. }
  18889. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  18890. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  18891. mesh.setIndices(indicesData);
  18892. }
  18893. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  18894. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  18895. mesh.subMeshes = [];
  18896. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  18897. var materialIndex = subMeshesData[(i * 5) + 0];
  18898. var verticesStart = subMeshesData[(i * 5) + 1];
  18899. var verticesCount = subMeshesData[(i * 5) + 2];
  18900. var indexStart = subMeshesData[(i * 5) + 3];
  18901. var indexCount = subMeshesData[(i * 5) + 4];
  18902. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  18903. }
  18904. }
  18905. }
  18906. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  18907. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  18908. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  18909. if (parsedGeometry.uvs) {
  18910. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  18911. }
  18912. if (parsedGeometry.uvs2) {
  18913. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  18914. }
  18915. if (parsedGeometry.colors) {
  18916. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  18917. }
  18918. if (parsedGeometry.matricesIndices) {
  18919. if (!parsedGeometry.matricesIndices._isExpanded) {
  18920. var floatIndices = [];
  18921. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  18922. var matricesIndex = parsedGeometry.matricesIndices[i];
  18923. floatIndices.push(matricesIndex & 0x000000FF);
  18924. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  18925. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  18926. floatIndices.push(matricesIndex >> 24);
  18927. }
  18928. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  18929. }
  18930. else {
  18931. delete parsedGeometry.matricesIndices._isExpanded;
  18932. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  18933. }
  18934. }
  18935. if (parsedGeometry.matricesWeights) {
  18936. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  18937. }
  18938. mesh.setIndices(parsedGeometry.indices);
  18939. // SubMeshes
  18940. if (parsedGeometry.subMeshes) {
  18941. mesh.subMeshes = [];
  18942. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  18943. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  18944. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  18945. }
  18946. }
  18947. }
  18948. // Flat shading
  18949. if (mesh._shouldGenerateFlatShading) {
  18950. mesh.convertToFlatShadedMesh();
  18951. delete mesh._shouldGenerateFlatShading;
  18952. }
  18953. // Update
  18954. mesh.computeWorldMatrix(true);
  18955. // Octree
  18956. if (scene._selectionOctree) {
  18957. scene._selectionOctree.addMesh(mesh);
  18958. }
  18959. };
  18960. BABYLON.SceneLoader.RegisterPlugin({
  18961. extensions: ".babylon",
  18962. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  18963. var parsedData = JSON.parse(data);
  18964. var loadedSkeletonsIds = [];
  18965. var loadedMaterialsIds = [];
  18966. var hierarchyIds = [];
  18967. for (var index = 0; index < parsedData.meshes.length; index++) {
  18968. var parsedMesh = parsedData.meshes[index];
  18969. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  18970. if (meshesNames instanceof Array) {
  18971. // Remove found mesh name from list.
  18972. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  18973. }
  18974. // Material ?
  18975. if (parsedMesh.materialId) {
  18976. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  18977. if (!materialFound) {
  18978. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  18979. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  18980. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  18981. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18982. var subMatId = parsedMultiMaterial.materials[matIndex];
  18983. loadedMaterialsIds.push(subMatId);
  18984. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  18985. }
  18986. loadedMaterialsIds.push(parsedMultiMaterial.id);
  18987. parseMultiMaterial(parsedMultiMaterial, scene);
  18988. materialFound = true;
  18989. break;
  18990. }
  18991. }
  18992. }
  18993. if (!materialFound) {
  18994. loadedMaterialsIds.push(parsedMesh.materialId);
  18995. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  18996. }
  18997. }
  18998. // Skeleton ?
  18999. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19000. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19001. if (!skeletonAlreadyLoaded) {
  19002. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19003. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19004. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19005. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19006. loadedSkeletonsIds.push(parsedSkeleton.id);
  19007. }
  19008. }
  19009. }
  19010. }
  19011. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19012. meshes.push(mesh);
  19013. }
  19014. }
  19015. for (index = 0; index < scene.meshes.length; index++) {
  19016. var currentMesh = scene.meshes[index];
  19017. if (currentMesh._waitingParentId) {
  19018. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19019. currentMesh._waitingParentId = undefined;
  19020. }
  19021. }
  19022. // Particles
  19023. if (parsedData.particleSystems) {
  19024. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19025. var parsedParticleSystem = parsedData.particleSystems[index];
  19026. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19027. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19028. }
  19029. }
  19030. }
  19031. return true;
  19032. },
  19033. load: function (scene, data, rootUrl) {
  19034. var parsedData = JSON.parse(data);
  19035. // Scene
  19036. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19037. scene.autoClear = parsedData.autoClear;
  19038. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19039. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19040. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19041. // Fog
  19042. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19043. scene.fogMode = parsedData.fogMode;
  19044. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19045. scene.fogStart = parsedData.fogStart;
  19046. scene.fogEnd = parsedData.fogEnd;
  19047. scene.fogDensity = parsedData.fogDensity;
  19048. }
  19049. for (var index = 0; index < parsedData.lights.length; index++) {
  19050. var parsedLight = parsedData.lights[index];
  19051. parseLight(parsedLight, scene);
  19052. }
  19053. // Materials
  19054. if (parsedData.materials) {
  19055. for (index = 0; index < parsedData.materials.length; index++) {
  19056. var parsedMaterial = parsedData.materials[index];
  19057. parseMaterial(parsedMaterial, scene, rootUrl);
  19058. }
  19059. }
  19060. if (parsedData.multiMaterials) {
  19061. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19062. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19063. parseMultiMaterial(parsedMultiMaterial, scene);
  19064. }
  19065. }
  19066. // Skeletons
  19067. if (parsedData.skeletons) {
  19068. for (index = 0; index < parsedData.skeletons.length; index++) {
  19069. var parsedSkeleton = parsedData.skeletons[index];
  19070. parseSkeleton(parsedSkeleton, scene);
  19071. }
  19072. }
  19073. // Geometries
  19074. var geometries = parsedData.geometries;
  19075. if (geometries) {
  19076. // Boxes
  19077. var boxes = geometries.boxes;
  19078. if (boxes) {
  19079. for (index = 0; index < boxes.length; index++) {
  19080. var parsedBox = boxes[index];
  19081. parseBox(parsedBox, scene);
  19082. }
  19083. }
  19084. // Spheres
  19085. var spheres = geometries.spheres;
  19086. if (spheres) {
  19087. for (index = 0; index < spheres.length; index++) {
  19088. var parsedSphere = spheres[index];
  19089. parseSphere(parsedSphere, scene);
  19090. }
  19091. }
  19092. // Cylinders
  19093. var cylinders = geometries.cylinders;
  19094. if (cylinders) {
  19095. for (index = 0; index < cylinders.length; index++) {
  19096. var parsedCylinder = cylinders[index];
  19097. parseCylinder(parsedCylinder, scene);
  19098. }
  19099. }
  19100. // Toruses
  19101. var toruses = geometries.toruses;
  19102. if (toruses) {
  19103. for (index = 0; index < toruses.length; index++) {
  19104. var parsedTorus = toruses[index];
  19105. parseTorus(parsedTorus, scene);
  19106. }
  19107. }
  19108. // Grounds
  19109. var grounds = geometries.grounds;
  19110. if (grounds) {
  19111. for (index = 0; index < grounds.length; index++) {
  19112. var parsedGround = grounds[index];
  19113. parseGround(parsedGround, scene);
  19114. }
  19115. }
  19116. // Planes
  19117. var planes = geometries.planes;
  19118. if (planes) {
  19119. for (index = 0; index < planes.length; index++) {
  19120. var parsedPlane = planes[index];
  19121. parsePlane(parsedPlane, scene);
  19122. }
  19123. }
  19124. // TorusKnots
  19125. var torusKnots = geometries.torusKnots;
  19126. if (torusKnots) {
  19127. for (index = 0; index < torusKnots.length; index++) {
  19128. var parsedTorusKnot = torusKnots[index];
  19129. parseTorusKnot(parsedTorusKnot, scene);
  19130. }
  19131. }
  19132. // VertexData
  19133. var vertexData = geometries.vertexData;
  19134. if (vertexData) {
  19135. for (index = 0; index < vertexData.length; index++) {
  19136. var parsedVertexData = vertexData[index];
  19137. parseVertexData(parsedVertexData, scene, rootUrl);
  19138. }
  19139. }
  19140. }
  19141. for (index = 0; index < parsedData.meshes.length; index++) {
  19142. var parsedMesh = parsedData.meshes[index];
  19143. parseMesh(parsedMesh, scene, rootUrl);
  19144. }
  19145. for (index = 0; index < parsedData.cameras.length; index++) {
  19146. var parsedCamera = parsedData.cameras[index];
  19147. parseCamera(parsedCamera, scene);
  19148. }
  19149. if (parsedData.activeCameraID) {
  19150. scene.setActiveCameraByID(parsedData.activeCameraID);
  19151. }
  19152. for (index = 0; index < scene.cameras.length; index++) {
  19153. var camera = scene.cameras[index];
  19154. if (camera._waitingParentId) {
  19155. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19156. camera._waitingParentId = undefined;
  19157. }
  19158. }
  19159. for (index = 0; index < scene.lights.length; index++) {
  19160. var light = scene.lights[index];
  19161. if (light._waitingParentId) {
  19162. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19163. light._waitingParentId = undefined;
  19164. }
  19165. }
  19166. for (index = 0; index < scene.meshes.length; index++) {
  19167. var mesh = scene.meshes[index];
  19168. if (mesh._waitingParentId) {
  19169. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19170. mesh._waitingParentId = undefined;
  19171. }
  19172. if (mesh._waitingActions) {
  19173. parseActions(mesh._waitingActions, mesh, scene);
  19174. mesh._waitingActions = undefined;
  19175. }
  19176. }
  19177. // Particles Systems
  19178. if (parsedData.particleSystems) {
  19179. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19180. var parsedParticleSystem = parsedData.particleSystems[index];
  19181. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19182. }
  19183. }
  19184. // Lens flares
  19185. if (parsedData.lensFlareSystems) {
  19186. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19187. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19188. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19189. }
  19190. }
  19191. // Shadows
  19192. if (parsedData.shadowGenerators) {
  19193. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  19194. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  19195. parseShadowGenerator(parsedShadowGenerator, scene);
  19196. }
  19197. }
  19198. // Sounds
  19199. if (parsedData.sounds && BABYLON.Engine.audioEngine.canUseWebAudio) {
  19200. for (index = 0; index < parsedData.sounds.length; index++) {
  19201. var parsedSound = parsedData.sounds[index];
  19202. parseSound(parsedSound, scene, rootUrl);
  19203. }
  19204. }
  19205. // Actions (scene)
  19206. if (parsedData.actions) {
  19207. parseActions(parsedData.actions, null, scene);
  19208. }
  19209. // Finish
  19210. return true;
  19211. }
  19212. });
  19213. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  19214. })(BABYLON || (BABYLON = {}));
  19215. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  19216. (function (BABYLON) {
  19217. // Unique ID when we import meshes from Babylon to CSG
  19218. var currentCSGMeshId = 0;
  19219. // # class Vertex
  19220. // Represents a vertex of a polygon. Use your own vertex class instead of this
  19221. // one to provide additional features like texture coordinates and vertex
  19222. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  19223. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  19224. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  19225. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  19226. // is not used anywhere else.
  19227. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  19228. var Vertex = (function () {
  19229. function Vertex(pos, normal, uv) {
  19230. this.pos = pos;
  19231. this.normal = normal;
  19232. this.uv = uv;
  19233. }
  19234. Vertex.prototype.clone = function () {
  19235. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  19236. };
  19237. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  19238. // orientation of a polygon is flipped.
  19239. Vertex.prototype.flip = function () {
  19240. this.normal = this.normal.scale(-1);
  19241. };
  19242. // Create a new vertex between this vertex and `other` by linearly
  19243. // interpolating all properties using a parameter of `t`. Subclasses should
  19244. // override this to interpolate additional properties.
  19245. Vertex.prototype.interpolate = function (other, t) {
  19246. 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));
  19247. };
  19248. return Vertex;
  19249. })();
  19250. // # class Plane
  19251. // Represents a plane in 3D space.
  19252. var Plane = (function () {
  19253. function Plane(normal, w) {
  19254. this.normal = normal;
  19255. this.w = w;
  19256. }
  19257. Plane.FromPoints = function (a, b, c) {
  19258. var v0 = c.subtract(a);
  19259. var v1 = b.subtract(a);
  19260. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  19261. return null;
  19262. }
  19263. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  19264. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  19265. };
  19266. Plane.prototype.clone = function () {
  19267. return new Plane(this.normal.clone(), this.w);
  19268. };
  19269. Plane.prototype.flip = function () {
  19270. this.normal.scaleInPlace(-1);
  19271. this.w = -this.w;
  19272. };
  19273. // Split `polygon` by this plane if needed, then put the polygon or polygon
  19274. // fragments in the appropriate lists. Coplanar polygons go into either
  19275. // `coplanarFront` or `coplanarBack` depending on their orientation with
  19276. // respect to this plane. Polygons in front or in back of this plane go into
  19277. // either `front` or `back`.
  19278. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  19279. var COPLANAR = 0;
  19280. var FRONT = 1;
  19281. var BACK = 2;
  19282. var SPANNING = 3;
  19283. // Classify each point as well as the entire polygon into one of the above
  19284. // four classes.
  19285. var polygonType = 0;
  19286. var types = [];
  19287. for (var i = 0; i < polygon.vertices.length; i++) {
  19288. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  19289. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  19290. polygonType |= type;
  19291. types.push(type);
  19292. }
  19293. switch (polygonType) {
  19294. case COPLANAR:
  19295. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  19296. break;
  19297. case FRONT:
  19298. front.push(polygon);
  19299. break;
  19300. case BACK:
  19301. back.push(polygon);
  19302. break;
  19303. case SPANNING:
  19304. var f = [], b = [];
  19305. for (i = 0; i < polygon.vertices.length; i++) {
  19306. var j = (i + 1) % polygon.vertices.length;
  19307. var ti = types[i], tj = types[j];
  19308. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  19309. if (ti != BACK)
  19310. f.push(vi);
  19311. if (ti != FRONT)
  19312. b.push(ti != BACK ? vi.clone() : vi);
  19313. if ((ti | tj) == SPANNING) {
  19314. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  19315. var v = vi.interpolate(vj, t);
  19316. f.push(v);
  19317. b.push(v.clone());
  19318. }
  19319. }
  19320. if (f.length >= 3) {
  19321. var poly = new Polygon(f, polygon.shared);
  19322. if (poly.plane)
  19323. front.push(poly);
  19324. }
  19325. if (b.length >= 3) {
  19326. poly = new Polygon(b, polygon.shared);
  19327. if (poly.plane)
  19328. back.push(poly);
  19329. }
  19330. break;
  19331. }
  19332. };
  19333. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  19334. // point is on the plane.
  19335. Plane.EPSILON = 1e-5;
  19336. return Plane;
  19337. })();
  19338. // # class Polygon
  19339. // Represents a convex polygon. The vertices used to initialize a polygon must
  19340. // be coplanar and form a convex loop.
  19341. //
  19342. // Each convex polygon has a `shared` property, which is shared between all
  19343. // polygons that are clones of each other or were split from the same polygon.
  19344. // This can be used to define per-polygon properties (such as surface color).
  19345. var Polygon = (function () {
  19346. function Polygon(vertices, shared) {
  19347. this.vertices = vertices;
  19348. this.shared = shared;
  19349. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  19350. }
  19351. Polygon.prototype.clone = function () {
  19352. var vertices = this.vertices.map(function (v) { return v.clone(); });
  19353. return new Polygon(vertices, this.shared);
  19354. };
  19355. Polygon.prototype.flip = function () {
  19356. this.vertices.reverse().map(function (v) {
  19357. v.flip();
  19358. });
  19359. this.plane.flip();
  19360. };
  19361. return Polygon;
  19362. })();
  19363. // # class Node
  19364. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  19365. // by picking a polygon to split along. That polygon (and all other coplanar
  19366. // polygons) are added directly to that node and the other polygons are added to
  19367. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  19368. // no distinction between internal and leaf nodes.
  19369. var Node = (function () {
  19370. function Node(polygons) {
  19371. this.plane = null;
  19372. this.front = null;
  19373. this.back = null;
  19374. this.polygons = [];
  19375. if (polygons) {
  19376. this.build(polygons);
  19377. }
  19378. }
  19379. Node.prototype.clone = function () {
  19380. var node = new Node();
  19381. node.plane = this.plane && this.plane.clone();
  19382. node.front = this.front && this.front.clone();
  19383. node.back = this.back && this.back.clone();
  19384. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  19385. return node;
  19386. };
  19387. // Convert solid space to empty space and empty space to solid space.
  19388. Node.prototype.invert = function () {
  19389. for (var i = 0; i < this.polygons.length; i++) {
  19390. this.polygons[i].flip();
  19391. }
  19392. if (this.plane) {
  19393. this.plane.flip();
  19394. }
  19395. if (this.front) {
  19396. this.front.invert();
  19397. }
  19398. if (this.back) {
  19399. this.back.invert();
  19400. }
  19401. var temp = this.front;
  19402. this.front = this.back;
  19403. this.back = temp;
  19404. };
  19405. // Recursively remove all polygons in `polygons` that are inside this BSP
  19406. // tree.
  19407. Node.prototype.clipPolygons = function (polygons) {
  19408. if (!this.plane)
  19409. return polygons.slice();
  19410. var front = [], back = [];
  19411. for (var i = 0; i < polygons.length; i++) {
  19412. this.plane.splitPolygon(polygons[i], front, back, front, back);
  19413. }
  19414. if (this.front) {
  19415. front = this.front.clipPolygons(front);
  19416. }
  19417. if (this.back) {
  19418. back = this.back.clipPolygons(back);
  19419. }
  19420. else {
  19421. back = [];
  19422. }
  19423. return front.concat(back);
  19424. };
  19425. // Remove all polygons in this BSP tree that are inside the other BSP tree
  19426. // `bsp`.
  19427. Node.prototype.clipTo = function (bsp) {
  19428. this.polygons = bsp.clipPolygons(this.polygons);
  19429. if (this.front)
  19430. this.front.clipTo(bsp);
  19431. if (this.back)
  19432. this.back.clipTo(bsp);
  19433. };
  19434. // Return a list of all polygons in this BSP tree.
  19435. Node.prototype.allPolygons = function () {
  19436. var polygons = this.polygons.slice();
  19437. if (this.front)
  19438. polygons = polygons.concat(this.front.allPolygons());
  19439. if (this.back)
  19440. polygons = polygons.concat(this.back.allPolygons());
  19441. return polygons;
  19442. };
  19443. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  19444. // new polygons are filtered down to the bottom of the tree and become new
  19445. // nodes there. Each set of polygons is partitioned using the first polygon
  19446. // (no heuristic is used to pick a good split).
  19447. Node.prototype.build = function (polygons) {
  19448. if (!polygons.length)
  19449. return;
  19450. if (!this.plane)
  19451. this.plane = polygons[0].plane.clone();
  19452. var front = [], back = [];
  19453. for (var i = 0; i < polygons.length; i++) {
  19454. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  19455. }
  19456. if (front.length) {
  19457. if (!this.front)
  19458. this.front = new Node();
  19459. this.front.build(front);
  19460. }
  19461. if (back.length) {
  19462. if (!this.back)
  19463. this.back = new Node();
  19464. this.back.build(back);
  19465. }
  19466. };
  19467. return Node;
  19468. })();
  19469. var CSG = (function () {
  19470. function CSG() {
  19471. this.polygons = new Array();
  19472. }
  19473. // Convert BABYLON.Mesh to BABYLON.CSG
  19474. CSG.FromMesh = function (mesh) {
  19475. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  19476. if (mesh instanceof BABYLON.Mesh) {
  19477. mesh.computeWorldMatrix(true);
  19478. var matrix = mesh.getWorldMatrix();
  19479. var meshPosition = mesh.position.clone();
  19480. var meshRotation = mesh.rotation.clone();
  19481. var meshScaling = mesh.scaling.clone();
  19482. }
  19483. else {
  19484. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  19485. }
  19486. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19487. var subMeshes = mesh.subMeshes;
  19488. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  19489. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  19490. vertices = [];
  19491. for (var j = 0; j < 3; j++) {
  19492. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  19493. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  19494. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  19495. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  19496. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  19497. vertex = new Vertex(position, normal, uv);
  19498. vertices.push(vertex);
  19499. }
  19500. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  19501. // To handle the case of degenerated triangle
  19502. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  19503. if (polygon.plane)
  19504. polygons.push(polygon);
  19505. }
  19506. }
  19507. var csg = CSG.FromPolygons(polygons);
  19508. csg.matrix = matrix;
  19509. csg.position = meshPosition;
  19510. csg.rotation = meshRotation;
  19511. csg.scaling = meshScaling;
  19512. currentCSGMeshId++;
  19513. return csg;
  19514. };
  19515. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  19516. CSG.FromPolygons = function (polygons) {
  19517. var csg = new BABYLON.CSG();
  19518. csg.polygons = polygons;
  19519. return csg;
  19520. };
  19521. CSG.prototype.clone = function () {
  19522. var csg = new BABYLON.CSG();
  19523. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  19524. csg.copyTransformAttributes(this);
  19525. return csg;
  19526. };
  19527. CSG.prototype.toPolygons = function () {
  19528. return this.polygons;
  19529. };
  19530. CSG.prototype.union = function (csg) {
  19531. var a = new Node(this.clone().polygons);
  19532. var b = new Node(csg.clone().polygons);
  19533. a.clipTo(b);
  19534. b.clipTo(a);
  19535. b.invert();
  19536. b.clipTo(a);
  19537. b.invert();
  19538. a.build(b.allPolygons());
  19539. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19540. };
  19541. CSG.prototype.unionInPlace = function (csg) {
  19542. var a = new Node(this.polygons);
  19543. var b = new Node(csg.polygons);
  19544. a.clipTo(b);
  19545. b.clipTo(a);
  19546. b.invert();
  19547. b.clipTo(a);
  19548. b.invert();
  19549. a.build(b.allPolygons());
  19550. this.polygons = a.allPolygons();
  19551. };
  19552. CSG.prototype.subtract = function (csg) {
  19553. var a = new Node(this.clone().polygons);
  19554. var b = new Node(csg.clone().polygons);
  19555. a.invert();
  19556. a.clipTo(b);
  19557. b.clipTo(a);
  19558. b.invert();
  19559. b.clipTo(a);
  19560. b.invert();
  19561. a.build(b.allPolygons());
  19562. a.invert();
  19563. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19564. };
  19565. CSG.prototype.subtractInPlace = function (csg) {
  19566. var a = new Node(this.polygons);
  19567. var b = new Node(csg.polygons);
  19568. a.invert();
  19569. a.clipTo(b);
  19570. b.clipTo(a);
  19571. b.invert();
  19572. b.clipTo(a);
  19573. b.invert();
  19574. a.build(b.allPolygons());
  19575. a.invert();
  19576. this.polygons = a.allPolygons();
  19577. };
  19578. CSG.prototype.intersect = function (csg) {
  19579. var a = new Node(this.clone().polygons);
  19580. var b = new Node(csg.clone().polygons);
  19581. a.invert();
  19582. b.clipTo(a);
  19583. b.invert();
  19584. a.clipTo(b);
  19585. b.clipTo(a);
  19586. a.build(b.allPolygons());
  19587. a.invert();
  19588. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19589. };
  19590. CSG.prototype.intersectInPlace = function (csg) {
  19591. var a = new Node(this.polygons);
  19592. var b = new Node(csg.polygons);
  19593. a.invert();
  19594. b.clipTo(a);
  19595. b.invert();
  19596. a.clipTo(b);
  19597. b.clipTo(a);
  19598. a.build(b.allPolygons());
  19599. a.invert();
  19600. this.polygons = a.allPolygons();
  19601. };
  19602. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  19603. // not modified.
  19604. CSG.prototype.inverse = function () {
  19605. var csg = this.clone();
  19606. csg.inverseInPlace();
  19607. return csg;
  19608. };
  19609. CSG.prototype.inverseInPlace = function () {
  19610. this.polygons.map(function (p) {
  19611. p.flip();
  19612. });
  19613. };
  19614. // This is used to keep meshes transformations so they can be restored
  19615. // when we build back a Babylon Mesh
  19616. // NB : All CSG operations are performed in world coordinates
  19617. CSG.prototype.copyTransformAttributes = function (csg) {
  19618. this.matrix = csg.matrix;
  19619. this.position = csg.position;
  19620. this.rotation = csg.rotation;
  19621. this.scaling = csg.scaling;
  19622. return this;
  19623. };
  19624. // Build Raw mesh from CSG
  19625. // Coordinates here are in world space
  19626. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  19627. var matrix = this.matrix.clone();
  19628. matrix.invert();
  19629. 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;
  19630. if (keepSubMeshes) {
  19631. // Sort Polygons, since subMeshes are indices range
  19632. polygons.sort(function (a, b) {
  19633. if (a.shared.meshId === b.shared.meshId) {
  19634. return a.shared.subMeshId - b.shared.subMeshId;
  19635. }
  19636. else {
  19637. return a.shared.meshId - b.shared.meshId;
  19638. }
  19639. });
  19640. }
  19641. for (var i = 0, il = polygons.length; i < il; i++) {
  19642. polygon = polygons[i];
  19643. // Building SubMeshes
  19644. if (!subMesh_dict[polygon.shared.meshId]) {
  19645. subMesh_dict[polygon.shared.meshId] = {};
  19646. }
  19647. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  19648. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  19649. indexStart: +Infinity,
  19650. indexEnd: -Infinity,
  19651. materialIndex: polygon.shared.materialIndex
  19652. };
  19653. }
  19654. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  19655. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  19656. polygonIndices[0] = 0;
  19657. polygonIndices[1] = j - 1;
  19658. polygonIndices[2] = j;
  19659. for (var k = 0; k < 3; k++) {
  19660. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  19661. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  19662. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  19663. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  19664. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  19665. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  19666. // Check if 2 points can be merged
  19667. 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)) {
  19668. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  19669. uvs.push(uv.x, uv.y);
  19670. normals.push(normal.x, normal.y, normal.z);
  19671. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  19672. }
  19673. indices.push(vertex_idx);
  19674. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  19675. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  19676. currentIndex++;
  19677. }
  19678. }
  19679. }
  19680. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  19681. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19682. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  19683. mesh.setIndices(indices);
  19684. if (keepSubMeshes) {
  19685. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  19686. var materialIndexOffset = 0, materialMaxIndex;
  19687. mesh.subMeshes.length = 0;
  19688. for (var m in subMesh_dict) {
  19689. materialMaxIndex = -1;
  19690. for (var sm in subMesh_dict[m]) {
  19691. subMesh_obj = subMesh_dict[m][sm];
  19692. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  19693. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  19694. }
  19695. materialIndexOffset += ++materialMaxIndex;
  19696. }
  19697. }
  19698. return mesh;
  19699. };
  19700. // Build Mesh from CSG taking material and transforms into account
  19701. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  19702. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  19703. mesh.material = material;
  19704. mesh.position.copyFrom(this.position);
  19705. mesh.rotation.copyFrom(this.rotation);
  19706. mesh.scaling.copyFrom(this.scaling);
  19707. mesh.computeWorldMatrix(true);
  19708. return mesh;
  19709. };
  19710. return CSG;
  19711. })();
  19712. BABYLON.CSG = CSG;
  19713. })(BABYLON || (BABYLON = {}));
  19714. //# sourceMappingURL=babylon.csg.js.map
  19715. var BABYLON;
  19716. (function (BABYLON) {
  19717. var OculusDistortionCorrectionPostProcess = (function (_super) {
  19718. __extends(OculusDistortionCorrectionPostProcess, _super);
  19719. //ANY
  19720. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  19721. var _this = this;
  19722. _super.call(this, name, "oculusDistortionCorrection", [
  19723. 'LensCenter',
  19724. 'Scale',
  19725. 'ScaleIn',
  19726. 'HmdWarpParam'
  19727. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  19728. this._isRightEye = isRightEye;
  19729. this._distortionFactors = cameraSettings.DistortionK;
  19730. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  19731. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  19732. this.onSizeChanged = function () {
  19733. _this.aspectRatio = _this.width * .5 / _this.height;
  19734. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  19735. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  19736. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  19737. };
  19738. this.onApply = function (effect) {
  19739. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  19740. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  19741. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  19742. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  19743. };
  19744. }
  19745. return OculusDistortionCorrectionPostProcess;
  19746. })(BABYLON.PostProcess);
  19747. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  19748. })(BABYLON || (BABYLON = {}));
  19749. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  19750. // 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
  19751. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  19752. var BABYLON;
  19753. (function (BABYLON) {
  19754. (function (JoystickAxis) {
  19755. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  19756. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  19757. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  19758. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  19759. var JoystickAxis = BABYLON.JoystickAxis;
  19760. var VirtualJoystick = (function () {
  19761. function VirtualJoystick(leftJoystick) {
  19762. var _this = this;
  19763. if (leftJoystick) {
  19764. this._leftJoystick = true;
  19765. }
  19766. else {
  19767. this._leftJoystick = false;
  19768. }
  19769. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  19770. VirtualJoystick._globalJoystickIndex++;
  19771. // By default left & right arrow keys are moving the X
  19772. // and up & down keys are moving the Y
  19773. this._axisTargetedByLeftAndRight = 0 /* X */;
  19774. this._axisTargetedByUpAndDown = 1 /* Y */;
  19775. this.reverseLeftRight = false;
  19776. this.reverseUpDown = false;
  19777. // collections of pointers
  19778. this._touches = new BABYLON.VirtualJoystick.Collection();
  19779. this.deltaPosition = BABYLON.Vector3.Zero();
  19780. this._joystickSensibility = 25;
  19781. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19782. this._rotationSpeed = 25;
  19783. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  19784. this._rotateOnAxisRelativeToMesh = false;
  19785. // injecting a canvas element on top of the canvas 3D game
  19786. if (!VirtualJoystick.vjCanvas) {
  19787. window.addEventListener("resize", function () {
  19788. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19789. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19790. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  19791. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  19792. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  19793. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  19794. }, false);
  19795. VirtualJoystick.vjCanvas = document.createElement("canvas");
  19796. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19797. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19798. VirtualJoystick.vjCanvas.width = window.innerWidth;
  19799. VirtualJoystick.vjCanvas.height = window.innerHeight;
  19800. VirtualJoystick.vjCanvas.style.width = "100%";
  19801. VirtualJoystick.vjCanvas.style.height = "100%";
  19802. VirtualJoystick.vjCanvas.style.position = "absolute";
  19803. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  19804. VirtualJoystick.vjCanvas.style.top = "0px";
  19805. VirtualJoystick.vjCanvas.style.left = "0px";
  19806. VirtualJoystick.vjCanvas.style.zIndex = "5";
  19807. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  19808. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  19809. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  19810. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19811. document.body.appendChild(VirtualJoystick.vjCanvas);
  19812. }
  19813. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  19814. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  19815. this.pressed = false;
  19816. // default joystick color
  19817. this._joystickColor = "cyan";
  19818. this._joystickPointerID = -1;
  19819. // current joystick position
  19820. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  19821. // origin joystick position
  19822. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  19823. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  19824. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  19825. _this._onPointerDown(evt);
  19826. }, false);
  19827. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  19828. _this._onPointerMove(evt);
  19829. }, false);
  19830. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  19831. _this._onPointerUp(evt);
  19832. }, false);
  19833. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  19834. _this._onPointerUp(evt);
  19835. }, false);
  19836. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  19837. evt.preventDefault(); // Disables system menu
  19838. }, false);
  19839. requestAnimationFrame(function () {
  19840. _this._drawVirtualJoystick();
  19841. });
  19842. }
  19843. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  19844. this._joystickSensibility = newJoystickSensibility;
  19845. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19846. };
  19847. VirtualJoystick.prototype._onPointerDown = function (e) {
  19848. var positionOnScreenCondition;
  19849. e.preventDefault();
  19850. if (this._leftJoystick === true) {
  19851. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  19852. }
  19853. else {
  19854. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  19855. }
  19856. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  19857. // First contact will be dedicated to the virtual joystick
  19858. this._joystickPointerID = e.pointerId;
  19859. this._joystickPointerStartPos.x = e.clientX;
  19860. this._joystickPointerStartPos.y = e.clientY;
  19861. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  19862. this._deltaJoystickVector.x = 0;
  19863. this._deltaJoystickVector.y = 0;
  19864. this.pressed = true;
  19865. this._touches.add(e.pointerId.toString(), e);
  19866. }
  19867. else {
  19868. // You can only trigger the action buttons with a joystick declared
  19869. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  19870. this._action();
  19871. this._touches.add(e.pointerId.toString(), e);
  19872. }
  19873. }
  19874. };
  19875. VirtualJoystick.prototype._onPointerMove = function (e) {
  19876. // If the current pointer is the one associated to the joystick (first touch contact)
  19877. if (this._joystickPointerID == e.pointerId) {
  19878. this._joystickPointerPos.x = e.clientX;
  19879. this._joystickPointerPos.y = e.clientY;
  19880. this._deltaJoystickVector = this._joystickPointerPos.clone();
  19881. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  19882. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  19883. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  19884. switch (this._axisTargetedByLeftAndRight) {
  19885. case 0 /* X */:
  19886. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  19887. break;
  19888. case 1 /* Y */:
  19889. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  19890. break;
  19891. case 2 /* Z */:
  19892. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  19893. break;
  19894. }
  19895. var directionUpDown = this.reverseUpDown ? 1 : -1;
  19896. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  19897. switch (this._axisTargetedByUpAndDown) {
  19898. case 0 /* X */:
  19899. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  19900. break;
  19901. case 1 /* Y */:
  19902. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  19903. break;
  19904. case 2 /* Z */:
  19905. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  19906. break;
  19907. }
  19908. }
  19909. else {
  19910. if (this._touches.item(e.pointerId.toString())) {
  19911. this._touches.item(e.pointerId.toString()).x = e.clientX;
  19912. this._touches.item(e.pointerId.toString()).y = e.clientY;
  19913. }
  19914. }
  19915. };
  19916. VirtualJoystick.prototype._onPointerUp = function (e) {
  19917. this._clearCanvas();
  19918. if (this._joystickPointerID == e.pointerId) {
  19919. this._joystickPointerID = -1;
  19920. this.pressed = false;
  19921. }
  19922. this._deltaJoystickVector.x = 0;
  19923. this._deltaJoystickVector.y = 0;
  19924. this._touches.remove(e.pointerId.toString());
  19925. };
  19926. /**
  19927. * Change the color of the virtual joystick
  19928. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  19929. */
  19930. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  19931. this._joystickColor = newColor;
  19932. };
  19933. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  19934. this._action = action;
  19935. };
  19936. // Define which axis you'd like to control for left & right
  19937. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  19938. switch (axis) {
  19939. case 0 /* X */:
  19940. case 1 /* Y */:
  19941. case 2 /* Z */:
  19942. this._axisTargetedByLeftAndRight = axis;
  19943. break;
  19944. default:
  19945. this._axisTargetedByLeftAndRight = 0 /* X */;
  19946. break;
  19947. }
  19948. };
  19949. // Define which axis you'd like to control for up & down
  19950. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  19951. switch (axis) {
  19952. case 0 /* X */:
  19953. case 1 /* Y */:
  19954. case 2 /* Z */:
  19955. this._axisTargetedByUpAndDown = axis;
  19956. break;
  19957. default:
  19958. this._axisTargetedByUpAndDown = 1 /* Y */;
  19959. break;
  19960. }
  19961. };
  19962. VirtualJoystick.prototype._clearCanvas = function () {
  19963. if (this._leftJoystick) {
  19964. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  19965. }
  19966. else {
  19967. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  19968. }
  19969. };
  19970. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  19971. var _this = this;
  19972. if (this.pressed) {
  19973. this._clearCanvas();
  19974. this._touches.forEach(function (touch) {
  19975. if (touch.pointerId === _this._joystickPointerID) {
  19976. VirtualJoystick.vjCanvasContext.beginPath();
  19977. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19978. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19979. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  19980. VirtualJoystick.vjCanvasContext.stroke();
  19981. VirtualJoystick.vjCanvasContext.beginPath();
  19982. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19983. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19984. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  19985. VirtualJoystick.vjCanvasContext.stroke();
  19986. VirtualJoystick.vjCanvasContext.beginPath();
  19987. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19988. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  19989. VirtualJoystick.vjCanvasContext.stroke();
  19990. }
  19991. else {
  19992. VirtualJoystick.vjCanvasContext.beginPath();
  19993. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  19994. VirtualJoystick.vjCanvasContext.beginPath();
  19995. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  19996. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19997. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  19998. VirtualJoystick.vjCanvasContext.stroke();
  19999. }
  20000. ;
  20001. });
  20002. }
  20003. requestAnimationFrame(function () {
  20004. _this._drawVirtualJoystick();
  20005. });
  20006. };
  20007. VirtualJoystick.prototype.releaseCanvas = function () {
  20008. if (VirtualJoystick.vjCanvas) {
  20009. document.body.removeChild(VirtualJoystick.vjCanvas);
  20010. VirtualJoystick.vjCanvas = null;
  20011. }
  20012. };
  20013. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  20014. VirtualJoystick._globalJoystickIndex = 0;
  20015. return VirtualJoystick;
  20016. })();
  20017. BABYLON.VirtualJoystick = VirtualJoystick;
  20018. })(BABYLON || (BABYLON = {}));
  20019. var BABYLON;
  20020. (function (BABYLON) {
  20021. var VirtualJoystick;
  20022. (function (VirtualJoystick) {
  20023. var Collection = (function () {
  20024. function Collection() {
  20025. this._count = 0;
  20026. this._collection = new Array();
  20027. }
  20028. Collection.prototype.Count = function () {
  20029. return this._count;
  20030. };
  20031. Collection.prototype.add = function (key, item) {
  20032. if (this._collection[key] != undefined) {
  20033. return undefined;
  20034. }
  20035. this._collection[key] = item;
  20036. return ++this._count;
  20037. };
  20038. Collection.prototype.remove = function (key) {
  20039. if (this._collection[key] == undefined) {
  20040. return undefined;
  20041. }
  20042. delete this._collection[key];
  20043. return --this._count;
  20044. };
  20045. Collection.prototype.item = function (key) {
  20046. return this._collection[key];
  20047. };
  20048. Collection.prototype.forEach = function (block) {
  20049. var key;
  20050. for (key in this._collection) {
  20051. if (this._collection.hasOwnProperty(key)) {
  20052. block(this._collection[key]);
  20053. }
  20054. }
  20055. };
  20056. return Collection;
  20057. })();
  20058. VirtualJoystick.Collection = Collection;
  20059. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20060. })(BABYLON || (BABYLON = {}));
  20061. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20062. var BABYLON;
  20063. (function (BABYLON) {
  20064. var OculusRiftDevKit2013_Metric = {
  20065. HResolution: 1280,
  20066. VResolution: 800,
  20067. HScreenSize: 0.149759993,
  20068. VScreenSize: 0.0935999975,
  20069. VScreenCenter: 0.0467999987,
  20070. EyeToScreenDistance: 0.0410000011,
  20071. LensSeparationDistance: 0.0635000020,
  20072. InterpupillaryDistance: 0.0640000030,
  20073. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20074. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20075. PostProcessScaleFactor: 1.714605507808412,
  20076. LensCenterOffset: 0.151976421
  20077. };
  20078. var _OculusInnerCamera = (function (_super) {
  20079. __extends(_OculusInnerCamera, _super);
  20080. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20081. _super.call(this, name, position, scene);
  20082. this._workMatrix = new BABYLON.Matrix();
  20083. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20084. // Constants
  20085. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20086. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20087. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20088. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20089. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20090. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20091. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20092. // Postprocess
  20093. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20094. }
  20095. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  20096. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20097. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20098. return this._projectionMatrix;
  20099. };
  20100. _OculusInnerCamera.prototype._getViewMatrix = function () {
  20101. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20102. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20103. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20104. // Computing target and final matrix
  20105. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20106. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20107. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20108. return this._viewMatrix;
  20109. };
  20110. return _OculusInnerCamera;
  20111. })(BABYLON.FreeCamera);
  20112. var OculusCamera = (function (_super) {
  20113. __extends(OculusCamera, _super);
  20114. function OculusCamera(name, position, scene) {
  20115. _super.call(this, name, position, scene);
  20116. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  20117. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  20118. this.subCameras.push(this._leftCamera);
  20119. this.subCameras.push(this._rightCamera);
  20120. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20121. }
  20122. OculusCamera.prototype._update = function () {
  20123. this._leftCamera.position.copyFrom(this.position);
  20124. this._rightCamera.position.copyFrom(this.position);
  20125. this._updateCamera(this._leftCamera);
  20126. this._updateCamera(this._rightCamera);
  20127. _super.prototype._update.call(this);
  20128. };
  20129. OculusCamera.prototype._updateCamera = function (camera) {
  20130. camera.minZ = this.minZ;
  20131. camera.maxZ = this.maxZ;
  20132. camera.rotation.x = this.rotation.x;
  20133. camera.rotation.y = this.rotation.y;
  20134. camera.rotation.z = this.rotation.z;
  20135. };
  20136. // Oculus events
  20137. OculusCamera.prototype._onOrientationEvent = function (evt) {
  20138. var yaw = evt.alpha / 180 * Math.PI;
  20139. var pitch = evt.beta / 180 * Math.PI;
  20140. var roll = evt.gamma / 180 * Math.PI;
  20141. if (!this._offsetOrientation) {
  20142. this._offsetOrientation = {
  20143. yaw: yaw,
  20144. pitch: pitch,
  20145. roll: roll
  20146. };
  20147. return;
  20148. }
  20149. else {
  20150. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20151. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20152. this.rotation.z += this._offsetOrientation.roll - roll;
  20153. this._offsetOrientation.yaw = yaw;
  20154. this._offsetOrientation.pitch = pitch;
  20155. this._offsetOrientation.roll = roll;
  20156. }
  20157. };
  20158. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  20159. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20160. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20161. };
  20162. OculusCamera.prototype.detachControl = function (element) {
  20163. _super.prototype.detachControl.call(this, element);
  20164. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20165. };
  20166. return OculusCamera;
  20167. })(BABYLON.FreeCamera);
  20168. BABYLON.OculusCamera = OculusCamera;
  20169. })(BABYLON || (BABYLON = {}));
  20170. //# sourceMappingURL=babylon.oculusCamera.js.map
  20171. var BABYLON;
  20172. (function (BABYLON) {
  20173. var OculusRiftDevKit2013_Metric = {
  20174. HResolution: 1280,
  20175. VResolution: 800,
  20176. HScreenSize: 0.149759993,
  20177. VScreenSize: 0.0935999975,
  20178. VScreenCenter: 0.0467999987,
  20179. EyeToScreenDistance: 0.0410000011,
  20180. LensSeparationDistance: 0.0635000020,
  20181. InterpupillaryDistance: 0.0640000030,
  20182. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20183. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20184. PostProcessScaleFactor: 1.714605507808412,
  20185. LensCenterOffset: 0.151976421
  20186. };
  20187. var _OculusInnerGamepadCamera = (function (_super) {
  20188. __extends(_OculusInnerGamepadCamera, _super);
  20189. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  20190. _super.call(this, name, position, scene);
  20191. this._workMatrix = new BABYLON.Matrix();
  20192. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20193. // Constants
  20194. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20195. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20196. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20197. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20198. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20199. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20200. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20201. // Postprocess
  20202. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20203. }
  20204. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  20205. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20206. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20207. return this._projectionMatrix;
  20208. };
  20209. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  20210. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20211. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20212. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20213. // Computing target and final matrix
  20214. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20215. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20216. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20217. return this._viewMatrix;
  20218. };
  20219. return _OculusInnerGamepadCamera;
  20220. })(BABYLON.FreeCamera);
  20221. var OculusGamepadCamera = (function (_super) {
  20222. __extends(OculusGamepadCamera, _super);
  20223. function OculusGamepadCamera(name, position, scene) {
  20224. var _this = this;
  20225. _super.call(this, name, position, scene);
  20226. this.angularSensibility = 200;
  20227. this.moveSensibility = 75;
  20228. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  20229. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  20230. this.subCameras.push(this._leftCamera);
  20231. this.subCameras.push(this._rightCamera);
  20232. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20233. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20234. _this._onNewGameConnected(gamepad);
  20235. });
  20236. }
  20237. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20238. // Only the first gamepad can control the camera
  20239. if (gamepad.index === 0) {
  20240. this._gamepad = gamepad;
  20241. }
  20242. };
  20243. OculusGamepadCamera.prototype._update = function () {
  20244. this._leftCamera.position.copyFrom(this.position);
  20245. this._rightCamera.position.copyFrom(this.position);
  20246. this._updateCamera(this._leftCamera);
  20247. this._updateCamera(this._rightCamera);
  20248. _super.prototype._update.call(this);
  20249. };
  20250. OculusGamepadCamera.prototype._checkInputs = function () {
  20251. if (!this._gamepad) {
  20252. return;
  20253. }
  20254. var LSValues = this._gamepad.leftStick;
  20255. var normalizedLX = LSValues.x / this.moveSensibility;
  20256. var normalizedLY = LSValues.y / this.moveSensibility;
  20257. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20258. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20259. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20260. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20261. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20262. };
  20263. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  20264. camera.minZ = this.minZ;
  20265. camera.maxZ = this.maxZ;
  20266. camera.rotation.x = this.rotation.x;
  20267. camera.rotation.y = this.rotation.y;
  20268. camera.rotation.z = this.rotation.z;
  20269. };
  20270. // Oculus events
  20271. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  20272. var yaw = evt.alpha / 180 * Math.PI;
  20273. var pitch = evt.beta / 180 * Math.PI;
  20274. var roll = evt.gamma / 180 * Math.PI;
  20275. if (!this._offsetOrientation) {
  20276. this._offsetOrientation = {
  20277. yaw: yaw,
  20278. pitch: pitch,
  20279. roll: roll
  20280. };
  20281. return;
  20282. }
  20283. else {
  20284. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20285. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20286. this.rotation.z += this._offsetOrientation.roll - roll;
  20287. this._offsetOrientation.yaw = yaw;
  20288. this._offsetOrientation.pitch = pitch;
  20289. this._offsetOrientation.roll = roll;
  20290. }
  20291. };
  20292. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  20293. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20294. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20295. };
  20296. OculusGamepadCamera.prototype.detachControl = function (element) {
  20297. _super.prototype.detachControl.call(this, element);
  20298. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20299. };
  20300. OculusGamepadCamera.prototype.dispose = function () {
  20301. this._gamepads.dispose();
  20302. _super.prototype.dispose.call(this);
  20303. };
  20304. return OculusGamepadCamera;
  20305. })(BABYLON.FreeCamera);
  20306. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  20307. })(BABYLON || (BABYLON = {}));
  20308. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  20309. var BABYLON;
  20310. (function (BABYLON) {
  20311. // We're mainly based on the logic defined into the FreeCamera code
  20312. var VirtualJoysticksCamera = (function (_super) {
  20313. __extends(VirtualJoysticksCamera, _super);
  20314. function VirtualJoysticksCamera(name, position, scene) {
  20315. _super.call(this, name, position, scene);
  20316. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  20317. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  20318. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  20319. this._leftjoystick.setJoystickSensibility(0.15);
  20320. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  20321. this._rightjoystick.setAxisForUpDown(0 /* X */);
  20322. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  20323. this._rightjoystick.reverseUpDown = true;
  20324. this._rightjoystick.setJoystickSensibility(0.05);
  20325. this._rightjoystick.setJoystickColor("yellow");
  20326. }
  20327. VirtualJoysticksCamera.prototype._checkInputs = function () {
  20328. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20329. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  20330. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20331. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  20332. if (!this._leftjoystick.pressed) {
  20333. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  20334. }
  20335. if (!this._rightjoystick.pressed) {
  20336. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  20337. }
  20338. };
  20339. VirtualJoysticksCamera.prototype.dispose = function () {
  20340. this._leftjoystick.releaseCanvas();
  20341. _super.prototype.dispose.call(this);
  20342. };
  20343. return VirtualJoysticksCamera;
  20344. })(BABYLON.FreeCamera);
  20345. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  20346. })(BABYLON || (BABYLON = {}));
  20347. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  20348. var BABYLON;
  20349. (function (BABYLON) {
  20350. var ShaderMaterial = (function (_super) {
  20351. __extends(ShaderMaterial, _super);
  20352. function ShaderMaterial(name, scene, shaderPath, options) {
  20353. _super.call(this, name, scene);
  20354. this._textures = new Array();
  20355. this._floats = new Array();
  20356. this._floatsArrays = {};
  20357. this._colors3 = new Array();
  20358. this._colors4 = new Array();
  20359. this._vectors2 = new Array();
  20360. this._vectors3 = new Array();
  20361. this._matrices = new Array();
  20362. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  20363. this._shaderPath = shaderPath;
  20364. options.needAlphaBlending = options.needAlphaBlending || false;
  20365. options.needAlphaTesting = options.needAlphaTesting || false;
  20366. options.attributes = options.attributes || ["position", "normal", "uv"];
  20367. options.uniforms = options.uniforms || ["worldViewProjection"];
  20368. options.samplers = options.samplers || [];
  20369. this._options = options;
  20370. }
  20371. ShaderMaterial.prototype.needAlphaBlending = function () {
  20372. return this._options.needAlphaBlending;
  20373. };
  20374. ShaderMaterial.prototype.needAlphaTesting = function () {
  20375. return this._options.needAlphaTesting;
  20376. };
  20377. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  20378. if (this._options.uniforms.indexOf(uniformName) === -1) {
  20379. this._options.uniforms.push(uniformName);
  20380. }
  20381. };
  20382. ShaderMaterial.prototype.setTexture = function (name, texture) {
  20383. if (this._options.samplers.indexOf(name) === -1) {
  20384. this._options.samplers.push(name);
  20385. }
  20386. this._textures[name] = texture;
  20387. return this;
  20388. };
  20389. ShaderMaterial.prototype.setFloat = function (name, value) {
  20390. this._checkUniform(name);
  20391. this._floats[name] = value;
  20392. return this;
  20393. };
  20394. ShaderMaterial.prototype.setFloats = function (name, value) {
  20395. this._checkUniform(name);
  20396. this._floatsArrays[name] = value;
  20397. return this;
  20398. };
  20399. ShaderMaterial.prototype.setColor3 = function (name, value) {
  20400. this._checkUniform(name);
  20401. this._colors3[name] = value;
  20402. return this;
  20403. };
  20404. ShaderMaterial.prototype.setColor4 = function (name, value) {
  20405. this._checkUniform(name);
  20406. this._colors4[name] = value;
  20407. return this;
  20408. };
  20409. ShaderMaterial.prototype.setVector2 = function (name, value) {
  20410. this._checkUniform(name);
  20411. this._vectors2[name] = value;
  20412. return this;
  20413. };
  20414. ShaderMaterial.prototype.setVector3 = function (name, value) {
  20415. this._checkUniform(name);
  20416. this._vectors3[name] = value;
  20417. return this;
  20418. };
  20419. ShaderMaterial.prototype.setMatrix = function (name, value) {
  20420. this._checkUniform(name);
  20421. this._matrices[name] = value;
  20422. return this;
  20423. };
  20424. ShaderMaterial.prototype.isReady = function () {
  20425. var scene = this.getScene();
  20426. var engine = scene.getEngine();
  20427. if (!this.checkReadyOnEveryCall) {
  20428. if (this._renderId === scene.getRenderId()) {
  20429. return true;
  20430. }
  20431. }
  20432. var previousEffect = this._effect;
  20433. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  20434. if (!this._effect.isReady()) {
  20435. return false;
  20436. }
  20437. if (previousEffect !== this._effect) {
  20438. scene.resetCachedMaterial();
  20439. }
  20440. this._renderId = scene.getRenderId();
  20441. return true;
  20442. };
  20443. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20444. var scene = this.getScene();
  20445. if (this._options.uniforms.indexOf("world") !== -1) {
  20446. this._effect.setMatrix("world", world);
  20447. }
  20448. if (this._options.uniforms.indexOf("worldView") !== -1) {
  20449. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  20450. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  20451. }
  20452. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  20453. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  20454. }
  20455. };
  20456. ShaderMaterial.prototype.bind = function (world) {
  20457. // Std values
  20458. this.bindOnlyWorldMatrix(world);
  20459. if (this.getScene().getCachedMaterial() !== this) {
  20460. if (this._options.uniforms.indexOf("view") !== -1) {
  20461. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  20462. }
  20463. if (this._options.uniforms.indexOf("projection") !== -1) {
  20464. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  20465. }
  20466. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  20467. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  20468. }
  20469. for (var name in this._textures) {
  20470. this._effect.setTexture(name, this._textures[name]);
  20471. }
  20472. for (name in this._floats) {
  20473. this._effect.setFloat(name, this._floats[name]);
  20474. }
  20475. for (name in this._floatsArrays) {
  20476. this._effect.setArray(name, this._floatsArrays[name]);
  20477. }
  20478. for (name in this._colors3) {
  20479. this._effect.setColor3(name, this._colors3[name]);
  20480. }
  20481. for (name in this._colors4) {
  20482. var color = this._colors4[name];
  20483. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  20484. }
  20485. for (name in this._vectors2) {
  20486. this._effect.setVector2(name, this._vectors2[name]);
  20487. }
  20488. for (name in this._vectors3) {
  20489. this._effect.setVector3(name, this._vectors3[name]);
  20490. }
  20491. for (name in this._matrices) {
  20492. this._effect.setMatrix(name, this._matrices[name]);
  20493. }
  20494. }
  20495. _super.prototype.bind.call(this, world, null);
  20496. };
  20497. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  20498. for (var name in this._textures) {
  20499. this._textures[name].dispose();
  20500. }
  20501. this._textures = [];
  20502. _super.prototype.dispose.call(this, forceDisposeEffect);
  20503. };
  20504. return ShaderMaterial;
  20505. })(BABYLON.Material);
  20506. BABYLON.ShaderMaterial = ShaderMaterial;
  20507. })(BABYLON || (BABYLON = {}));
  20508. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  20509. (function (BABYLON) {
  20510. var VertexData = (function () {
  20511. function VertexData() {
  20512. }
  20513. VertexData.prototype.set = function (data, kind) {
  20514. switch (kind) {
  20515. case BABYLON.VertexBuffer.PositionKind:
  20516. this.positions = data;
  20517. break;
  20518. case BABYLON.VertexBuffer.NormalKind:
  20519. this.normals = data;
  20520. break;
  20521. case BABYLON.VertexBuffer.UVKind:
  20522. this.uvs = data;
  20523. break;
  20524. case BABYLON.VertexBuffer.UV2Kind:
  20525. this.uv2s = data;
  20526. break;
  20527. case BABYLON.VertexBuffer.ColorKind:
  20528. this.colors = data;
  20529. break;
  20530. case BABYLON.VertexBuffer.MatricesIndicesKind:
  20531. this.matricesIndices = data;
  20532. break;
  20533. case BABYLON.VertexBuffer.MatricesWeightsKind:
  20534. this.matricesWeights = data;
  20535. break;
  20536. }
  20537. };
  20538. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  20539. this._applyTo(mesh, updatable);
  20540. };
  20541. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  20542. this._applyTo(geometry, updatable);
  20543. };
  20544. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  20545. this._update(mesh);
  20546. };
  20547. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  20548. this._update(geometry);
  20549. };
  20550. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  20551. if (this.positions) {
  20552. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  20553. }
  20554. if (this.normals) {
  20555. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  20556. }
  20557. if (this.uvs) {
  20558. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  20559. }
  20560. if (this.uv2s) {
  20561. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  20562. }
  20563. if (this.colors) {
  20564. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  20565. }
  20566. if (this.matricesIndices) {
  20567. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  20568. }
  20569. if (this.matricesWeights) {
  20570. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  20571. }
  20572. if (this.indices) {
  20573. meshOrGeometry.setIndices(this.indices);
  20574. }
  20575. };
  20576. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  20577. if (this.positions) {
  20578. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  20579. }
  20580. if (this.normals) {
  20581. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  20582. }
  20583. if (this.uvs) {
  20584. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  20585. }
  20586. if (this.uv2s) {
  20587. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  20588. }
  20589. if (this.colors) {
  20590. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  20591. }
  20592. if (this.matricesIndices) {
  20593. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  20594. }
  20595. if (this.matricesWeights) {
  20596. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  20597. }
  20598. if (this.indices) {
  20599. meshOrGeometry.setIndices(this.indices);
  20600. }
  20601. };
  20602. VertexData.prototype.transform = function (matrix) {
  20603. var transformed = BABYLON.Vector3.Zero();
  20604. if (this.positions) {
  20605. var position = BABYLON.Vector3.Zero();
  20606. for (var index = 0; index < this.positions.length; index += 3) {
  20607. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  20608. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  20609. this.positions[index] = transformed.x;
  20610. this.positions[index + 1] = transformed.y;
  20611. this.positions[index + 2] = transformed.z;
  20612. }
  20613. }
  20614. if (this.normals) {
  20615. var normal = BABYLON.Vector3.Zero();
  20616. for (index = 0; index < this.normals.length; index += 3) {
  20617. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  20618. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  20619. this.normals[index] = transformed.x;
  20620. this.normals[index + 1] = transformed.y;
  20621. this.normals[index + 2] = transformed.z;
  20622. }
  20623. }
  20624. };
  20625. VertexData.prototype.merge = function (other) {
  20626. if (other.indices) {
  20627. if (!this.indices) {
  20628. this.indices = [];
  20629. }
  20630. var offset = this.positions ? this.positions.length / 3 : 0;
  20631. for (var index = 0; index < other.indices.length; index++) {
  20632. this.indices.push(other.indices[index] + offset);
  20633. }
  20634. }
  20635. if (other.positions) {
  20636. if (!this.positions) {
  20637. this.positions = [];
  20638. }
  20639. for (index = 0; index < other.positions.length; index++) {
  20640. this.positions.push(other.positions[index]);
  20641. }
  20642. }
  20643. if (other.normals) {
  20644. if (!this.normals) {
  20645. this.normals = [];
  20646. }
  20647. for (index = 0; index < other.normals.length; index++) {
  20648. this.normals.push(other.normals[index]);
  20649. }
  20650. }
  20651. if (other.uvs) {
  20652. if (!this.uvs) {
  20653. this.uvs = [];
  20654. }
  20655. for (index = 0; index < other.uvs.length; index++) {
  20656. this.uvs.push(other.uvs[index]);
  20657. }
  20658. }
  20659. if (other.uv2s) {
  20660. if (!this.uv2s) {
  20661. this.uv2s = [];
  20662. }
  20663. for (index = 0; index < other.uv2s.length; index++) {
  20664. this.uv2s.push(other.uv2s[index]);
  20665. }
  20666. }
  20667. if (other.matricesIndices) {
  20668. if (!this.matricesIndices) {
  20669. this.matricesIndices = [];
  20670. }
  20671. for (index = 0; index < other.matricesIndices.length; index++) {
  20672. this.matricesIndices.push(other.matricesIndices[index]);
  20673. }
  20674. }
  20675. if (other.matricesWeights) {
  20676. if (!this.matricesWeights) {
  20677. this.matricesWeights = [];
  20678. }
  20679. for (index = 0; index < other.matricesWeights.length; index++) {
  20680. this.matricesWeights.push(other.matricesWeights[index]);
  20681. }
  20682. }
  20683. if (other.colors) {
  20684. if (!this.colors) {
  20685. this.colors = [];
  20686. }
  20687. for (index = 0; index < other.colors.length; index++) {
  20688. this.colors.push(other.colors[index]);
  20689. }
  20690. }
  20691. };
  20692. // Statics
  20693. VertexData.ExtractFromMesh = function (mesh) {
  20694. return VertexData._ExtractFrom(mesh);
  20695. };
  20696. VertexData.ExtractFromGeometry = function (geometry) {
  20697. return VertexData._ExtractFrom(geometry);
  20698. };
  20699. VertexData._ExtractFrom = function (meshOrGeometry) {
  20700. var result = new BABYLON.VertexData();
  20701. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20702. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20703. }
  20704. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20705. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20706. }
  20707. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20708. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20709. }
  20710. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20711. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  20712. }
  20713. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20714. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  20715. }
  20716. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20717. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20718. }
  20719. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20720. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20721. }
  20722. result.indices = meshOrGeometry.getIndices();
  20723. return result;
  20724. };
  20725. VertexData.CreateBox = function (size) {
  20726. var normalsSource = [
  20727. new BABYLON.Vector3(0, 0, 1),
  20728. new BABYLON.Vector3(0, 0, -1),
  20729. new BABYLON.Vector3(1, 0, 0),
  20730. new BABYLON.Vector3(-1, 0, 0),
  20731. new BABYLON.Vector3(0, 1, 0),
  20732. new BABYLON.Vector3(0, -1, 0)
  20733. ];
  20734. var indices = [];
  20735. var positions = [];
  20736. var normals = [];
  20737. var uvs = [];
  20738. size = size || 1;
  20739. for (var index = 0; index < normalsSource.length; index++) {
  20740. var normal = normalsSource[index];
  20741. // Get two vectors perpendicular to the face normal and to each other.
  20742. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  20743. var side2 = BABYLON.Vector3.Cross(normal, side1);
  20744. // Six indices (two triangles) per face.
  20745. var verticesLength = positions.length / 3;
  20746. indices.push(verticesLength);
  20747. indices.push(verticesLength + 1);
  20748. indices.push(verticesLength + 2);
  20749. indices.push(verticesLength);
  20750. indices.push(verticesLength + 2);
  20751. indices.push(verticesLength + 3);
  20752. // Four vertices per face.
  20753. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  20754. positions.push(vertex.x, vertex.y, vertex.z);
  20755. normals.push(normal.x, normal.y, normal.z);
  20756. uvs.push(1.0, 1.0);
  20757. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  20758. positions.push(vertex.x, vertex.y, vertex.z);
  20759. normals.push(normal.x, normal.y, normal.z);
  20760. uvs.push(0.0, 1.0);
  20761. vertex = normal.add(side1).add(side2).scale(size / 2);
  20762. positions.push(vertex.x, vertex.y, vertex.z);
  20763. normals.push(normal.x, normal.y, normal.z);
  20764. uvs.push(0.0, 0.0);
  20765. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  20766. positions.push(vertex.x, vertex.y, vertex.z);
  20767. normals.push(normal.x, normal.y, normal.z);
  20768. uvs.push(1.0, 0.0);
  20769. }
  20770. // Result
  20771. var vertexData = new BABYLON.VertexData();
  20772. vertexData.indices = indices;
  20773. vertexData.positions = positions;
  20774. vertexData.normals = normals;
  20775. vertexData.uvs = uvs;
  20776. return vertexData;
  20777. };
  20778. VertexData.CreateSphere = function (segments, diameter) {
  20779. segments = segments || 32;
  20780. diameter = diameter || 1;
  20781. var radius = diameter / 2;
  20782. var totalZRotationSteps = 2 + segments;
  20783. var totalYRotationSteps = 2 * totalZRotationSteps;
  20784. var indices = [];
  20785. var positions = [];
  20786. var normals = [];
  20787. var uvs = [];
  20788. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  20789. var normalizedZ = zRotationStep / totalZRotationSteps;
  20790. var angleZ = (normalizedZ * Math.PI);
  20791. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  20792. var normalizedY = yRotationStep / totalYRotationSteps;
  20793. var angleY = normalizedY * Math.PI * 2;
  20794. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  20795. var rotationY = BABYLON.Matrix.RotationY(angleY);
  20796. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  20797. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  20798. var vertex = complete.scale(radius);
  20799. var normal = BABYLON.Vector3.Normalize(vertex);
  20800. positions.push(vertex.x, vertex.y, vertex.z);
  20801. normals.push(normal.x, normal.y, normal.z);
  20802. uvs.push(normalizedZ, normalizedY);
  20803. }
  20804. if (zRotationStep > 0) {
  20805. var verticesCount = positions.length / 3;
  20806. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  20807. indices.push((firstIndex));
  20808. indices.push((firstIndex + 1));
  20809. indices.push(firstIndex + totalYRotationSteps + 1);
  20810. indices.push((firstIndex + totalYRotationSteps + 1));
  20811. indices.push((firstIndex + 1));
  20812. indices.push((firstIndex + totalYRotationSteps + 2));
  20813. }
  20814. }
  20815. }
  20816. // Result
  20817. var vertexData = new BABYLON.VertexData();
  20818. vertexData.indices = indices;
  20819. vertexData.positions = positions;
  20820. vertexData.normals = normals;
  20821. vertexData.uvs = uvs;
  20822. return vertexData;
  20823. };
  20824. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  20825. if (subdivisions === void 0) { subdivisions = 1; }
  20826. var radiusTop = diameterTop / 2;
  20827. var radiusBottom = diameterBottom / 2;
  20828. var indices = [];
  20829. var positions = [];
  20830. var normals = [];
  20831. var uvs = [];
  20832. height = height || 1;
  20833. diameterTop = diameterTop || 0.5;
  20834. diameterBottom = diameterBottom || 1;
  20835. tessellation = tessellation || 16;
  20836. subdivisions = subdivisions || 1;
  20837. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  20838. var getCircleVector = function (i) {
  20839. var angle = (i * 2.0 * Math.PI / tessellation);
  20840. var dx = Math.cos(angle);
  20841. var dz = Math.sin(angle);
  20842. return new BABYLON.Vector3(dx, 0, dz);
  20843. };
  20844. var createCylinderCap = function (isTop) {
  20845. var radius = isTop ? radiusTop : radiusBottom;
  20846. if (radius == 0) {
  20847. return;
  20848. }
  20849. var vbase = positions.length / 3;
  20850. var offset = new BABYLON.Vector3(0, height / 2, 0);
  20851. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  20852. if (!isTop) {
  20853. offset.scaleInPlace(-1);
  20854. textureScale.x = -textureScale.x;
  20855. }
  20856. for (i = 0; i < tessellation; i++) {
  20857. var circleVector = getCircleVector(i);
  20858. var position = circleVector.scale(radius).add(offset);
  20859. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  20860. positions.push(position.x, position.y, position.z);
  20861. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20862. }
  20863. for (var i = 0; i < tessellation - 2; i++) {
  20864. if (!isTop) {
  20865. indices.push(vbase);
  20866. indices.push(vbase + (i + 2) % tessellation);
  20867. indices.push(vbase + (i + 1) % tessellation);
  20868. }
  20869. else {
  20870. indices.push(vbase);
  20871. indices.push(vbase + (i + 1) % tessellation);
  20872. indices.push(vbase + (i + 2) % tessellation);
  20873. }
  20874. }
  20875. };
  20876. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  20877. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  20878. var stride = tessellation + 1;
  20879. for (var i = 0; i <= tessellation; i++) {
  20880. var circleVector = getCircleVector(i);
  20881. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  20882. var position, radius = radiusBottom;
  20883. for (var s = 0; s <= subdivisions; s++) {
  20884. // Update variables
  20885. position = circleVector.scale(radius);
  20886. position.addInPlace(base.add(offset.scale(s)));
  20887. textureCoordinate.y += 1 / subdivisions;
  20888. radius += (radiusTop - radiusBottom) / subdivisions;
  20889. // Push in arrays
  20890. positions.push(position.x, position.y, position.z);
  20891. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20892. }
  20893. }
  20894. subdivisions += 1;
  20895. for (var s = 0; s < subdivisions - 1; s++) {
  20896. for (var i = 0; i <= tessellation; i++) {
  20897. indices.push(i * subdivisions + s);
  20898. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20899. indices.push(i * subdivisions + (s + 1));
  20900. indices.push(i * subdivisions + (s + 1));
  20901. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20902. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  20903. }
  20904. }
  20905. // Create flat triangle fan caps to seal the top and bottom.
  20906. createCylinderCap(true);
  20907. createCylinderCap(false);
  20908. // Normals
  20909. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20910. // Result
  20911. var vertexData = new BABYLON.VertexData();
  20912. vertexData.indices = indices;
  20913. vertexData.positions = positions;
  20914. vertexData.normals = normals;
  20915. vertexData.uvs = uvs;
  20916. return vertexData;
  20917. };
  20918. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  20919. var indices = [];
  20920. var positions = [];
  20921. var normals = [];
  20922. var uvs = [];
  20923. diameter = diameter || 1;
  20924. thickness = thickness || 0.5;
  20925. tessellation = tessellation || 16;
  20926. var stride = tessellation + 1;
  20927. for (var i = 0; i <= tessellation; i++) {
  20928. var u = i / tessellation;
  20929. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  20930. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  20931. for (var j = 0; j <= tessellation; j++) {
  20932. var v = 1 - j / tessellation;
  20933. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  20934. var dx = Math.cos(innerAngle);
  20935. var dy = Math.sin(innerAngle);
  20936. // Create a vertex.
  20937. var normal = new BABYLON.Vector3(dx, dy, 0);
  20938. var position = normal.scale(thickness / 2);
  20939. var textureCoordinate = new BABYLON.Vector2(u, v);
  20940. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  20941. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  20942. positions.push(position.x, position.y, position.z);
  20943. normals.push(normal.x, normal.y, normal.z);
  20944. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20945. // And create indices for two triangles.
  20946. var nextI = (i + 1) % stride;
  20947. var nextJ = (j + 1) % stride;
  20948. indices.push(i * stride + j);
  20949. indices.push(i * stride + nextJ);
  20950. indices.push(nextI * stride + j);
  20951. indices.push(i * stride + nextJ);
  20952. indices.push(nextI * stride + nextJ);
  20953. indices.push(nextI * stride + j);
  20954. }
  20955. }
  20956. // Result
  20957. var vertexData = new BABYLON.VertexData();
  20958. vertexData.indices = indices;
  20959. vertexData.positions = positions;
  20960. vertexData.normals = normals;
  20961. vertexData.uvs = uvs;
  20962. return vertexData;
  20963. };
  20964. VertexData.CreateLines = function (points) {
  20965. var indices = [];
  20966. var positions = [];
  20967. for (var index = 0; index < points.length; index++) {
  20968. positions.push(points[index].x, points[index].y, points[index].z);
  20969. if (index > 0) {
  20970. indices.push(index - 1);
  20971. indices.push(index);
  20972. }
  20973. }
  20974. // Result
  20975. var vertexData = new BABYLON.VertexData();
  20976. vertexData.indices = indices;
  20977. vertexData.positions = positions;
  20978. return vertexData;
  20979. };
  20980. VertexData.CreateGround = function (width, height, subdivisions) {
  20981. var indices = [];
  20982. var positions = [];
  20983. var normals = [];
  20984. var uvs = [];
  20985. var row, col;
  20986. width = width || 1;
  20987. height = height || 1;
  20988. subdivisions = subdivisions || 1;
  20989. for (row = 0; row <= subdivisions; row++) {
  20990. for (col = 0; col <= subdivisions; col++) {
  20991. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  20992. var normal = new BABYLON.Vector3(0, 1.0, 0);
  20993. positions.push(position.x, position.y, position.z);
  20994. normals.push(normal.x, normal.y, normal.z);
  20995. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20996. }
  20997. }
  20998. for (row = 0; row < subdivisions; row++) {
  20999. for (col = 0; col < subdivisions; col++) {
  21000. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21001. indices.push(col + 1 + row * (subdivisions + 1));
  21002. indices.push(col + row * (subdivisions + 1));
  21003. indices.push(col + (row + 1) * (subdivisions + 1));
  21004. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21005. indices.push(col + row * (subdivisions + 1));
  21006. }
  21007. }
  21008. // Result
  21009. var vertexData = new BABYLON.VertexData();
  21010. vertexData.indices = indices;
  21011. vertexData.positions = positions;
  21012. vertexData.normals = normals;
  21013. vertexData.uvs = uvs;
  21014. return vertexData;
  21015. };
  21016. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  21017. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  21018. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  21019. var indices = [];
  21020. var positions = [];
  21021. var normals = [];
  21022. var uvs = [];
  21023. var row, col, tileRow, tileCol;
  21024. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  21025. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  21026. precision.w = (precision.w < 1) ? 1 : precision.w;
  21027. precision.h = (precision.h < 1) ? 1 : precision.h;
  21028. var tileSize = {
  21029. 'w': (xmax - xmin) / subdivisions.w,
  21030. 'h': (zmax - zmin) / subdivisions.h
  21031. };
  21032. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  21033. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  21034. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  21035. }
  21036. }
  21037. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  21038. // Indices
  21039. var base = positions.length / 3;
  21040. var rowLength = precision.w + 1;
  21041. for (row = 0; row < precision.h; row++) {
  21042. for (col = 0; col < precision.w; col++) {
  21043. var square = [
  21044. base + col + row * rowLength,
  21045. base + (col + 1) + row * rowLength,
  21046. base + (col + 1) + (row + 1) * rowLength,
  21047. base + col + (row + 1) * rowLength
  21048. ];
  21049. indices.push(square[1]);
  21050. indices.push(square[2]);
  21051. indices.push(square[3]);
  21052. indices.push(square[0]);
  21053. indices.push(square[1]);
  21054. indices.push(square[3]);
  21055. }
  21056. }
  21057. // Position, normals and uvs
  21058. var position = BABYLON.Vector3.Zero();
  21059. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21060. for (row = 0; row <= precision.h; row++) {
  21061. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  21062. for (col = 0; col <= precision.w; col++) {
  21063. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  21064. position.y = 0;
  21065. positions.push(position.x, position.y, position.z);
  21066. normals.push(normal.x, normal.y, normal.z);
  21067. uvs.push(col / precision.w, row / precision.h);
  21068. }
  21069. }
  21070. }
  21071. // Result
  21072. var vertexData = new BABYLON.VertexData();
  21073. vertexData.indices = indices;
  21074. vertexData.positions = positions;
  21075. vertexData.normals = normals;
  21076. vertexData.uvs = uvs;
  21077. return vertexData;
  21078. };
  21079. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  21080. var indices = [];
  21081. var positions = [];
  21082. var normals = [];
  21083. var uvs = [];
  21084. var row, col;
  21085. for (row = 0; row <= subdivisions; row++) {
  21086. for (col = 0; col <= subdivisions; col++) {
  21087. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21088. // Compute height
  21089. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  21090. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  21091. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  21092. var r = buffer[pos] / 255.0;
  21093. var g = buffer[pos + 1] / 255.0;
  21094. var b = buffer[pos + 2] / 255.0;
  21095. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21096. position.y = minHeight + (maxHeight - minHeight) * gradient;
  21097. // Add vertex
  21098. positions.push(position.x, position.y, position.z);
  21099. normals.push(0, 0, 0);
  21100. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21101. }
  21102. }
  21103. for (row = 0; row < subdivisions; row++) {
  21104. for (col = 0; col < subdivisions; col++) {
  21105. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21106. indices.push(col + 1 + row * (subdivisions + 1));
  21107. indices.push(col + row * (subdivisions + 1));
  21108. indices.push(col + (row + 1) * (subdivisions + 1));
  21109. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21110. indices.push(col + row * (subdivisions + 1));
  21111. }
  21112. }
  21113. // Normals
  21114. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21115. // Result
  21116. var vertexData = new BABYLON.VertexData();
  21117. vertexData.indices = indices;
  21118. vertexData.positions = positions;
  21119. vertexData.normals = normals;
  21120. vertexData.uvs = uvs;
  21121. return vertexData;
  21122. };
  21123. VertexData.CreatePlane = function (size) {
  21124. var indices = [];
  21125. var positions = [];
  21126. var normals = [];
  21127. var uvs = [];
  21128. size = size || 1;
  21129. // Vertices
  21130. var halfSize = size / 2.0;
  21131. positions.push(-halfSize, -halfSize, 0);
  21132. normals.push(0, 0, -1.0);
  21133. uvs.push(0.0, 0.0);
  21134. positions.push(halfSize, -halfSize, 0);
  21135. normals.push(0, 0, -1.0);
  21136. uvs.push(1.0, 0.0);
  21137. positions.push(halfSize, halfSize, 0);
  21138. normals.push(0, 0, -1.0);
  21139. uvs.push(1.0, 1.0);
  21140. positions.push(-halfSize, halfSize, 0);
  21141. normals.push(0, 0, -1.0);
  21142. uvs.push(0.0, 1.0);
  21143. // Indices
  21144. indices.push(0);
  21145. indices.push(1);
  21146. indices.push(2);
  21147. indices.push(0);
  21148. indices.push(2);
  21149. indices.push(3);
  21150. // Result
  21151. var vertexData = new BABYLON.VertexData();
  21152. vertexData.indices = indices;
  21153. vertexData.positions = positions;
  21154. vertexData.normals = normals;
  21155. vertexData.uvs = uvs;
  21156. return vertexData;
  21157. };
  21158. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  21159. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  21160. var indices = [];
  21161. var positions = [];
  21162. var normals = [];
  21163. var uvs = [];
  21164. radius = radius || 2;
  21165. tube = tube || 0.5;
  21166. radialSegments = radialSegments || 32;
  21167. tubularSegments = tubularSegments || 32;
  21168. p = p || 2;
  21169. q = q || 3;
  21170. // Helper
  21171. var getPos = function (angle) {
  21172. var cu = Math.cos(angle);
  21173. var su = Math.sin(angle);
  21174. var quOverP = q / p * angle;
  21175. var cs = Math.cos(quOverP);
  21176. var tx = radius * (2 + cs) * 0.5 * cu;
  21177. var ty = radius * (2 + cs) * su * 0.5;
  21178. var tz = radius * Math.sin(quOverP) * 0.5;
  21179. return new BABYLON.Vector3(tx, ty, tz);
  21180. };
  21181. for (var i = 0; i <= radialSegments; i++) {
  21182. var modI = i % radialSegments;
  21183. var u = modI / radialSegments * 2 * p * Math.PI;
  21184. var p1 = getPos(u);
  21185. var p2 = getPos(u + 0.01);
  21186. var tang = p2.subtract(p1);
  21187. var n = p2.add(p1);
  21188. var bitan = BABYLON.Vector3.Cross(tang, n);
  21189. n = BABYLON.Vector3.Cross(bitan, tang);
  21190. bitan.normalize();
  21191. n.normalize();
  21192. for (var j = 0; j < tubularSegments; j++) {
  21193. var modJ = j % tubularSegments;
  21194. var v = modJ / tubularSegments * 2 * Math.PI;
  21195. var cx = -tube * Math.cos(v);
  21196. var cy = tube * Math.sin(v);
  21197. positions.push(p1.x + cx * n.x + cy * bitan.x);
  21198. positions.push(p1.y + cx * n.y + cy * bitan.y);
  21199. positions.push(p1.z + cx * n.z + cy * bitan.z);
  21200. uvs.push(i / radialSegments);
  21201. uvs.push(j / tubularSegments);
  21202. }
  21203. }
  21204. for (i = 0; i < radialSegments; i++) {
  21205. for (j = 0; j < tubularSegments; j++) {
  21206. var jNext = (j + 1) % tubularSegments;
  21207. var a = i * tubularSegments + j;
  21208. var b = (i + 1) * tubularSegments + j;
  21209. var c = (i + 1) * tubularSegments + jNext;
  21210. var d = i * tubularSegments + jNext;
  21211. indices.push(d);
  21212. indices.push(b);
  21213. indices.push(a);
  21214. indices.push(d);
  21215. indices.push(c);
  21216. indices.push(b);
  21217. }
  21218. }
  21219. // Normals
  21220. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21221. // Result
  21222. var vertexData = new BABYLON.VertexData();
  21223. vertexData.indices = indices;
  21224. vertexData.positions = positions;
  21225. vertexData.normals = normals;
  21226. vertexData.uvs = uvs;
  21227. return vertexData;
  21228. };
  21229. // Tools
  21230. VertexData.ComputeNormals = function (positions, indices, normals) {
  21231. var positionVectors = [];
  21232. var facesOfVertices = [];
  21233. var index;
  21234. for (index = 0; index < positions.length; index += 3) {
  21235. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  21236. positionVectors.push(vector3);
  21237. facesOfVertices.push([]);
  21238. }
  21239. // Compute normals
  21240. var facesNormals = [];
  21241. for (index = 0; index < indices.length / 3; index++) {
  21242. var i1 = indices[index * 3];
  21243. var i2 = indices[index * 3 + 1];
  21244. var i3 = indices[index * 3 + 2];
  21245. var p1 = positionVectors[i1];
  21246. var p2 = positionVectors[i2];
  21247. var p3 = positionVectors[i3];
  21248. var p1p2 = p1.subtract(p2);
  21249. var p3p2 = p3.subtract(p2);
  21250. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21251. facesOfVertices[i1].push(index);
  21252. facesOfVertices[i2].push(index);
  21253. facesOfVertices[i3].push(index);
  21254. }
  21255. for (index = 0; index < positionVectors.length; index++) {
  21256. var faces = facesOfVertices[index];
  21257. var normal = BABYLON.Vector3.Zero();
  21258. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  21259. normal.addInPlace(facesNormals[faces[faceIndex]]);
  21260. }
  21261. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  21262. normals[index * 3] = normal.x;
  21263. normals[index * 3 + 1] = normal.y;
  21264. normals[index * 3 + 2] = normal.z;
  21265. }
  21266. };
  21267. return VertexData;
  21268. })();
  21269. BABYLON.VertexData = VertexData;
  21270. })(BABYLON || (BABYLON = {}));
  21271. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  21272. var BABYLON;
  21273. (function (BABYLON) {
  21274. var buildCamera = function (that, name) {
  21275. that._leftCamera.isIntermediate = true;
  21276. that.subCameras.push(that._leftCamera);
  21277. that.subCameras.push(that._rightCamera);
  21278. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  21279. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  21280. that._anaglyphPostProcess.onApply = function (effect) {
  21281. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  21282. };
  21283. that._update();
  21284. };
  21285. var AnaglyphArcRotateCamera = (function (_super) {
  21286. __extends(AnaglyphArcRotateCamera, _super);
  21287. // ANY
  21288. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  21289. _super.call(this, name, alpha, beta, radius, target, scene);
  21290. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21291. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  21292. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  21293. buildCamera(this, name);
  21294. }
  21295. AnaglyphArcRotateCamera.prototype._update = function () {
  21296. this._updateCamera(this._leftCamera);
  21297. this._updateCamera(this._rightCamera);
  21298. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  21299. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  21300. _super.prototype._update.call(this);
  21301. };
  21302. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  21303. camera.beta = this.beta;
  21304. camera.radius = this.radius;
  21305. camera.minZ = this.minZ;
  21306. camera.maxZ = this.maxZ;
  21307. camera.fov = this.fov;
  21308. camera.target = this.target;
  21309. };
  21310. return AnaglyphArcRotateCamera;
  21311. })(BABYLON.ArcRotateCamera);
  21312. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  21313. var AnaglyphFreeCamera = (function (_super) {
  21314. __extends(AnaglyphFreeCamera, _super);
  21315. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  21316. _super.call(this, name, position, scene);
  21317. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21318. this._transformMatrix = new BABYLON.Matrix();
  21319. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  21320. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  21321. buildCamera(this, name);
  21322. }
  21323. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  21324. var target = this.getTarget();
  21325. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  21326. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  21327. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  21328. };
  21329. AnaglyphFreeCamera.prototype._update = function () {
  21330. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  21331. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  21332. this._updateCamera(this._leftCamera);
  21333. this._updateCamera(this._rightCamera);
  21334. _super.prototype._update.call(this);
  21335. };
  21336. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  21337. camera.minZ = this.minZ;
  21338. camera.maxZ = this.maxZ;
  21339. camera.fov = this.fov;
  21340. camera.viewport = this.viewport;
  21341. camera.setTarget(this.getTarget());
  21342. };
  21343. return AnaglyphFreeCamera;
  21344. })(BABYLON.FreeCamera);
  21345. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  21346. })(BABYLON || (BABYLON = {}));
  21347. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  21348. var BABYLON;
  21349. (function (BABYLON) {
  21350. var AnaglyphPostProcess = (function (_super) {
  21351. __extends(AnaglyphPostProcess, _super);
  21352. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21353. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  21354. }
  21355. return AnaglyphPostProcess;
  21356. })(BABYLON.PostProcess);
  21357. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  21358. })(BABYLON || (BABYLON = {}));
  21359. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  21360. (function (BABYLON) {
  21361. var Tags = (function () {
  21362. function Tags() {
  21363. }
  21364. Tags.EnableFor = function (obj) {
  21365. obj._tags = obj._tags || {};
  21366. obj.hasTags = function () {
  21367. return Tags.HasTags(obj);
  21368. };
  21369. obj.addTags = function (tagsString) {
  21370. return Tags.AddTagsTo(obj, tagsString);
  21371. };
  21372. obj.removeTags = function (tagsString) {
  21373. return Tags.RemoveTagsFrom(obj, tagsString);
  21374. };
  21375. obj.matchesTagsQuery = function (tagsQuery) {
  21376. return Tags.MatchesQuery(obj, tagsQuery);
  21377. };
  21378. };
  21379. Tags.DisableFor = function (obj) {
  21380. delete obj._tags;
  21381. delete obj.hasTags;
  21382. delete obj.addTags;
  21383. delete obj.removeTags;
  21384. delete obj.matchesTagsQuery;
  21385. };
  21386. Tags.HasTags = function (obj) {
  21387. if (!obj._tags) {
  21388. return false;
  21389. }
  21390. return !BABYLON.Tools.IsEmpty(obj._tags);
  21391. };
  21392. Tags.GetTags = function (obj) {
  21393. if (!obj._tags) {
  21394. return null;
  21395. }
  21396. return obj._tags;
  21397. };
  21398. // the tags 'true' and 'false' are reserved and cannot be used as tags
  21399. // a tag cannot start with '||', '&&', and '!'
  21400. // it cannot contain whitespaces
  21401. Tags.AddTagsTo = function (obj, tagsString) {
  21402. if (!tagsString) {
  21403. return;
  21404. }
  21405. var tags = tagsString.split(" ");
  21406. for (var t in tags) {
  21407. Tags._AddTagTo(obj, tags[t]);
  21408. }
  21409. };
  21410. Tags._AddTagTo = function (obj, tag) {
  21411. tag = tag.trim();
  21412. if (tag === "" || tag === "true" || tag === "false") {
  21413. return;
  21414. }
  21415. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  21416. return;
  21417. }
  21418. Tags.EnableFor(obj);
  21419. obj._tags[tag] = true;
  21420. };
  21421. Tags.RemoveTagsFrom = function (obj, tagsString) {
  21422. if (!Tags.HasTags(obj)) {
  21423. return;
  21424. }
  21425. var tags = tagsString.split(" ");
  21426. for (var t in tags) {
  21427. Tags._RemoveTagFrom(obj, tags[t]);
  21428. }
  21429. };
  21430. Tags._RemoveTagFrom = function (obj, tag) {
  21431. delete obj._tags[tag];
  21432. };
  21433. Tags.MatchesQuery = function (obj, tagsQuery) {
  21434. if (tagsQuery === undefined) {
  21435. return true;
  21436. }
  21437. if (tagsQuery === "") {
  21438. return Tags.HasTags(obj);
  21439. }
  21440. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  21441. };
  21442. return Tags;
  21443. })();
  21444. BABYLON.Tags = Tags;
  21445. })(BABYLON || (BABYLON = {}));
  21446. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  21447. (function (BABYLON) {
  21448. var Internals;
  21449. (function (Internals) {
  21450. var AndOrNotEvaluator = (function () {
  21451. function AndOrNotEvaluator() {
  21452. }
  21453. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  21454. if (!query.match(/\([^\(\)]*\)/g)) {
  21455. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  21456. }
  21457. else {
  21458. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  21459. // remove parenthesis
  21460. r = r.slice(1, r.length - 1);
  21461. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  21462. });
  21463. }
  21464. if (query === "true") {
  21465. return true;
  21466. }
  21467. if (query === "false") {
  21468. return false;
  21469. }
  21470. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  21471. };
  21472. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  21473. evaluateCallback = evaluateCallback || (function (r) {
  21474. return r === "true" ? true : false;
  21475. });
  21476. var result;
  21477. var or = parenthesisContent.split("||");
  21478. for (var i in or) {
  21479. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  21480. var and = ori.split("&&");
  21481. if (and.length > 1) {
  21482. for (var j = 0; j < and.length; ++j) {
  21483. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  21484. if (andj !== "true" && andj !== "false") {
  21485. if (andj[0] === "!") {
  21486. result = !evaluateCallback(andj.substring(1));
  21487. }
  21488. else {
  21489. result = evaluateCallback(andj);
  21490. }
  21491. }
  21492. else {
  21493. result = andj === "true" ? true : false;
  21494. }
  21495. if (!result) {
  21496. ori = "false";
  21497. break;
  21498. }
  21499. }
  21500. }
  21501. if (result || ori === "true") {
  21502. result = true;
  21503. break;
  21504. }
  21505. // result equals false (or undefined)
  21506. if (ori !== "true" && ori !== "false") {
  21507. if (ori[0] === "!") {
  21508. result = !evaluateCallback(ori.substring(1));
  21509. }
  21510. else {
  21511. result = evaluateCallback(ori);
  21512. }
  21513. }
  21514. else {
  21515. result = ori === "true" ? true : false;
  21516. }
  21517. }
  21518. // the whole parenthesis scope is replaced by 'true' or 'false'
  21519. return result ? "true" : "false";
  21520. };
  21521. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  21522. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  21523. // remove whitespaces
  21524. r = r.replace(/[\s]/g, function () { return ""; });
  21525. return r.length % 2 ? "!" : "";
  21526. });
  21527. booleanString = booleanString.trim();
  21528. if (booleanString === "!true") {
  21529. booleanString = "false";
  21530. }
  21531. else if (booleanString === "!false") {
  21532. booleanString = "true";
  21533. }
  21534. return booleanString;
  21535. };
  21536. return AndOrNotEvaluator;
  21537. })();
  21538. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  21539. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21540. })(BABYLON || (BABYLON = {}));
  21541. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  21542. (function (BABYLON) {
  21543. var PostProcessRenderPass = (function () {
  21544. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  21545. this._enabled = true;
  21546. this._refCount = 0;
  21547. this._name = name;
  21548. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  21549. this.setRenderList(renderList);
  21550. this._renderTexture.onBeforeRender = beforeRender;
  21551. this._renderTexture.onAfterRender = afterRender;
  21552. this._scene = scene;
  21553. this._renderList = renderList;
  21554. }
  21555. // private
  21556. PostProcessRenderPass.prototype._incRefCount = function () {
  21557. if (this._refCount === 0) {
  21558. this._scene.customRenderTargets.push(this._renderTexture);
  21559. }
  21560. return ++this._refCount;
  21561. };
  21562. PostProcessRenderPass.prototype._decRefCount = function () {
  21563. this._refCount--;
  21564. if (this._refCount <= 0) {
  21565. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  21566. }
  21567. return this._refCount;
  21568. };
  21569. PostProcessRenderPass.prototype._update = function () {
  21570. this.setRenderList(this._renderList);
  21571. };
  21572. // public
  21573. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  21574. this._renderTexture.renderList = renderList;
  21575. };
  21576. PostProcessRenderPass.prototype.getRenderTexture = function () {
  21577. return this._renderTexture;
  21578. };
  21579. return PostProcessRenderPass;
  21580. })();
  21581. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  21582. })(BABYLON || (BABYLON = {}));
  21583. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  21584. (function (BABYLON) {
  21585. var PostProcessRenderEffect = (function () {
  21586. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  21587. this._engine = engine;
  21588. this._name = name;
  21589. this._singleInstance = singleInstance || true;
  21590. this._getPostProcess = getPostProcess;
  21591. this._cameras = [];
  21592. this._indicesForCamera = [];
  21593. this._postProcesses = {};
  21594. this._renderPasses = {};
  21595. this._renderEffectAsPasses = {};
  21596. }
  21597. PostProcessRenderEffect.prototype._update = function () {
  21598. for (var renderPassName in this._renderPasses) {
  21599. this._renderPasses[renderPassName]._update();
  21600. }
  21601. };
  21602. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  21603. this._renderPasses[renderPass._name] = renderPass;
  21604. this._linkParameters();
  21605. };
  21606. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  21607. delete this._renderPasses[renderPass._name];
  21608. this._linkParameters();
  21609. };
  21610. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  21611. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  21612. this._linkParameters();
  21613. };
  21614. PostProcessRenderEffect.prototype.getPass = function (passName) {
  21615. for (var renderPassName in this._renderPasses) {
  21616. if (renderPassName === passName) {
  21617. return this._renderPasses[passName];
  21618. }
  21619. }
  21620. };
  21621. PostProcessRenderEffect.prototype.emptyPasses = function () {
  21622. this._renderPasses = {};
  21623. this._linkParameters();
  21624. };
  21625. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  21626. var cameraKey;
  21627. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21628. for (var i = 0; i < _cam.length; i++) {
  21629. var camera = _cam[i];
  21630. var cameraName = camera.name;
  21631. if (this._singleInstance) {
  21632. cameraKey = 0;
  21633. }
  21634. else {
  21635. cameraKey = cameraName;
  21636. }
  21637. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  21638. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  21639. if (!this._indicesForCamera[cameraName]) {
  21640. this._indicesForCamera[cameraName] = [];
  21641. }
  21642. this._indicesForCamera[cameraName].push(index);
  21643. if (this._cameras.indexOf(camera) === -1) {
  21644. this._cameras[cameraName] = camera;
  21645. }
  21646. for (var passName in this._renderPasses) {
  21647. this._renderPasses[passName]._incRefCount();
  21648. }
  21649. }
  21650. this._linkParameters();
  21651. };
  21652. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  21653. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21654. for (var i = 0; i < _cam.length; i++) {
  21655. var camera = _cam[i];
  21656. var cameraName = camera.name;
  21657. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21658. var index = this._cameras.indexOf(cameraName);
  21659. this._indicesForCamera.splice(index, 1);
  21660. this._cameras.splice(index, 1);
  21661. for (var passName in this._renderPasses) {
  21662. this._renderPasses[passName]._decRefCount();
  21663. }
  21664. }
  21665. };
  21666. PostProcessRenderEffect.prototype._enable = function (cameras) {
  21667. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21668. for (var i = 0; i < _cam.length; i++) {
  21669. var camera = _cam[i];
  21670. var cameraName = camera.name;
  21671. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  21672. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  21673. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  21674. }
  21675. }
  21676. for (var passName in this._renderPasses) {
  21677. this._renderPasses[passName]._incRefCount();
  21678. }
  21679. }
  21680. };
  21681. PostProcessRenderEffect.prototype._disable = function (cameras) {
  21682. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21683. for (var i = 0; i < _cam.length; i++) {
  21684. var camera = _cam[i];
  21685. var cameraName = camera.Name;
  21686. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21687. for (var passName in this._renderPasses) {
  21688. this._renderPasses[passName]._decRefCount();
  21689. }
  21690. }
  21691. };
  21692. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  21693. if (this._singleInstance) {
  21694. return this._postProcesses[0];
  21695. }
  21696. else {
  21697. return this._postProcesses[camera.name];
  21698. }
  21699. };
  21700. PostProcessRenderEffect.prototype._linkParameters = function () {
  21701. var _this = this;
  21702. for (var index in this._postProcesses) {
  21703. if (this.applyParameters) {
  21704. this.applyParameters(this._postProcesses[index]);
  21705. }
  21706. this._postProcesses[index].onBeforeRender = function (effect) {
  21707. _this._linkTextures(effect);
  21708. };
  21709. }
  21710. };
  21711. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  21712. for (var renderPassName in this._renderPasses) {
  21713. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  21714. }
  21715. for (var renderEffectName in this._renderEffectAsPasses) {
  21716. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  21717. }
  21718. };
  21719. return PostProcessRenderEffect;
  21720. })();
  21721. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  21722. })(BABYLON || (BABYLON = {}));
  21723. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  21724. (function (BABYLON) {
  21725. var PostProcessRenderPipeline = (function () {
  21726. function PostProcessRenderPipeline(engine, name) {
  21727. this._engine = engine;
  21728. this._name = name;
  21729. this._renderEffects = {};
  21730. this._renderEffectsForIsolatedPass = {};
  21731. this._cameras = [];
  21732. }
  21733. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  21734. this._renderEffects[renderEffect._name] = renderEffect;
  21735. };
  21736. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  21737. var renderEffects = this._renderEffects[renderEffectName];
  21738. if (!renderEffects) {
  21739. return;
  21740. }
  21741. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21742. };
  21743. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  21744. var renderEffects = this._renderEffects[renderEffectName];
  21745. if (!renderEffects) {
  21746. return;
  21747. }
  21748. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21749. };
  21750. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  21751. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21752. var indicesToDelete = [];
  21753. for (var i = 0; i < _cam.length; i++) {
  21754. var camera = _cam[i];
  21755. var cameraName = camera.name;
  21756. if (this._cameras.indexOf(camera) === -1) {
  21757. this._cameras[cameraName] = camera;
  21758. }
  21759. else if (unique) {
  21760. indicesToDelete.push(i);
  21761. }
  21762. }
  21763. for (var i = 0; i < indicesToDelete.length; i++) {
  21764. cameras.splice(indicesToDelete[i], 1);
  21765. }
  21766. for (var renderEffectName in this._renderEffects) {
  21767. this._renderEffects[renderEffectName]._attachCameras(_cam);
  21768. }
  21769. };
  21770. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  21771. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21772. for (var renderEffectName in this._renderEffects) {
  21773. this._renderEffects[renderEffectName]._detachCameras(_cam);
  21774. }
  21775. for (var i = 0; i < _cam.length; i++) {
  21776. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  21777. }
  21778. };
  21779. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  21780. var _this = this;
  21781. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21782. var pass = null;
  21783. for (var renderEffectName in this._renderEffects) {
  21784. pass = this._renderEffects[renderEffectName].getPass(passName);
  21785. if (pass != null) {
  21786. break;
  21787. }
  21788. }
  21789. if (pass === null) {
  21790. return;
  21791. }
  21792. for (var renderEffectName in this._renderEffects) {
  21793. this._renderEffects[renderEffectName]._disable(_cam);
  21794. }
  21795. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  21796. for (var i = 0; i < _cam.length; i++) {
  21797. var camera = _cam[i];
  21798. var cameraName = camera.name;
  21799. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21800. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21801. });
  21802. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  21803. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  21804. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  21805. }
  21806. };
  21807. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  21808. var _this = this;
  21809. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21810. for (var i = 0; i < _cam.length; i++) {
  21811. var camera = _cam[i];
  21812. var cameraName = camera.name;
  21813. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21814. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21815. });
  21816. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  21817. }
  21818. for (var renderEffectName in this._renderEffects) {
  21819. this._renderEffects[renderEffectName]._enable(_cam);
  21820. }
  21821. };
  21822. PostProcessRenderPipeline.prototype._update = function () {
  21823. for (var renderEffectName in this._renderEffects) {
  21824. this._renderEffects[renderEffectName]._update();
  21825. }
  21826. for (var i = 0; i < this._cameras.length; i++) {
  21827. var cameraName = this._cameras[i].name;
  21828. if (this._renderEffectsForIsolatedPass[cameraName]) {
  21829. this._renderEffectsForIsolatedPass[cameraName]._update();
  21830. }
  21831. }
  21832. };
  21833. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  21834. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  21835. return PostProcessRenderPipeline;
  21836. })();
  21837. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  21838. })(BABYLON || (BABYLON = {}));
  21839. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  21840. (function (BABYLON) {
  21841. var PostProcessRenderPipelineManager = (function () {
  21842. function PostProcessRenderPipelineManager() {
  21843. this._renderPipelines = {};
  21844. }
  21845. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  21846. this._renderPipelines[renderPipeline._name] = renderPipeline;
  21847. };
  21848. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  21849. var renderPipeline = this._renderPipelines[renderPipelineName];
  21850. if (!renderPipeline) {
  21851. return;
  21852. }
  21853. renderPipeline._attachCameras(cameras, unique);
  21854. };
  21855. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  21856. var renderPipeline = this._renderPipelines[renderPipelineName];
  21857. if (!renderPipeline) {
  21858. return;
  21859. }
  21860. renderPipeline._detachCameras(cameras);
  21861. };
  21862. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21863. var renderPipeline = this._renderPipelines[renderPipelineName];
  21864. if (!renderPipeline) {
  21865. return;
  21866. }
  21867. renderPipeline._enableEffect(renderEffectName, cameras);
  21868. };
  21869. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21870. var renderPipeline = this._renderPipelines[renderPipelineName];
  21871. if (!renderPipeline) {
  21872. return;
  21873. }
  21874. renderPipeline._disableEffect(renderEffectName, cameras);
  21875. };
  21876. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  21877. var renderPipeline = this._renderPipelines[renderPipelineName];
  21878. if (!renderPipeline) {
  21879. return;
  21880. }
  21881. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  21882. };
  21883. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  21884. var renderPipeline = this._renderPipelines[renderPipelineName];
  21885. if (!renderPipeline) {
  21886. return;
  21887. }
  21888. renderPipeline._disableDisplayOnlyPass(cameras);
  21889. };
  21890. PostProcessRenderPipelineManager.prototype.update = function () {
  21891. for (var renderPipelineName in this._renderPipelines) {
  21892. this._renderPipelines[renderPipelineName]._update();
  21893. }
  21894. };
  21895. return PostProcessRenderPipelineManager;
  21896. })();
  21897. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  21898. })(BABYLON || (BABYLON = {}));
  21899. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  21900. var BABYLON;
  21901. (function (BABYLON) {
  21902. var DisplayPassPostProcess = (function (_super) {
  21903. __extends(DisplayPassPostProcess, _super);
  21904. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21905. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  21906. }
  21907. return DisplayPassPostProcess;
  21908. })(BABYLON.PostProcess);
  21909. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  21910. })(BABYLON || (BABYLON = {}));
  21911. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  21912. (function (BABYLON) {
  21913. var BoundingBoxRenderer = (function () {
  21914. function BoundingBoxRenderer(scene) {
  21915. this.frontColor = new BABYLON.Color3(1, 1, 1);
  21916. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  21917. this.showBackLines = true;
  21918. this.renderList = new BABYLON.SmartArray(32);
  21919. this._scene = scene;
  21920. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  21921. attributes: ["position"],
  21922. uniforms: ["worldViewProjection", "color"]
  21923. });
  21924. var engine = this._scene.getEngine();
  21925. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  21926. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  21927. 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]);
  21928. }
  21929. BoundingBoxRenderer.prototype.reset = function () {
  21930. this.renderList.reset();
  21931. };
  21932. BoundingBoxRenderer.prototype.render = function () {
  21933. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  21934. return;
  21935. }
  21936. var engine = this._scene.getEngine();
  21937. engine.setDepthWrite(false);
  21938. this._colorShader._preBind();
  21939. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  21940. var boundingBox = this.renderList.data[boundingBoxIndex];
  21941. var min = boundingBox.minimum;
  21942. var max = boundingBox.maximum;
  21943. var diff = max.subtract(min);
  21944. var median = min.add(diff.scale(0.5));
  21945. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  21946. // VBOs
  21947. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  21948. if (this.showBackLines) {
  21949. // Back
  21950. engine.setDepthFunctionToGreaterOrEqual();
  21951. this._scene.resetCachedMaterial();
  21952. this._colorShader.setColor4("color", this.backColor.toColor4());
  21953. this._colorShader.bind(worldMatrix);
  21954. // Draw order
  21955. engine.draw(false, 0, 24);
  21956. }
  21957. // Front
  21958. engine.setDepthFunctionToLess();
  21959. this._scene.resetCachedMaterial();
  21960. this._colorShader.setColor4("color", this.frontColor.toColor4());
  21961. this._colorShader.bind(worldMatrix);
  21962. // Draw order
  21963. engine.draw(false, 0, 24);
  21964. }
  21965. this._colorShader.unbind();
  21966. engine.setDepthFunctionToLessOrEqual();
  21967. engine.setDepthWrite(true);
  21968. };
  21969. BoundingBoxRenderer.prototype.dispose = function () {
  21970. this._colorShader.dispose();
  21971. this._vb.dispose();
  21972. this._scene.getEngine()._releaseBuffer(this._ib);
  21973. };
  21974. return BoundingBoxRenderer;
  21975. })();
  21976. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  21977. })(BABYLON || (BABYLON = {}));
  21978. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  21979. (function (BABYLON) {
  21980. var Internals;
  21981. (function (Internals) {
  21982. /*
  21983. * Based on jsTGALoader - Javascript loader for TGA file
  21984. * By Vincent Thibault
  21985. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  21986. */
  21987. var TGATools = (function () {
  21988. function TGATools() {
  21989. }
  21990. TGATools.GetTGAHeader = function (data) {
  21991. var offset = 0;
  21992. var header = {
  21993. id_length: data[offset++],
  21994. colormap_type: data[offset++],
  21995. image_type: data[offset++],
  21996. colormap_index: data[offset++] | data[offset++] << 8,
  21997. colormap_length: data[offset++] | data[offset++] << 8,
  21998. colormap_size: data[offset++],
  21999. origin: [
  22000. data[offset++] | data[offset++] << 8,
  22001. data[offset++] | data[offset++] << 8
  22002. ],
  22003. width: data[offset++] | data[offset++] << 8,
  22004. height: data[offset++] | data[offset++] << 8,
  22005. pixel_size: data[offset++],
  22006. flags: data[offset++]
  22007. };
  22008. return header;
  22009. };
  22010. TGATools.UploadContent = function (gl, data) {
  22011. // Not enough data to contain header ?
  22012. if (data.length < 19) {
  22013. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  22014. return;
  22015. }
  22016. // Read Header
  22017. var offset = 18;
  22018. var header = TGATools.GetTGAHeader(data);
  22019. // Assume it's a valid Targa file.
  22020. if (header.id_length + offset > data.length) {
  22021. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  22022. return;
  22023. }
  22024. // Skip not needed data
  22025. offset += header.id_length;
  22026. var use_rle = false;
  22027. var use_pal = false;
  22028. var use_rgb = false;
  22029. var use_grey = false;
  22030. switch (header.image_type) {
  22031. case TGATools._TYPE_RLE_INDEXED:
  22032. use_rle = true;
  22033. case TGATools._TYPE_INDEXED:
  22034. use_pal = true;
  22035. break;
  22036. case TGATools._TYPE_RLE_RGB:
  22037. use_rle = true;
  22038. case TGATools._TYPE_RGB:
  22039. use_rgb = true;
  22040. break;
  22041. case TGATools._TYPE_RLE_GREY:
  22042. use_rle = true;
  22043. case TGATools._TYPE_GREY:
  22044. use_grey = true;
  22045. break;
  22046. }
  22047. var pixel_data;
  22048. var numAlphaBits = header.flags & 0xf;
  22049. var pixel_size = header.pixel_size >> 3;
  22050. var pixel_total = header.width * header.height * pixel_size;
  22051. // Read palettes
  22052. var palettes;
  22053. if (use_pal) {
  22054. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  22055. }
  22056. // Read LRE
  22057. if (use_rle) {
  22058. pixel_data = new Uint8Array(pixel_total);
  22059. var c, count, i;
  22060. var localOffset = 0;
  22061. var pixels = new Uint8Array(pixel_size);
  22062. while (offset < pixel_total && localOffset < pixel_total) {
  22063. c = data[offset++];
  22064. count = (c & 0x7f) + 1;
  22065. // RLE pixels
  22066. if (c & 0x80) {
  22067. for (i = 0; i < pixel_size; ++i) {
  22068. pixels[i] = data[offset++];
  22069. }
  22070. for (i = 0; i < count; ++i) {
  22071. pixel_data.set(pixels, localOffset + i * pixel_size);
  22072. }
  22073. localOffset += pixel_size * count;
  22074. }
  22075. else {
  22076. count *= pixel_size;
  22077. for (i = 0; i < count; ++i) {
  22078. pixel_data[localOffset + i] = data[offset++];
  22079. }
  22080. localOffset += count;
  22081. }
  22082. }
  22083. }
  22084. else {
  22085. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  22086. }
  22087. // Load to texture
  22088. var x_start, y_start, x_step, y_step, y_end, x_end;
  22089. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  22090. default:
  22091. case TGATools._ORIGIN_UL:
  22092. x_start = 0;
  22093. x_step = 1;
  22094. x_end = header.width;
  22095. y_start = 0;
  22096. y_step = 1;
  22097. y_end = header.height;
  22098. break;
  22099. case TGATools._ORIGIN_BL:
  22100. x_start = 0;
  22101. x_step = 1;
  22102. x_end = header.width;
  22103. y_start = header.height - 1;
  22104. y_step = -1;
  22105. y_end = -1;
  22106. break;
  22107. case TGATools._ORIGIN_UR:
  22108. x_start = header.width - 1;
  22109. x_step = -1;
  22110. x_end = -1;
  22111. y_start = 0;
  22112. y_step = 1;
  22113. y_end = header.height;
  22114. break;
  22115. case TGATools._ORIGIN_BR:
  22116. x_start = header.width - 1;
  22117. x_step = -1;
  22118. x_end = -1;
  22119. y_start = header.height - 1;
  22120. y_step = -1;
  22121. y_end = -1;
  22122. break;
  22123. }
  22124. // Load the specify method
  22125. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  22126. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  22127. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  22128. };
  22129. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22130. var image = pixel_data, colormap = palettes;
  22131. var width = header.width, height = header.height;
  22132. var color, i = 0, x, y;
  22133. var imageData = new Uint8Array(width * height * 4);
  22134. for (y = y_start; y !== y_end; y += y_step) {
  22135. for (x = x_start; x !== x_end; x += x_step, i++) {
  22136. color = image[i];
  22137. imageData[(x + width * y) * 4 + 3] = 255;
  22138. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  22139. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  22140. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  22141. }
  22142. }
  22143. return imageData;
  22144. };
  22145. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22146. var image = pixel_data;
  22147. var width = header.width, height = header.height;
  22148. var color, i = 0, x, y;
  22149. var imageData = new Uint8Array(width * height * 4);
  22150. for (y = y_start; y !== y_end; y += y_step) {
  22151. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22152. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  22153. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  22154. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  22155. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  22156. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  22157. }
  22158. }
  22159. return imageData;
  22160. };
  22161. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22162. var image = pixel_data;
  22163. var width = header.width, height = header.height;
  22164. var i = 0, x, y;
  22165. var imageData = new Uint8Array(width * height * 4);
  22166. for (y = y_start; y !== y_end; y += y_step) {
  22167. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  22168. imageData[(x + width * y) * 4 + 3] = 255;
  22169. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22170. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22171. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22172. }
  22173. }
  22174. return imageData;
  22175. };
  22176. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22177. var image = pixel_data;
  22178. var width = header.width, height = header.height;
  22179. var i = 0, x, y;
  22180. var imageData = new Uint8Array(width * height * 4);
  22181. for (y = y_start; y !== y_end; y += y_step) {
  22182. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  22183. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22184. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22185. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22186. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  22187. }
  22188. }
  22189. return imageData;
  22190. };
  22191. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22192. var image = pixel_data;
  22193. var width = header.width, height = header.height;
  22194. var color, i = 0, x, y;
  22195. var imageData = new Uint8Array(width * height * 4);
  22196. for (y = y_start; y !== y_end; y += y_step) {
  22197. for (x = x_start; x !== x_end; x += x_step, i++) {
  22198. color = image[i];
  22199. imageData[(x + width * y) * 4 + 0] = color;
  22200. imageData[(x + width * y) * 4 + 1] = color;
  22201. imageData[(x + width * y) * 4 + 2] = color;
  22202. imageData[(x + width * y) * 4 + 3] = 255;
  22203. }
  22204. }
  22205. return imageData;
  22206. };
  22207. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22208. var image = pixel_data;
  22209. var width = header.width, height = header.height;
  22210. var i = 0, x, y;
  22211. var imageData = new Uint8Array(width * height * 4);
  22212. for (y = y_start; y !== y_end; y += y_step) {
  22213. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22214. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  22215. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  22216. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22217. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  22218. }
  22219. }
  22220. return imageData;
  22221. };
  22222. TGATools._TYPE_NO_DATA = 0;
  22223. TGATools._TYPE_INDEXED = 1;
  22224. TGATools._TYPE_RGB = 2;
  22225. TGATools._TYPE_GREY = 3;
  22226. TGATools._TYPE_RLE_INDEXED = 9;
  22227. TGATools._TYPE_RLE_RGB = 10;
  22228. TGATools._TYPE_RLE_GREY = 11;
  22229. TGATools._ORIGIN_MASK = 0x30;
  22230. TGATools._ORIGIN_SHIFT = 0x04;
  22231. TGATools._ORIGIN_BL = 0x00;
  22232. TGATools._ORIGIN_BR = 0x01;
  22233. TGATools._ORIGIN_UL = 0x02;
  22234. TGATools._ORIGIN_UR = 0x03;
  22235. return TGATools;
  22236. })();
  22237. Internals.TGATools = TGATools;
  22238. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22239. })(BABYLON || (BABYLON = {}));
  22240. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  22241. (function (BABYLON) {
  22242. var Internals;
  22243. (function (Internals) {
  22244. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  22245. // All values and structures referenced from:
  22246. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  22247. var DDS_MAGIC = 0x20534444;
  22248. 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;
  22249. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  22250. 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;
  22251. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  22252. function FourCCToInt32(value) {
  22253. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  22254. }
  22255. function Int32ToFourCC(value) {
  22256. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  22257. }
  22258. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  22259. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  22260. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  22261. var headerLengthInt = 31; // The header length in 32 bit ints
  22262. // Offsets into the header array
  22263. var off_magic = 0;
  22264. var off_size = 1;
  22265. var off_flags = 2;
  22266. var off_height = 3;
  22267. var off_width = 4;
  22268. var off_mipmapCount = 7;
  22269. var off_pfFlags = 20;
  22270. var off_pfFourCC = 21;
  22271. var off_RGBbpp = 22;
  22272. var off_RMask = 23;
  22273. var off_GMask = 24;
  22274. var off_BMask = 25;
  22275. var off_AMask = 26;
  22276. var off_caps1 = 27;
  22277. var off_caps2 = 28;
  22278. ;
  22279. var DDSTools = (function () {
  22280. function DDSTools() {
  22281. }
  22282. DDSTools.GetDDSInfo = function (arrayBuffer) {
  22283. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  22284. var mipmapCount = 1;
  22285. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  22286. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22287. }
  22288. return {
  22289. width: header[off_width],
  22290. height: header[off_height],
  22291. mipmapCount: mipmapCount,
  22292. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  22293. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  22294. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  22295. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  22296. };
  22297. };
  22298. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22299. var byteArray = new Uint8Array(dataLength);
  22300. var srcData = new Uint8Array(arrayBuffer);
  22301. var index = 0;
  22302. for (var y = height - 1; y >= 0; y--) {
  22303. for (var x = 0; x < width; x++) {
  22304. var srcPos = dataOffset + (x + y * width) * 4;
  22305. byteArray[index + 2] = srcData[srcPos];
  22306. byteArray[index + 1] = srcData[srcPos + 1];
  22307. byteArray[index] = srcData[srcPos + 2];
  22308. byteArray[index + 3] = srcData[srcPos + 3];
  22309. index += 4;
  22310. }
  22311. }
  22312. return byteArray;
  22313. };
  22314. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22315. var byteArray = new Uint8Array(dataLength);
  22316. var srcData = new Uint8Array(arrayBuffer);
  22317. var index = 0;
  22318. for (var y = height - 1; y >= 0; y--) {
  22319. for (var x = 0; x < width; x++) {
  22320. var srcPos = dataOffset + (x + y * width) * 3;
  22321. byteArray[index + 2] = srcData[srcPos];
  22322. byteArray[index + 1] = srcData[srcPos + 1];
  22323. byteArray[index] = srcData[srcPos + 2];
  22324. index += 3;
  22325. }
  22326. }
  22327. return byteArray;
  22328. };
  22329. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22330. var byteArray = new Uint8Array(dataLength);
  22331. var srcData = new Uint8Array(arrayBuffer);
  22332. var index = 0;
  22333. for (var y = height - 1; y >= 0; y--) {
  22334. for (var x = 0; x < width; x++) {
  22335. var srcPos = dataOffset + (x + y * width);
  22336. byteArray[index] = srcData[srcPos];
  22337. index++;
  22338. }
  22339. }
  22340. return byteArray;
  22341. };
  22342. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  22343. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  22344. if (header[off_magic] != DDS_MAGIC) {
  22345. BABYLON.Tools.Error("Invalid magic number in DDS header");
  22346. return;
  22347. }
  22348. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  22349. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  22350. return;
  22351. }
  22352. if (info.isFourCC) {
  22353. fourCC = header[off_pfFourCC];
  22354. switch (fourCC) {
  22355. case FOURCC_DXT1:
  22356. blockBytes = 8;
  22357. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  22358. break;
  22359. case FOURCC_DXT3:
  22360. blockBytes = 16;
  22361. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  22362. break;
  22363. case FOURCC_DXT5:
  22364. blockBytes = 16;
  22365. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  22366. break;
  22367. default:
  22368. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  22369. return;
  22370. }
  22371. }
  22372. mipmapCount = 1;
  22373. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  22374. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22375. }
  22376. var bpp = header[off_RGBbpp];
  22377. for (var face = 0; face < faces; face++) {
  22378. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  22379. width = header[off_width];
  22380. height = header[off_height];
  22381. dataOffset = header[off_size] + 4;
  22382. for (i = 0; i < mipmapCount; ++i) {
  22383. if (info.isRGB) {
  22384. if (bpp == 24) {
  22385. dataLength = width * height * 3;
  22386. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22387. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  22388. }
  22389. else {
  22390. dataLength = width * height * 4;
  22391. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22392. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  22393. }
  22394. }
  22395. else if (info.isLuminance) {
  22396. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  22397. var unpaddedRowSize = width;
  22398. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  22399. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  22400. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22401. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  22402. }
  22403. else {
  22404. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  22405. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  22406. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  22407. }
  22408. dataOffset += dataLength;
  22409. width *= 0.5;
  22410. height *= 0.5;
  22411. width = Math.max(1.0, width);
  22412. height = Math.max(1.0, height);
  22413. }
  22414. }
  22415. };
  22416. return DDSTools;
  22417. })();
  22418. Internals.DDSTools = DDSTools;
  22419. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22420. })(BABYLON || (BABYLON = {}));
  22421. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  22422. (function (BABYLON) {
  22423. var SmartArray = (function () {
  22424. function SmartArray(capacity) {
  22425. this.length = 0;
  22426. this._duplicateId = 0;
  22427. this.data = new Array(capacity);
  22428. this._id = SmartArray._GlobalId++;
  22429. }
  22430. SmartArray.prototype.push = function (value) {
  22431. this.data[this.length++] = value;
  22432. if (this.length > this.data.length) {
  22433. this.data.length *= 2;
  22434. }
  22435. if (!value.__smartArrayFlags) {
  22436. value.__smartArrayFlags = {};
  22437. }
  22438. value.__smartArrayFlags[this._id] = this._duplicateId;
  22439. };
  22440. SmartArray.prototype.pushNoDuplicate = function (value) {
  22441. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  22442. return;
  22443. }
  22444. this.push(value);
  22445. };
  22446. SmartArray.prototype.sort = function (compareFn) {
  22447. this.data.sort(compareFn);
  22448. };
  22449. SmartArray.prototype.reset = function () {
  22450. this.length = 0;
  22451. this._duplicateId++;
  22452. };
  22453. SmartArray.prototype.concat = function (array) {
  22454. if (array.length === 0) {
  22455. return;
  22456. }
  22457. if (this.length + array.length > this.data.length) {
  22458. this.data.length = (this.length + array.length) * 2;
  22459. }
  22460. for (var index = 0; index < array.length; index++) {
  22461. this.data[this.length++] = (array.data || array)[index];
  22462. }
  22463. };
  22464. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  22465. if (array.length === 0) {
  22466. return;
  22467. }
  22468. if (this.length + array.length > this.data.length) {
  22469. this.data.length = (this.length + array.length) * 2;
  22470. }
  22471. for (var index = 0; index < array.length; index++) {
  22472. var item = (array.data || array)[index];
  22473. this.pushNoDuplicate(item);
  22474. }
  22475. };
  22476. SmartArray.prototype.indexOf = function (value) {
  22477. var position = this.data.indexOf(value);
  22478. if (position >= this.length) {
  22479. return -1;
  22480. }
  22481. return position;
  22482. };
  22483. // Statics
  22484. SmartArray._GlobalId = 0;
  22485. return SmartArray;
  22486. })();
  22487. BABYLON.SmartArray = SmartArray;
  22488. })(BABYLON || (BABYLON = {}));
  22489. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  22490. (function (BABYLON) {
  22491. var CannonJSPlugin = (function () {
  22492. function CannonJSPlugin() {
  22493. this._registeredMeshes = [];
  22494. this._physicsMaterials = [];
  22495. this.updateBodyPosition = function (mesh) {
  22496. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22497. var registeredMesh = this._registeredMeshes[index];
  22498. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22499. var body = registeredMesh.body;
  22500. var center = mesh.getBoundingInfo().boundingBox.center;
  22501. body.position.set(center.x, center.z, center.y);
  22502. body.quaternion.x = mesh.rotationQuaternion.x;
  22503. body.quaternion.z = mesh.rotationQuaternion.y;
  22504. body.quaternion.y = mesh.rotationQuaternion.z;
  22505. body.quaternion.w = -mesh.rotationQuaternion.w;
  22506. return;
  22507. }
  22508. }
  22509. };
  22510. }
  22511. CannonJSPlugin.prototype.initialize = function (iterations) {
  22512. if (iterations === void 0) { iterations = 10; }
  22513. this._world = new CANNON.World();
  22514. this._world.broadphase = new CANNON.NaiveBroadphase();
  22515. this._world.solver.iterations = iterations;
  22516. };
  22517. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22518. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22519. };
  22520. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22521. this._world.step(delta);
  22522. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22523. var registeredMesh = this._registeredMeshes[index];
  22524. if (registeredMesh.isChild) {
  22525. continue;
  22526. }
  22527. // Body position
  22528. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22529. var deltaPos = registeredMesh.delta;
  22530. if (deltaPos) {
  22531. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22532. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22533. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22534. }
  22535. else {
  22536. registeredMesh.mesh.position.x = bodyX;
  22537. registeredMesh.mesh.position.y = bodyZ;
  22538. registeredMesh.mesh.position.z = bodyY;
  22539. }
  22540. if (!registeredMesh.mesh.rotationQuaternion) {
  22541. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22542. }
  22543. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22544. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22545. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22546. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22547. }
  22548. };
  22549. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22550. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22551. };
  22552. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22553. this.unregisterMesh(mesh);
  22554. mesh.computeWorldMatrix(true);
  22555. switch (impostor) {
  22556. case BABYLON.PhysicsEngine.SphereImpostor:
  22557. var bbox = mesh.getBoundingInfo().boundingBox;
  22558. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22559. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22560. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22561. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22562. case BABYLON.PhysicsEngine.BoxImpostor:
  22563. bbox = mesh.getBoundingInfo().boundingBox;
  22564. var min = bbox.minimumWorld;
  22565. var max = bbox.maximumWorld;
  22566. var box = max.subtract(min).scale(0.5);
  22567. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22568. case BABYLON.PhysicsEngine.PlaneImpostor:
  22569. return this._createPlane(mesh, options);
  22570. case BABYLON.PhysicsEngine.MeshImpostor:
  22571. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22572. var rawFaces = mesh.getIndices();
  22573. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22574. }
  22575. return null;
  22576. };
  22577. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22578. var shape = new CANNON.Sphere(radius);
  22579. if (!options) {
  22580. return shape;
  22581. }
  22582. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22583. };
  22584. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22585. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22586. if (!options) {
  22587. return shape;
  22588. }
  22589. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22590. };
  22591. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22592. var shape = new CANNON.Plane();
  22593. if (!options) {
  22594. return shape;
  22595. }
  22596. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22597. };
  22598. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22599. var verts = [], faces = [];
  22600. mesh.computeWorldMatrix(true);
  22601. for (var i = 0; i < rawVerts.length; i += 3) {
  22602. var transformed = BABYLON.Vector3.Zero();
  22603. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22604. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22605. }
  22606. for (var j = 0; j < rawFaces.length; j += 3) {
  22607. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22608. }
  22609. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22610. if (!options) {
  22611. return shape;
  22612. }
  22613. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22614. };
  22615. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22616. var index;
  22617. var mat;
  22618. for (index = 0; index < this._physicsMaterials.length; index++) {
  22619. mat = this._physicsMaterials[index];
  22620. if (mat.friction === friction && mat.restitution === restitution) {
  22621. return mat;
  22622. }
  22623. }
  22624. var currentMat = new CANNON.Material();
  22625. currentMat.friction = friction;
  22626. currentMat.restitution = restitution;
  22627. this._physicsMaterials.push(currentMat);
  22628. for (index = 0; index < this._physicsMaterials.length; index++) {
  22629. mat = this._physicsMaterials[index];
  22630. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22631. contactMaterial.contactEquationStiffness = 1e10;
  22632. contactMaterial.contactEquationRegularizationTime = 10;
  22633. this._world.addContactMaterial(contactMaterial);
  22634. }
  22635. return currentMat;
  22636. };
  22637. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22638. var initialRotation = null;
  22639. if (mesh.rotationQuaternion) {
  22640. initialRotation = mesh.rotationQuaternion.clone();
  22641. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22642. }
  22643. // The delta between the mesh position and the mesh bounding box center
  22644. var bbox = mesh.getBoundingInfo().boundingBox;
  22645. var deltaPosition = mesh.position.subtract(bbox.center);
  22646. var material = this._addMaterial(friction, restitution);
  22647. var body = new CANNON.RigidBody(mass, shape, material);
  22648. if (initialRotation) {
  22649. body.quaternion.x = initialRotation.x;
  22650. body.quaternion.z = initialRotation.y;
  22651. body.quaternion.y = initialRotation.z;
  22652. body.quaternion.w = -initialRotation.w;
  22653. }
  22654. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22655. this._world.add(body);
  22656. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22657. return body;
  22658. };
  22659. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22660. var compoundShape = new CANNON.Compound();
  22661. for (var index = 0; index < parts.length; index++) {
  22662. var mesh = parts[index].mesh;
  22663. var shape = this.registerMesh(mesh, parts[index].impostor);
  22664. if (index == 0) {
  22665. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22666. }
  22667. else {
  22668. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22669. }
  22670. }
  22671. var initialMesh = parts[0].mesh;
  22672. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22673. body.parts = parts;
  22674. return body;
  22675. };
  22676. CannonJSPlugin.prototype._unbindBody = function (body) {
  22677. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22678. var registeredMesh = this._registeredMeshes[index];
  22679. if (registeredMesh.body === body) {
  22680. registeredMesh.body = null;
  22681. registeredMesh.delta = 0;
  22682. }
  22683. }
  22684. };
  22685. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22686. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22687. var registeredMesh = this._registeredMeshes[index];
  22688. if (registeredMesh.mesh === mesh) {
  22689. // Remove body
  22690. if (registeredMesh.body) {
  22691. this._world.remove(registeredMesh.body);
  22692. this._unbindBody(registeredMesh.body);
  22693. }
  22694. this._registeredMeshes.splice(index, 1);
  22695. return;
  22696. }
  22697. }
  22698. };
  22699. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22700. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22701. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22702. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22703. var registeredMesh = this._registeredMeshes[index];
  22704. if (registeredMesh.mesh === mesh) {
  22705. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22706. return;
  22707. }
  22708. }
  22709. };
  22710. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22711. var body1 = null, body2 = null;
  22712. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22713. var registeredMesh = this._registeredMeshes[index];
  22714. if (registeredMesh.mesh === mesh1) {
  22715. body1 = registeredMesh.body;
  22716. }
  22717. else if (registeredMesh.mesh === mesh2) {
  22718. body2 = registeredMesh.body;
  22719. }
  22720. }
  22721. if (!body1 || !body2) {
  22722. return false;
  22723. }
  22724. 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));
  22725. this._world.addConstraint(constraint);
  22726. return true;
  22727. };
  22728. CannonJSPlugin.prototype.dispose = function () {
  22729. while (this._registeredMeshes.length) {
  22730. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22731. }
  22732. };
  22733. CannonJSPlugin.prototype.isSupported = function () {
  22734. return window.CANNON !== undefined;
  22735. };
  22736. return CannonJSPlugin;
  22737. })();
  22738. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22739. })(BABYLON || (BABYLON = {}));
  22740. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22741. var BABYLON;
  22742. (function (BABYLON) {
  22743. var Condition = (function () {
  22744. function Condition(actionManager) {
  22745. this._actionManager = actionManager;
  22746. }
  22747. Condition.prototype.isValid = function () {
  22748. return true;
  22749. };
  22750. Condition.prototype._getProperty = function (propertyPath) {
  22751. return this._actionManager._getProperty(propertyPath);
  22752. };
  22753. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  22754. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22755. };
  22756. return Condition;
  22757. })();
  22758. BABYLON.Condition = Condition;
  22759. var ValueCondition = (function (_super) {
  22760. __extends(ValueCondition, _super);
  22761. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  22762. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  22763. _super.call(this, actionManager);
  22764. this.propertyPath = propertyPath;
  22765. this.value = value;
  22766. this.operator = operator;
  22767. this._target = this._getEffectiveTarget(target, this.propertyPath);
  22768. this._property = this._getProperty(this.propertyPath);
  22769. }
  22770. Object.defineProperty(ValueCondition, "IsEqual", {
  22771. get: function () {
  22772. return ValueCondition._IsEqual;
  22773. },
  22774. enumerable: true,
  22775. configurable: true
  22776. });
  22777. Object.defineProperty(ValueCondition, "IsDifferent", {
  22778. get: function () {
  22779. return ValueCondition._IsDifferent;
  22780. },
  22781. enumerable: true,
  22782. configurable: true
  22783. });
  22784. Object.defineProperty(ValueCondition, "IsGreater", {
  22785. get: function () {
  22786. return ValueCondition._IsGreater;
  22787. },
  22788. enumerable: true,
  22789. configurable: true
  22790. });
  22791. Object.defineProperty(ValueCondition, "IsLesser", {
  22792. get: function () {
  22793. return ValueCondition._IsLesser;
  22794. },
  22795. enumerable: true,
  22796. configurable: true
  22797. });
  22798. // Methods
  22799. ValueCondition.prototype.isValid = function () {
  22800. switch (this.operator) {
  22801. case ValueCondition.IsGreater:
  22802. return this._target[this._property] > this.value;
  22803. case ValueCondition.IsLesser:
  22804. return this._target[this._property] < this.value;
  22805. case ValueCondition.IsEqual:
  22806. case ValueCondition.IsDifferent:
  22807. var check;
  22808. if (this.value.equals) {
  22809. check = this.value.equals(this._target[this._property]);
  22810. }
  22811. else {
  22812. check = this.value === this._target[this._property];
  22813. }
  22814. return this.operator === ValueCondition.IsEqual ? check : !check;
  22815. }
  22816. return false;
  22817. };
  22818. // Statics
  22819. ValueCondition._IsEqual = 0;
  22820. ValueCondition._IsDifferent = 1;
  22821. ValueCondition._IsGreater = 2;
  22822. ValueCondition._IsLesser = 3;
  22823. return ValueCondition;
  22824. })(Condition);
  22825. BABYLON.ValueCondition = ValueCondition;
  22826. var PredicateCondition = (function (_super) {
  22827. __extends(PredicateCondition, _super);
  22828. function PredicateCondition(actionManager, predicate) {
  22829. _super.call(this, actionManager);
  22830. this.predicate = predicate;
  22831. }
  22832. PredicateCondition.prototype.isValid = function () {
  22833. return this.predicate();
  22834. };
  22835. return PredicateCondition;
  22836. })(Condition);
  22837. BABYLON.PredicateCondition = PredicateCondition;
  22838. var StateCondition = (function (_super) {
  22839. __extends(StateCondition, _super);
  22840. function StateCondition(actionManager, target, value) {
  22841. _super.call(this, actionManager);
  22842. this.value = value;
  22843. this._target = target;
  22844. }
  22845. // Methods
  22846. StateCondition.prototype.isValid = function () {
  22847. return this._target.state === this.value;
  22848. };
  22849. return StateCondition;
  22850. })(Condition);
  22851. BABYLON.StateCondition = StateCondition;
  22852. })(BABYLON || (BABYLON = {}));
  22853. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  22854. (function (BABYLON) {
  22855. var Action = (function () {
  22856. function Action(triggerOptions, condition) {
  22857. this.triggerOptions = triggerOptions;
  22858. if (triggerOptions.parameter) {
  22859. this.trigger = triggerOptions.trigger;
  22860. this._triggerParameter = triggerOptions.parameter;
  22861. }
  22862. else {
  22863. this.trigger = triggerOptions;
  22864. }
  22865. this._nextActiveAction = this;
  22866. this._condition = condition;
  22867. }
  22868. // Methods
  22869. Action.prototype._prepare = function () {
  22870. };
  22871. Action.prototype.getTriggerParameter = function () {
  22872. return this._triggerParameter;
  22873. };
  22874. Action.prototype._executeCurrent = function (evt) {
  22875. if (this._condition) {
  22876. var currentRenderId = this._actionManager.getScene().getRenderId();
  22877. // We cache the current evaluation for the current frame
  22878. if (this._condition._evaluationId === currentRenderId) {
  22879. if (!this._condition._currentResult) {
  22880. return;
  22881. }
  22882. }
  22883. else {
  22884. this._condition._evaluationId = currentRenderId;
  22885. if (!this._condition.isValid()) {
  22886. this._condition._currentResult = false;
  22887. return;
  22888. }
  22889. this._condition._currentResult = true;
  22890. }
  22891. }
  22892. this._nextActiveAction.execute(evt);
  22893. if (this._nextActiveAction._child) {
  22894. if (!this._nextActiveAction._child._actionManager) {
  22895. this._nextActiveAction._child._actionManager = this._actionManager;
  22896. }
  22897. this._nextActiveAction = this._nextActiveAction._child;
  22898. }
  22899. else {
  22900. this._nextActiveAction = this;
  22901. }
  22902. };
  22903. Action.prototype.execute = function (evt) {
  22904. };
  22905. Action.prototype.then = function (action) {
  22906. this._child = action;
  22907. action._actionManager = this._actionManager;
  22908. action._prepare();
  22909. return action;
  22910. };
  22911. Action.prototype._getProperty = function (propertyPath) {
  22912. return this._actionManager._getProperty(propertyPath);
  22913. };
  22914. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  22915. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22916. };
  22917. return Action;
  22918. })();
  22919. BABYLON.Action = Action;
  22920. })(BABYLON || (BABYLON = {}));
  22921. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  22922. (function (BABYLON) {
  22923. /**
  22924. * ActionEvent is the event beint sent when an action is triggered.
  22925. */
  22926. var ActionEvent = (function () {
  22927. /**
  22928. * @constructor
  22929. * @param source The mesh that triggered the action.
  22930. * @param pointerX the X mouse cursor position at the time of the event
  22931. * @param pointerY the Y mouse cursor position at the time of the event
  22932. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  22933. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  22934. */
  22935. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  22936. this.source = source;
  22937. this.pointerX = pointerX;
  22938. this.pointerY = pointerY;
  22939. this.meshUnderPointer = meshUnderPointer;
  22940. this.sourceEvent = sourceEvent;
  22941. }
  22942. /**
  22943. * Helper function to auto-create an ActionEvent from a source mesh.
  22944. * @param source the source mesh that triggered the event
  22945. * @param evt {Event} The original (browser) event
  22946. */
  22947. ActionEvent.CreateNew = function (source, evt) {
  22948. var scene = source.getScene();
  22949. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22950. };
  22951. /**
  22952. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  22953. * @param scene the scene where the event occurred
  22954. * @param evt {Event} The original (browser) event
  22955. */
  22956. ActionEvent.CreateNewFromScene = function (scene, evt) {
  22957. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22958. };
  22959. return ActionEvent;
  22960. })();
  22961. BABYLON.ActionEvent = ActionEvent;
  22962. /**
  22963. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  22964. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  22965. */
  22966. var ActionManager = (function () {
  22967. function ActionManager(scene) {
  22968. // Members
  22969. this.actions = new Array();
  22970. this._scene = scene;
  22971. scene._actionManagers.push(this);
  22972. }
  22973. Object.defineProperty(ActionManager, "NothingTrigger", {
  22974. get: function () {
  22975. return ActionManager._NothingTrigger;
  22976. },
  22977. enumerable: true,
  22978. configurable: true
  22979. });
  22980. Object.defineProperty(ActionManager, "OnPickTrigger", {
  22981. get: function () {
  22982. return ActionManager._OnPickTrigger;
  22983. },
  22984. enumerable: true,
  22985. configurable: true
  22986. });
  22987. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  22988. get: function () {
  22989. return ActionManager._OnLeftPickTrigger;
  22990. },
  22991. enumerable: true,
  22992. configurable: true
  22993. });
  22994. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  22995. get: function () {
  22996. return ActionManager._OnRightPickTrigger;
  22997. },
  22998. enumerable: true,
  22999. configurable: true
  23000. });
  23001. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  23002. get: function () {
  23003. return ActionManager._OnCenterPickTrigger;
  23004. },
  23005. enumerable: true,
  23006. configurable: true
  23007. });
  23008. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  23009. get: function () {
  23010. return ActionManager._OnPointerOverTrigger;
  23011. },
  23012. enumerable: true,
  23013. configurable: true
  23014. });
  23015. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  23016. get: function () {
  23017. return ActionManager._OnPointerOutTrigger;
  23018. },
  23019. enumerable: true,
  23020. configurable: true
  23021. });
  23022. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  23023. get: function () {
  23024. return ActionManager._OnEveryFrameTrigger;
  23025. },
  23026. enumerable: true,
  23027. configurable: true
  23028. });
  23029. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  23030. get: function () {
  23031. return ActionManager._OnIntersectionEnterTrigger;
  23032. },
  23033. enumerable: true,
  23034. configurable: true
  23035. });
  23036. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  23037. get: function () {
  23038. return ActionManager._OnIntersectionExitTrigger;
  23039. },
  23040. enumerable: true,
  23041. configurable: true
  23042. });
  23043. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  23044. get: function () {
  23045. return ActionManager._OnKeyDownTrigger;
  23046. },
  23047. enumerable: true,
  23048. configurable: true
  23049. });
  23050. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  23051. get: function () {
  23052. return ActionManager._OnKeyUpTrigger;
  23053. },
  23054. enumerable: true,
  23055. configurable: true
  23056. });
  23057. // Methods
  23058. ActionManager.prototype.dispose = function () {
  23059. var index = this._scene._actionManagers.indexOf(this);
  23060. if (index > -1) {
  23061. this._scene._actionManagers.splice(index, 1);
  23062. }
  23063. };
  23064. ActionManager.prototype.getScene = function () {
  23065. return this._scene;
  23066. };
  23067. /**
  23068. * Does this action manager handles actions of any of the given triggers
  23069. * @param {number[]} triggers - the triggers to be tested
  23070. * @return {boolean} whether one (or more) of the triggers is handeled
  23071. */
  23072. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  23073. for (var index = 0; index < this.actions.length; index++) {
  23074. var action = this.actions[index];
  23075. if (triggers.indexOf(action.trigger) > -1) {
  23076. return true;
  23077. }
  23078. }
  23079. return false;
  23080. };
  23081. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  23082. /**
  23083. * Does this action manager has pointer triggers
  23084. * @return {boolean} whether or not it has pointer triggers
  23085. */
  23086. get: function () {
  23087. for (var index = 0; index < this.actions.length; index++) {
  23088. var action = this.actions[index];
  23089. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  23090. return true;
  23091. }
  23092. }
  23093. return false;
  23094. },
  23095. enumerable: true,
  23096. configurable: true
  23097. });
  23098. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  23099. /**
  23100. * Does this action manager has pick triggers
  23101. * @return {boolean} whether or not it has pick triggers
  23102. */
  23103. get: function () {
  23104. for (var index = 0; index < this.actions.length; index++) {
  23105. var action = this.actions[index];
  23106. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  23107. return true;
  23108. }
  23109. }
  23110. return false;
  23111. },
  23112. enumerable: true,
  23113. configurable: true
  23114. });
  23115. /**
  23116. * Registers an action to this action manager
  23117. * @param {BABYLON.Action} action - the action to be registered
  23118. * @return {BABYLON.Action} the action amended (prepared) after registration
  23119. */
  23120. ActionManager.prototype.registerAction = function (action) {
  23121. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  23122. if (this.getScene().actionManager !== this) {
  23123. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  23124. return null;
  23125. }
  23126. }
  23127. this.actions.push(action);
  23128. action._actionManager = this;
  23129. action._prepare();
  23130. return action;
  23131. };
  23132. /**
  23133. * Process a specific trigger
  23134. * @param {number} trigger - the trigger to process
  23135. * @param evt {BABYLON.ActionEvent} the event details to be processed
  23136. */
  23137. ActionManager.prototype.processTrigger = function (trigger, evt) {
  23138. for (var index = 0; index < this.actions.length; index++) {
  23139. var action = this.actions[index];
  23140. if (action.trigger === trigger) {
  23141. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  23142. var parameter = action.getTriggerParameter();
  23143. if (parameter) {
  23144. if (evt.sourceEvent.key !== parameter) {
  23145. continue;
  23146. }
  23147. }
  23148. }
  23149. action._executeCurrent(evt);
  23150. }
  23151. }
  23152. };
  23153. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  23154. var properties = propertyPath.split(".");
  23155. for (var index = 0; index < properties.length - 1; index++) {
  23156. target = target[properties[index]];
  23157. }
  23158. return target;
  23159. };
  23160. ActionManager.prototype._getProperty = function (propertyPath) {
  23161. var properties = propertyPath.split(".");
  23162. return properties[properties.length - 1];
  23163. };
  23164. // Statics
  23165. ActionManager._NothingTrigger = 0;
  23166. ActionManager._OnPickTrigger = 1;
  23167. ActionManager._OnLeftPickTrigger = 2;
  23168. ActionManager._OnRightPickTrigger = 3;
  23169. ActionManager._OnCenterPickTrigger = 4;
  23170. ActionManager._OnPointerOverTrigger = 5;
  23171. ActionManager._OnPointerOutTrigger = 6;
  23172. ActionManager._OnEveryFrameTrigger = 7;
  23173. ActionManager._OnIntersectionEnterTrigger = 8;
  23174. ActionManager._OnIntersectionExitTrigger = 9;
  23175. ActionManager._OnKeyDownTrigger = 10;
  23176. ActionManager._OnKeyUpTrigger = 11;
  23177. return ActionManager;
  23178. })();
  23179. BABYLON.ActionManager = ActionManager;
  23180. })(BABYLON || (BABYLON = {}));
  23181. //# sourceMappingURL=babylon.actionManager.js.map
  23182. var BABYLON;
  23183. (function (BABYLON) {
  23184. var InterpolateValueAction = (function (_super) {
  23185. __extends(InterpolateValueAction, _super);
  23186. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  23187. if (duration === void 0) { duration = 1000; }
  23188. _super.call(this, triggerOptions, condition);
  23189. this.propertyPath = propertyPath;
  23190. this.value = value;
  23191. this.duration = duration;
  23192. this.stopOtherAnimations = stopOtherAnimations;
  23193. this._target = target;
  23194. }
  23195. InterpolateValueAction.prototype._prepare = function () {
  23196. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23197. this._property = this._getProperty(this.propertyPath);
  23198. };
  23199. InterpolateValueAction.prototype.execute = function () {
  23200. var scene = this._actionManager.getScene();
  23201. var keys = [
  23202. {
  23203. frame: 0,
  23204. value: this._target[this._property]
  23205. },
  23206. {
  23207. frame: 100,
  23208. value: this.value
  23209. }
  23210. ];
  23211. var dataType;
  23212. if (typeof this.value === "number") {
  23213. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  23214. }
  23215. else if (this.value instanceof BABYLON.Color3) {
  23216. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  23217. }
  23218. else if (this.value instanceof BABYLON.Vector3) {
  23219. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  23220. }
  23221. else if (this.value instanceof BABYLON.Matrix) {
  23222. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  23223. }
  23224. else if (this.value instanceof BABYLON.Quaternion) {
  23225. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  23226. }
  23227. else {
  23228. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  23229. return;
  23230. }
  23231. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  23232. animation.setKeys(keys);
  23233. if (this.stopOtherAnimations) {
  23234. scene.stopAnimation(this._target);
  23235. }
  23236. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  23237. };
  23238. return InterpolateValueAction;
  23239. })(BABYLON.Action);
  23240. BABYLON.InterpolateValueAction = InterpolateValueAction;
  23241. })(BABYLON || (BABYLON = {}));
  23242. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  23243. var BABYLON;
  23244. (function (BABYLON) {
  23245. var SwitchBooleanAction = (function (_super) {
  23246. __extends(SwitchBooleanAction, _super);
  23247. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  23248. _super.call(this, triggerOptions, condition);
  23249. this.propertyPath = propertyPath;
  23250. this._target = target;
  23251. }
  23252. SwitchBooleanAction.prototype._prepare = function () {
  23253. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23254. this._property = this._getProperty(this.propertyPath);
  23255. };
  23256. SwitchBooleanAction.prototype.execute = function () {
  23257. this._target[this._property] = !this._target[this._property];
  23258. };
  23259. return SwitchBooleanAction;
  23260. })(BABYLON.Action);
  23261. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  23262. var SetStateAction = (function (_super) {
  23263. __extends(SetStateAction, _super);
  23264. function SetStateAction(triggerOptions, target, value, condition) {
  23265. _super.call(this, triggerOptions, condition);
  23266. this.value = value;
  23267. this._target = target;
  23268. }
  23269. SetStateAction.prototype.execute = function () {
  23270. this._target.state = this.value;
  23271. };
  23272. return SetStateAction;
  23273. })(BABYLON.Action);
  23274. BABYLON.SetStateAction = SetStateAction;
  23275. var SetValueAction = (function (_super) {
  23276. __extends(SetValueAction, _super);
  23277. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  23278. _super.call(this, triggerOptions, condition);
  23279. this.propertyPath = propertyPath;
  23280. this.value = value;
  23281. this._target = target;
  23282. }
  23283. SetValueAction.prototype._prepare = function () {
  23284. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23285. this._property = this._getProperty(this.propertyPath);
  23286. };
  23287. SetValueAction.prototype.execute = function () {
  23288. this._target[this._property] = this.value;
  23289. };
  23290. return SetValueAction;
  23291. })(BABYLON.Action);
  23292. BABYLON.SetValueAction = SetValueAction;
  23293. var IncrementValueAction = (function (_super) {
  23294. __extends(IncrementValueAction, _super);
  23295. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  23296. _super.call(this, triggerOptions, condition);
  23297. this.propertyPath = propertyPath;
  23298. this.value = value;
  23299. this._target = target;
  23300. }
  23301. IncrementValueAction.prototype._prepare = function () {
  23302. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23303. this._property = this._getProperty(this.propertyPath);
  23304. if (typeof this._target[this._property] !== "number") {
  23305. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  23306. }
  23307. };
  23308. IncrementValueAction.prototype.execute = function () {
  23309. this._target[this._property] += this.value;
  23310. };
  23311. return IncrementValueAction;
  23312. })(BABYLON.Action);
  23313. BABYLON.IncrementValueAction = IncrementValueAction;
  23314. var PlayAnimationAction = (function (_super) {
  23315. __extends(PlayAnimationAction, _super);
  23316. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  23317. _super.call(this, triggerOptions, condition);
  23318. this.from = from;
  23319. this.to = to;
  23320. this.loop = loop;
  23321. this._target = target;
  23322. }
  23323. PlayAnimationAction.prototype._prepare = function () {
  23324. };
  23325. PlayAnimationAction.prototype.execute = function () {
  23326. var scene = this._actionManager.getScene();
  23327. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  23328. };
  23329. return PlayAnimationAction;
  23330. })(BABYLON.Action);
  23331. BABYLON.PlayAnimationAction = PlayAnimationAction;
  23332. var StopAnimationAction = (function (_super) {
  23333. __extends(StopAnimationAction, _super);
  23334. function StopAnimationAction(triggerOptions, target, condition) {
  23335. _super.call(this, triggerOptions, condition);
  23336. this._target = target;
  23337. }
  23338. StopAnimationAction.prototype._prepare = function () {
  23339. };
  23340. StopAnimationAction.prototype.execute = function () {
  23341. var scene = this._actionManager.getScene();
  23342. scene.stopAnimation(this._target);
  23343. };
  23344. return StopAnimationAction;
  23345. })(BABYLON.Action);
  23346. BABYLON.StopAnimationAction = StopAnimationAction;
  23347. var DoNothingAction = (function (_super) {
  23348. __extends(DoNothingAction, _super);
  23349. function DoNothingAction(triggerOptions, condition) {
  23350. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  23351. _super.call(this, triggerOptions, condition);
  23352. }
  23353. DoNothingAction.prototype.execute = function () {
  23354. };
  23355. return DoNothingAction;
  23356. })(BABYLON.Action);
  23357. BABYLON.DoNothingAction = DoNothingAction;
  23358. var CombineAction = (function (_super) {
  23359. __extends(CombineAction, _super);
  23360. function CombineAction(triggerOptions, children, condition) {
  23361. _super.call(this, triggerOptions, condition);
  23362. this.children = children;
  23363. }
  23364. CombineAction.prototype._prepare = function () {
  23365. for (var index = 0; index < this.children.length; index++) {
  23366. this.children[index]._actionManager = this._actionManager;
  23367. this.children[index]._prepare();
  23368. }
  23369. };
  23370. CombineAction.prototype.execute = function (evt) {
  23371. for (var index = 0; index < this.children.length; index++) {
  23372. this.children[index].execute(evt);
  23373. }
  23374. };
  23375. return CombineAction;
  23376. })(BABYLON.Action);
  23377. BABYLON.CombineAction = CombineAction;
  23378. var ExecuteCodeAction = (function (_super) {
  23379. __extends(ExecuteCodeAction, _super);
  23380. function ExecuteCodeAction(triggerOptions, func, condition) {
  23381. _super.call(this, triggerOptions, condition);
  23382. this.func = func;
  23383. }
  23384. ExecuteCodeAction.prototype.execute = function (evt) {
  23385. this.func(evt);
  23386. };
  23387. return ExecuteCodeAction;
  23388. })(BABYLON.Action);
  23389. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  23390. var SetParentAction = (function (_super) {
  23391. __extends(SetParentAction, _super);
  23392. function SetParentAction(triggerOptions, target, parent, condition) {
  23393. _super.call(this, triggerOptions, condition);
  23394. this._target = target;
  23395. this._parent = parent;
  23396. }
  23397. SetParentAction.prototype._prepare = function () {
  23398. };
  23399. SetParentAction.prototype.execute = function () {
  23400. if (this._target.parent === this._parent) {
  23401. return;
  23402. }
  23403. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  23404. invertParentWorldMatrix.invert();
  23405. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  23406. this._target.parent = this._parent;
  23407. };
  23408. return SetParentAction;
  23409. })(BABYLON.Action);
  23410. BABYLON.SetParentAction = SetParentAction;
  23411. })(BABYLON || (BABYLON = {}));
  23412. //# sourceMappingURL=babylon.directActions.js.map
  23413. var BABYLON;
  23414. (function (BABYLON) {
  23415. var Geometry = (function () {
  23416. function Geometry(id, scene, vertexData, updatable, mesh) {
  23417. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23418. this._totalVertices = 0;
  23419. this._indices = [];
  23420. this.id = id;
  23421. this._engine = scene.getEngine();
  23422. this._meshes = [];
  23423. this._scene = scene;
  23424. // vertexData
  23425. if (vertexData) {
  23426. this.setAllVerticesData(vertexData, updatable);
  23427. }
  23428. else {
  23429. this._totalVertices = 0;
  23430. this._indices = [];
  23431. }
  23432. // applyToMesh
  23433. if (mesh) {
  23434. this.applyToMesh(mesh);
  23435. }
  23436. }
  23437. Geometry.prototype.getScene = function () {
  23438. return this._scene;
  23439. };
  23440. Geometry.prototype.getEngine = function () {
  23441. return this._engine;
  23442. };
  23443. Geometry.prototype.isReady = function () {
  23444. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  23445. };
  23446. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  23447. vertexData.applyToGeometry(this, updatable);
  23448. };
  23449. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23450. this._vertexBuffers = this._vertexBuffers || {};
  23451. if (this._vertexBuffers[kind]) {
  23452. this._vertexBuffers[kind].dispose();
  23453. }
  23454. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  23455. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23456. stride = this._vertexBuffers[kind].getStrideSize();
  23457. this._totalVertices = data.length / stride;
  23458. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23459. var meshes = this._meshes;
  23460. var numOfMeshes = meshes.length;
  23461. for (var index = 0; index < numOfMeshes; index++) {
  23462. var mesh = meshes[index];
  23463. mesh._resetPointsArrayCache();
  23464. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23465. mesh._createGlobalSubMesh();
  23466. mesh.computeWorldMatrix(true);
  23467. }
  23468. }
  23469. };
  23470. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  23471. var vertexBuffer = this.getVertexBuffer(kind);
  23472. if (!vertexBuffer) {
  23473. return;
  23474. }
  23475. vertexBuffer.updateDirectly(data, offset);
  23476. };
  23477. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  23478. var vertexBuffer = this.getVertexBuffer(kind);
  23479. if (!vertexBuffer) {
  23480. return;
  23481. }
  23482. vertexBuffer.update(data);
  23483. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23484. var extend;
  23485. var stride = vertexBuffer.getStrideSize();
  23486. this._totalVertices = data.length / stride;
  23487. if (updateExtends) {
  23488. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23489. }
  23490. var meshes = this._meshes;
  23491. var numOfMeshes = meshes.length;
  23492. for (var index = 0; index < numOfMeshes; index++) {
  23493. var mesh = meshes[index];
  23494. mesh._resetPointsArrayCache();
  23495. if (updateExtends) {
  23496. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23497. }
  23498. }
  23499. }
  23500. };
  23501. Geometry.prototype.getTotalVertices = function () {
  23502. if (!this.isReady()) {
  23503. return 0;
  23504. }
  23505. return this._totalVertices;
  23506. };
  23507. Geometry.prototype.getVerticesData = function (kind) {
  23508. var vertexBuffer = this.getVertexBuffer(kind);
  23509. if (!vertexBuffer) {
  23510. return null;
  23511. }
  23512. return vertexBuffer.getData();
  23513. };
  23514. Geometry.prototype.getVertexBuffer = function (kind) {
  23515. if (!this.isReady()) {
  23516. return null;
  23517. }
  23518. return this._vertexBuffers[kind];
  23519. };
  23520. Geometry.prototype.getVertexBuffers = function () {
  23521. if (!this.isReady()) {
  23522. return null;
  23523. }
  23524. return this._vertexBuffers;
  23525. };
  23526. Geometry.prototype.isVerticesDataPresent = function (kind) {
  23527. if (!this._vertexBuffers) {
  23528. if (this._delayInfo) {
  23529. return this._delayInfo.indexOf(kind) !== -1;
  23530. }
  23531. return false;
  23532. }
  23533. return this._vertexBuffers[kind] !== undefined;
  23534. };
  23535. Geometry.prototype.getVerticesDataKinds = function () {
  23536. var result = [];
  23537. if (!this._vertexBuffers && this._delayInfo) {
  23538. for (var kind in this._delayInfo) {
  23539. result.push(kind);
  23540. }
  23541. }
  23542. else {
  23543. for (kind in this._vertexBuffers) {
  23544. result.push(kind);
  23545. }
  23546. }
  23547. return result;
  23548. };
  23549. Geometry.prototype.setIndices = function (indices, totalVertices) {
  23550. if (this._indexBuffer) {
  23551. this._engine._releaseBuffer(this._indexBuffer);
  23552. }
  23553. this._indices = indices;
  23554. if (this._meshes.length !== 0 && this._indices) {
  23555. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23556. }
  23557. if (totalVertices !== undefined) {
  23558. this._totalVertices = totalVertices;
  23559. }
  23560. var meshes = this._meshes;
  23561. var numOfMeshes = meshes.length;
  23562. for (var index = 0; index < numOfMeshes; index++) {
  23563. meshes[index]._createGlobalSubMesh();
  23564. }
  23565. };
  23566. Geometry.prototype.getTotalIndices = function () {
  23567. if (!this.isReady()) {
  23568. return 0;
  23569. }
  23570. return this._indices.length;
  23571. };
  23572. Geometry.prototype.getIndices = function () {
  23573. if (!this.isReady()) {
  23574. return null;
  23575. }
  23576. return this._indices;
  23577. };
  23578. Geometry.prototype.getIndexBuffer = function () {
  23579. if (!this.isReady()) {
  23580. return null;
  23581. }
  23582. return this._indexBuffer;
  23583. };
  23584. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  23585. var meshes = this._meshes;
  23586. var index = meshes.indexOf(mesh);
  23587. if (index === -1) {
  23588. return;
  23589. }
  23590. for (var kind in this._vertexBuffers) {
  23591. this._vertexBuffers[kind].dispose();
  23592. }
  23593. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  23594. this._indexBuffer = null;
  23595. }
  23596. meshes.splice(index, 1);
  23597. mesh._geometry = null;
  23598. if (meshes.length === 0 && shouldDispose) {
  23599. this.dispose();
  23600. }
  23601. };
  23602. Geometry.prototype.applyToMesh = function (mesh) {
  23603. if (mesh._geometry === this) {
  23604. return;
  23605. }
  23606. var previousGeometry = mesh._geometry;
  23607. if (previousGeometry) {
  23608. previousGeometry.releaseForMesh(mesh);
  23609. }
  23610. var meshes = this._meshes;
  23611. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  23612. mesh._geometry = this;
  23613. this._scene.pushGeometry(this);
  23614. meshes.push(mesh);
  23615. if (this.isReady()) {
  23616. this._applyToMesh(mesh);
  23617. }
  23618. else {
  23619. mesh._boundingInfo = this._boundingInfo;
  23620. }
  23621. };
  23622. Geometry.prototype._applyToMesh = function (mesh) {
  23623. var numOfMeshes = this._meshes.length;
  23624. for (var kind in this._vertexBuffers) {
  23625. if (numOfMeshes === 1) {
  23626. this._vertexBuffers[kind].create();
  23627. }
  23628. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  23629. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23630. mesh._resetPointsArrayCache();
  23631. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  23632. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23633. mesh._createGlobalSubMesh();
  23634. //bounding info was just created again, world matrix should be applied again.
  23635. mesh._updateBoundingInfo();
  23636. }
  23637. }
  23638. // indexBuffer
  23639. if (numOfMeshes === 1 && this._indices) {
  23640. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23641. }
  23642. if (this._indexBuffer) {
  23643. this._indexBuffer.references = numOfMeshes;
  23644. }
  23645. };
  23646. Geometry.prototype.load = function (scene, onLoaded) {
  23647. var _this = this;
  23648. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23649. return;
  23650. }
  23651. if (this.isReady()) {
  23652. if (onLoaded) {
  23653. onLoaded();
  23654. }
  23655. return;
  23656. }
  23657. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23658. scene._addPendingData(this);
  23659. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23660. _this._delayLoadingFunction(JSON.parse(data), _this);
  23661. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23662. _this._delayInfo = [];
  23663. scene._removePendingData(_this);
  23664. var meshes = _this._meshes;
  23665. var numOfMeshes = meshes.length;
  23666. for (var index = 0; index < numOfMeshes; index++) {
  23667. _this._applyToMesh(meshes[index]);
  23668. }
  23669. if (onLoaded) {
  23670. onLoaded();
  23671. }
  23672. }, function () {
  23673. }, scene.database);
  23674. };
  23675. Geometry.prototype.dispose = function () {
  23676. var meshes = this._meshes;
  23677. var numOfMeshes = meshes.length;
  23678. var index;
  23679. for (index = 0; index < numOfMeshes; index++) {
  23680. this.releaseForMesh(meshes[index]);
  23681. }
  23682. this._meshes = [];
  23683. for (var kind in this._vertexBuffers) {
  23684. this._vertexBuffers[kind].dispose();
  23685. }
  23686. this._vertexBuffers = [];
  23687. this._totalVertices = 0;
  23688. if (this._indexBuffer) {
  23689. this._engine._releaseBuffer(this._indexBuffer);
  23690. }
  23691. this._indexBuffer = null;
  23692. this._indices = [];
  23693. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23694. this.delayLoadingFile = null;
  23695. this._delayLoadingFunction = null;
  23696. this._delayInfo = [];
  23697. this._boundingInfo = null; // todo: .dispose()
  23698. var geometries = this._scene.getGeometries();
  23699. index = geometries.indexOf(this);
  23700. if (index > -1) {
  23701. geometries.splice(index, 1);
  23702. }
  23703. };
  23704. Geometry.prototype.copy = function (id) {
  23705. var vertexData = new BABYLON.VertexData();
  23706. vertexData.indices = [];
  23707. var indices = this.getIndices();
  23708. for (var index = 0; index < indices.length; index++) {
  23709. vertexData.indices.push(indices[index]);
  23710. }
  23711. var updatable = false;
  23712. var stopChecking = false;
  23713. for (var kind in this._vertexBuffers) {
  23714. vertexData.set(this.getVerticesData(kind), kind);
  23715. if (!stopChecking) {
  23716. updatable = this.getVertexBuffer(kind).isUpdatable();
  23717. stopChecking = !updatable;
  23718. }
  23719. }
  23720. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  23721. geometry.delayLoadState = this.delayLoadState;
  23722. geometry.delayLoadingFile = this.delayLoadingFile;
  23723. geometry._delayLoadingFunction = this._delayLoadingFunction;
  23724. for (kind in this._delayInfo) {
  23725. geometry._delayInfo = geometry._delayInfo || [];
  23726. geometry._delayInfo.push(kind);
  23727. }
  23728. // Bounding info
  23729. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  23730. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23731. return geometry;
  23732. };
  23733. // Statics
  23734. Geometry.ExtractFromMesh = function (mesh, id) {
  23735. var geometry = mesh._geometry;
  23736. if (!geometry) {
  23737. return null;
  23738. }
  23739. return geometry.copy(id);
  23740. };
  23741. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  23742. // be aware Math.random() could cause collisions
  23743. Geometry.RandomId = function () {
  23744. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  23745. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  23746. return v.toString(16);
  23747. });
  23748. };
  23749. return Geometry;
  23750. })();
  23751. BABYLON.Geometry = Geometry;
  23752. /////// Primitives //////////////////////////////////////////////
  23753. var Geometry;
  23754. (function (Geometry) {
  23755. var Primitives;
  23756. (function (Primitives) {
  23757. /// Abstract class
  23758. var _Primitive = (function (_super) {
  23759. __extends(_Primitive, _super);
  23760. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  23761. this._beingRegenerated = true;
  23762. this._canBeRegenerated = canBeRegenerated;
  23763. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  23764. this._beingRegenerated = false;
  23765. }
  23766. _Primitive.prototype.canBeRegenerated = function () {
  23767. return this._canBeRegenerated;
  23768. };
  23769. _Primitive.prototype.regenerate = function () {
  23770. if (!this._canBeRegenerated) {
  23771. return;
  23772. }
  23773. this._beingRegenerated = true;
  23774. this.setAllVerticesData(this._regenerateVertexData(), false);
  23775. this._beingRegenerated = false;
  23776. };
  23777. _Primitive.prototype.asNewGeometry = function (id) {
  23778. return _super.prototype.copy.call(this, id);
  23779. };
  23780. // overrides
  23781. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  23782. if (!this._beingRegenerated) {
  23783. return;
  23784. }
  23785. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  23786. };
  23787. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  23788. if (!this._beingRegenerated) {
  23789. return;
  23790. }
  23791. _super.prototype.setVerticesData.call(this, kind, data, false);
  23792. };
  23793. // to override
  23794. // protected
  23795. _Primitive.prototype._regenerateVertexData = function () {
  23796. throw new Error("Abstract method");
  23797. };
  23798. _Primitive.prototype.copy = function (id) {
  23799. throw new Error("Must be overriden in sub-classes.");
  23800. };
  23801. return _Primitive;
  23802. })(Geometry);
  23803. Primitives._Primitive = _Primitive;
  23804. var Box = (function (_super) {
  23805. __extends(Box, _super);
  23806. function Box(id, scene, size, canBeRegenerated, mesh) {
  23807. this.size = size;
  23808. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23809. }
  23810. Box.prototype._regenerateVertexData = function () {
  23811. return BABYLON.VertexData.CreateBox(this.size);
  23812. };
  23813. Box.prototype.copy = function (id) {
  23814. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23815. };
  23816. return Box;
  23817. })(_Primitive);
  23818. Primitives.Box = Box;
  23819. var Sphere = (function (_super) {
  23820. __extends(Sphere, _super);
  23821. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  23822. this.segments = segments;
  23823. this.diameter = diameter;
  23824. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23825. }
  23826. Sphere.prototype._regenerateVertexData = function () {
  23827. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  23828. };
  23829. Sphere.prototype.copy = function (id) {
  23830. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  23831. };
  23832. return Sphere;
  23833. })(_Primitive);
  23834. Primitives.Sphere = Sphere;
  23835. var Cylinder = (function (_super) {
  23836. __extends(Cylinder, _super);
  23837. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  23838. if (subdivisions === void 0) { subdivisions = 1; }
  23839. this.height = height;
  23840. this.diameterTop = diameterTop;
  23841. this.diameterBottom = diameterBottom;
  23842. this.tessellation = tessellation;
  23843. this.subdivisions = subdivisions;
  23844. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23845. }
  23846. Cylinder.prototype._regenerateVertexData = function () {
  23847. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  23848. };
  23849. Cylinder.prototype.copy = function (id) {
  23850. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  23851. };
  23852. return Cylinder;
  23853. })(_Primitive);
  23854. Primitives.Cylinder = Cylinder;
  23855. var Torus = (function (_super) {
  23856. __extends(Torus, _super);
  23857. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  23858. this.diameter = diameter;
  23859. this.thickness = thickness;
  23860. this.tessellation = tessellation;
  23861. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23862. }
  23863. Torus.prototype._regenerateVertexData = function () {
  23864. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  23865. };
  23866. Torus.prototype.copy = function (id) {
  23867. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  23868. };
  23869. return Torus;
  23870. })(_Primitive);
  23871. Primitives.Torus = Torus;
  23872. var Ground = (function (_super) {
  23873. __extends(Ground, _super);
  23874. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  23875. this.width = width;
  23876. this.height = height;
  23877. this.subdivisions = subdivisions;
  23878. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23879. }
  23880. Ground.prototype._regenerateVertexData = function () {
  23881. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  23882. };
  23883. Ground.prototype.copy = function (id) {
  23884. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  23885. };
  23886. return Ground;
  23887. })(_Primitive);
  23888. Primitives.Ground = Ground;
  23889. var TiledGround = (function (_super) {
  23890. __extends(TiledGround, _super);
  23891. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  23892. this.xmin = xmin;
  23893. this.zmin = zmin;
  23894. this.xmax = xmax;
  23895. this.zmax = zmax;
  23896. this.subdivisions = subdivisions;
  23897. this.precision = precision;
  23898. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23899. }
  23900. TiledGround.prototype._regenerateVertexData = function () {
  23901. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  23902. };
  23903. TiledGround.prototype.copy = function (id) {
  23904. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  23905. };
  23906. return TiledGround;
  23907. })(_Primitive);
  23908. Primitives.TiledGround = TiledGround;
  23909. var Plane = (function (_super) {
  23910. __extends(Plane, _super);
  23911. function Plane(id, scene, size, canBeRegenerated, mesh) {
  23912. this.size = size;
  23913. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23914. }
  23915. Plane.prototype._regenerateVertexData = function () {
  23916. return BABYLON.VertexData.CreatePlane(this.size);
  23917. };
  23918. Plane.prototype.copy = function (id) {
  23919. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23920. };
  23921. return Plane;
  23922. })(_Primitive);
  23923. Primitives.Plane = Plane;
  23924. var TorusKnot = (function (_super) {
  23925. __extends(TorusKnot, _super);
  23926. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  23927. this.radius = radius;
  23928. this.tube = tube;
  23929. this.radialSegments = radialSegments;
  23930. this.tubularSegments = tubularSegments;
  23931. this.p = p;
  23932. this.q = q;
  23933. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23934. }
  23935. TorusKnot.prototype._regenerateVertexData = function () {
  23936. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  23937. };
  23938. TorusKnot.prototype.copy = function (id) {
  23939. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  23940. };
  23941. return TorusKnot;
  23942. })(_Primitive);
  23943. Primitives.TorusKnot = TorusKnot;
  23944. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  23945. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  23946. })(BABYLON || (BABYLON = {}));
  23947. //# sourceMappingURL=babylon.geometry.js.map
  23948. var BABYLON;
  23949. (function (BABYLON) {
  23950. var Gamepads = (function () {
  23951. function Gamepads(ongamedpadconnected) {
  23952. var _this = this;
  23953. this.babylonGamepads = [];
  23954. this.oneGamepadConnected = false;
  23955. this.isMonitoring = false;
  23956. this.gamepadEventSupported = 'GamepadEvent' in window;
  23957. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  23958. 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=";
  23959. this._callbackGamepadConnected = ongamedpadconnected;
  23960. if (this.gamepadSupportAvailable) {
  23961. // Checking if the gamepad connected event is supported (like in Firefox)
  23962. if (this.gamepadEventSupported) {
  23963. window.addEventListener('gamepadconnected', function (evt) {
  23964. _this._onGamepadConnected(evt);
  23965. }, false);
  23966. window.addEventListener('gamepaddisconnected', function (evt) {
  23967. _this._onGamepadDisconnected(evt);
  23968. }, false);
  23969. }
  23970. else {
  23971. this._startMonitoringGamepads();
  23972. }
  23973. if (!this.oneGamepadConnected) {
  23974. this._insertGamepadDOMInstructions();
  23975. }
  23976. }
  23977. else {
  23978. this._insertGamepadDOMNotSupported();
  23979. }
  23980. }
  23981. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  23982. Gamepads.gamepadDOMInfo = document.createElement("div");
  23983. var buttonAImage = document.createElement("img");
  23984. buttonAImage.src = this.buttonADataURL;
  23985. var spanMessage = document.createElement("span");
  23986. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  23987. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  23988. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23989. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23990. Gamepads.gamepadDOMInfo.style.width = "100%";
  23991. Gamepads.gamepadDOMInfo.style.height = "48px";
  23992. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23993. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23994. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23995. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23996. buttonAImage.style.position = "relative";
  23997. buttonAImage.style.bottom = "8px";
  23998. spanMessage.style.position = "relative";
  23999. spanMessage.style.fontSize = "32px";
  24000. spanMessage.style.bottom = "32px";
  24001. spanMessage.style.color = "green";
  24002. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24003. };
  24004. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  24005. Gamepads.gamepadDOMInfo = document.createElement("div");
  24006. var spanMessage = document.createElement("span");
  24007. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  24008. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24009. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24010. Gamepads.gamepadDOMInfo.style.width = "100%";
  24011. Gamepads.gamepadDOMInfo.style.height = "40px";
  24012. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24013. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24014. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24015. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24016. spanMessage.style.position = "relative";
  24017. spanMessage.style.fontSize = "32px";
  24018. spanMessage.style.color = "red";
  24019. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24020. };
  24021. Gamepads.prototype.dispose = function () {
  24022. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24023. };
  24024. Gamepads.prototype._onGamepadConnected = function (evt) {
  24025. var newGamepad = this._addNewGamepad(evt.gamepad);
  24026. if (this._callbackGamepadConnected)
  24027. this._callbackGamepadConnected(newGamepad);
  24028. this._startMonitoringGamepads();
  24029. };
  24030. Gamepads.prototype._addNewGamepad = function (gamepad) {
  24031. if (!this.oneGamepadConnected) {
  24032. this.oneGamepadConnected = true;
  24033. if (Gamepads.gamepadDOMInfo) {
  24034. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24035. Gamepads.gamepadDOMInfo = null;
  24036. }
  24037. }
  24038. var newGamepad;
  24039. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  24040. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  24041. }
  24042. else {
  24043. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  24044. }
  24045. this.babylonGamepads.push(newGamepad);
  24046. return newGamepad;
  24047. };
  24048. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  24049. for (var i in this.babylonGamepads) {
  24050. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  24051. this.babylonGamepads.splice(i, 1);
  24052. break;
  24053. }
  24054. }
  24055. // If no gamepads are left, stop the polling loop.
  24056. if (this.babylonGamepads.length == 0) {
  24057. this._stopMonitoringGamepads();
  24058. }
  24059. };
  24060. Gamepads.prototype._startMonitoringGamepads = function () {
  24061. if (!this.isMonitoring) {
  24062. this.isMonitoring = true;
  24063. this._checkGamepadsStatus();
  24064. }
  24065. };
  24066. Gamepads.prototype._stopMonitoringGamepads = function () {
  24067. this.isMonitoring = false;
  24068. };
  24069. Gamepads.prototype._checkGamepadsStatus = function () {
  24070. var _this = this;
  24071. // updating gamepad objects
  24072. this._updateGamepadObjects();
  24073. for (var i in this.babylonGamepads) {
  24074. this.babylonGamepads[i].update();
  24075. }
  24076. if (this.isMonitoring) {
  24077. if (window.requestAnimationFrame) {
  24078. window.requestAnimationFrame(function () {
  24079. _this._checkGamepadsStatus();
  24080. });
  24081. }
  24082. else if (window.mozRequestAnimationFrame) {
  24083. window.mozRequestAnimationFrame(function () {
  24084. _this._checkGamepadsStatus();
  24085. });
  24086. }
  24087. else if (window.webkitRequestAnimationFrame) {
  24088. window.webkitRequestAnimationFrame(function () {
  24089. _this._checkGamepadsStatus();
  24090. });
  24091. }
  24092. }
  24093. };
  24094. // This function is called only on Chrome, which does not yet support
  24095. // connection/disconnection events, but requires you to monitor
  24096. // an array for changes.
  24097. Gamepads.prototype._updateGamepadObjects = function () {
  24098. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  24099. for (var i = 0; i < gamepads.length; i++) {
  24100. if (gamepads[i]) {
  24101. if (!(gamepads[i].index in this.babylonGamepads)) {
  24102. var newGamepad = this._addNewGamepad(gamepads[i]);
  24103. if (this._callbackGamepadConnected) {
  24104. this._callbackGamepadConnected(newGamepad);
  24105. }
  24106. }
  24107. else {
  24108. this.babylonGamepads[i].browserGamepad = gamepads[i];
  24109. }
  24110. }
  24111. }
  24112. };
  24113. return Gamepads;
  24114. })();
  24115. BABYLON.Gamepads = Gamepads;
  24116. var StickValues = (function () {
  24117. function StickValues(x, y) {
  24118. this.x = x;
  24119. this.y = y;
  24120. }
  24121. return StickValues;
  24122. })();
  24123. BABYLON.StickValues = StickValues;
  24124. var Gamepad = (function () {
  24125. function Gamepad(id, index, browserGamepad) {
  24126. this.id = id;
  24127. this.index = index;
  24128. this.browserGamepad = browserGamepad;
  24129. if (this.browserGamepad.axes.length >= 2) {
  24130. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24131. }
  24132. if (this.browserGamepad.axes.length >= 4) {
  24133. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24134. }
  24135. }
  24136. Gamepad.prototype.onleftstickchanged = function (callback) {
  24137. this._onleftstickchanged = callback;
  24138. };
  24139. Gamepad.prototype.onrightstickchanged = function (callback) {
  24140. this._onrightstickchanged = callback;
  24141. };
  24142. Object.defineProperty(Gamepad.prototype, "leftStick", {
  24143. get: function () {
  24144. return this._leftStick;
  24145. },
  24146. set: function (newValues) {
  24147. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  24148. this._onleftstickchanged(newValues);
  24149. }
  24150. this._leftStick = newValues;
  24151. },
  24152. enumerable: true,
  24153. configurable: true
  24154. });
  24155. Object.defineProperty(Gamepad.prototype, "rightStick", {
  24156. get: function () {
  24157. return this._rightStick;
  24158. },
  24159. set: function (newValues) {
  24160. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  24161. this._onrightstickchanged(newValues);
  24162. }
  24163. this._rightStick = newValues;
  24164. },
  24165. enumerable: true,
  24166. configurable: true
  24167. });
  24168. Gamepad.prototype.update = function () {
  24169. if (this._leftStick) {
  24170. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24171. }
  24172. if (this._rightStick) {
  24173. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24174. }
  24175. };
  24176. return Gamepad;
  24177. })();
  24178. BABYLON.Gamepad = Gamepad;
  24179. var GenericPad = (function (_super) {
  24180. __extends(GenericPad, _super);
  24181. function GenericPad(id, index, gamepad) {
  24182. _super.call(this, id, index, gamepad);
  24183. this.id = id;
  24184. this.index = index;
  24185. this.gamepad = gamepad;
  24186. this._buttons = new Array(gamepad.buttons.length);
  24187. }
  24188. GenericPad.prototype.onbuttondown = function (callback) {
  24189. this._onbuttondown = callback;
  24190. };
  24191. GenericPad.prototype.onbuttonup = function (callback) {
  24192. this._onbuttonup = callback;
  24193. };
  24194. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  24195. if (newValue !== currentValue) {
  24196. if (this._onbuttondown && newValue === 1) {
  24197. this._onbuttondown(buttonIndex);
  24198. }
  24199. if (this._onbuttonup && newValue === 0) {
  24200. this._onbuttonup(buttonIndex);
  24201. }
  24202. }
  24203. return newValue;
  24204. };
  24205. GenericPad.prototype.update = function () {
  24206. _super.prototype.update.call(this);
  24207. for (var index = 0; index < this._buttons.length; index++) {
  24208. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  24209. }
  24210. };
  24211. return GenericPad;
  24212. })(Gamepad);
  24213. BABYLON.GenericPad = GenericPad;
  24214. (function (Xbox360Button) {
  24215. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  24216. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  24217. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  24218. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  24219. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  24220. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  24221. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  24222. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  24223. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  24224. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  24225. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  24226. var Xbox360Button = BABYLON.Xbox360Button;
  24227. (function (Xbox360Dpad) {
  24228. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  24229. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  24230. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  24231. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  24232. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  24233. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  24234. var Xbox360Pad = (function (_super) {
  24235. __extends(Xbox360Pad, _super);
  24236. function Xbox360Pad() {
  24237. _super.apply(this, arguments);
  24238. this._leftTrigger = 0;
  24239. this._rightTrigger = 0;
  24240. this._buttonA = 0;
  24241. this._buttonB = 0;
  24242. this._buttonX = 0;
  24243. this._buttonY = 0;
  24244. this._buttonBack = 0;
  24245. this._buttonStart = 0;
  24246. this._buttonLB = 0;
  24247. this._buttonRB = 0;
  24248. this._buttonLeftStick = 0;
  24249. this._buttonRightStick = 0;
  24250. this._dPadUp = 0;
  24251. this._dPadDown = 0;
  24252. this._dPadLeft = 0;
  24253. this._dPadRight = 0;
  24254. }
  24255. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  24256. this._onlefttriggerchanged = callback;
  24257. };
  24258. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  24259. this._onrighttriggerchanged = callback;
  24260. };
  24261. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  24262. get: function () {
  24263. return this._leftTrigger;
  24264. },
  24265. set: function (newValue) {
  24266. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  24267. this._onlefttriggerchanged(newValue);
  24268. }
  24269. this._leftTrigger = newValue;
  24270. },
  24271. enumerable: true,
  24272. configurable: true
  24273. });
  24274. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  24275. get: function () {
  24276. return this._rightTrigger;
  24277. },
  24278. set: function (newValue) {
  24279. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  24280. this._onrighttriggerchanged(newValue);
  24281. }
  24282. this._rightTrigger = newValue;
  24283. },
  24284. enumerable: true,
  24285. configurable: true
  24286. });
  24287. Xbox360Pad.prototype.onbuttondown = function (callback) {
  24288. this._onbuttondown = callback;
  24289. };
  24290. Xbox360Pad.prototype.onbuttonup = function (callback) {
  24291. this._onbuttonup = callback;
  24292. };
  24293. Xbox360Pad.prototype.ondpaddown = function (callback) {
  24294. this._ondpaddown = callback;
  24295. };
  24296. Xbox360Pad.prototype.ondpadup = function (callback) {
  24297. this._ondpadup = callback;
  24298. };
  24299. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  24300. if (newValue !== currentValue) {
  24301. if (this._onbuttondown && newValue === 1) {
  24302. this._onbuttondown(buttonType);
  24303. }
  24304. if (this._onbuttonup && newValue === 0) {
  24305. this._onbuttonup(buttonType);
  24306. }
  24307. }
  24308. return newValue;
  24309. };
  24310. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  24311. if (newValue !== currentValue) {
  24312. if (this._ondpaddown && newValue === 1) {
  24313. this._ondpaddown(buttonType);
  24314. }
  24315. if (this._ondpadup && newValue === 0) {
  24316. this._ondpadup(buttonType);
  24317. }
  24318. }
  24319. return newValue;
  24320. };
  24321. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  24322. get: function () {
  24323. return this._buttonA;
  24324. },
  24325. set: function (value) {
  24326. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  24327. },
  24328. enumerable: true,
  24329. configurable: true
  24330. });
  24331. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  24332. get: function () {
  24333. return this._buttonB;
  24334. },
  24335. set: function (value) {
  24336. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  24337. },
  24338. enumerable: true,
  24339. configurable: true
  24340. });
  24341. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  24342. get: function () {
  24343. return this._buttonX;
  24344. },
  24345. set: function (value) {
  24346. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  24347. },
  24348. enumerable: true,
  24349. configurable: true
  24350. });
  24351. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  24352. get: function () {
  24353. return this._buttonY;
  24354. },
  24355. set: function (value) {
  24356. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  24357. },
  24358. enumerable: true,
  24359. configurable: true
  24360. });
  24361. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  24362. get: function () {
  24363. return this._buttonStart;
  24364. },
  24365. set: function (value) {
  24366. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  24367. },
  24368. enumerable: true,
  24369. configurable: true
  24370. });
  24371. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  24372. get: function () {
  24373. return this._buttonBack;
  24374. },
  24375. set: function (value) {
  24376. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  24377. },
  24378. enumerable: true,
  24379. configurable: true
  24380. });
  24381. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  24382. get: function () {
  24383. return this._buttonLB;
  24384. },
  24385. set: function (value) {
  24386. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  24387. },
  24388. enumerable: true,
  24389. configurable: true
  24390. });
  24391. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  24392. get: function () {
  24393. return this._buttonRB;
  24394. },
  24395. set: function (value) {
  24396. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  24397. },
  24398. enumerable: true,
  24399. configurable: true
  24400. });
  24401. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  24402. get: function () {
  24403. return this._buttonLeftStick;
  24404. },
  24405. set: function (value) {
  24406. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  24407. },
  24408. enumerable: true,
  24409. configurable: true
  24410. });
  24411. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  24412. get: function () {
  24413. return this._buttonRightStick;
  24414. },
  24415. set: function (value) {
  24416. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  24417. },
  24418. enumerable: true,
  24419. configurable: true
  24420. });
  24421. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  24422. get: function () {
  24423. return this._dPadUp;
  24424. },
  24425. set: function (value) {
  24426. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  24427. },
  24428. enumerable: true,
  24429. configurable: true
  24430. });
  24431. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  24432. get: function () {
  24433. return this._dPadDown;
  24434. },
  24435. set: function (value) {
  24436. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  24437. },
  24438. enumerable: true,
  24439. configurable: true
  24440. });
  24441. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  24442. get: function () {
  24443. return this._dPadLeft;
  24444. },
  24445. set: function (value) {
  24446. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  24447. },
  24448. enumerable: true,
  24449. configurable: true
  24450. });
  24451. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  24452. get: function () {
  24453. return this._dPadRight;
  24454. },
  24455. set: function (value) {
  24456. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  24457. },
  24458. enumerable: true,
  24459. configurable: true
  24460. });
  24461. Xbox360Pad.prototype.update = function () {
  24462. _super.prototype.update.call(this);
  24463. this.buttonA = this.browserGamepad.buttons[0].value;
  24464. this.buttonB = this.browserGamepad.buttons[1].value;
  24465. this.buttonX = this.browserGamepad.buttons[2].value;
  24466. this.buttonY = this.browserGamepad.buttons[3].value;
  24467. this.buttonLB = this.browserGamepad.buttons[4].value;
  24468. this.buttonRB = this.browserGamepad.buttons[5].value;
  24469. this.leftTrigger = this.browserGamepad.buttons[6].value;
  24470. this.rightTrigger = this.browserGamepad.buttons[7].value;
  24471. this.buttonBack = this.browserGamepad.buttons[8].value;
  24472. this.buttonStart = this.browserGamepad.buttons[9].value;
  24473. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  24474. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  24475. this.dPadUp = this.browserGamepad.buttons[12].value;
  24476. this.dPadDown = this.browserGamepad.buttons[13].value;
  24477. this.dPadLeft = this.browserGamepad.buttons[14].value;
  24478. this.dPadRight = this.browserGamepad.buttons[15].value;
  24479. };
  24480. return Xbox360Pad;
  24481. })(Gamepad);
  24482. BABYLON.Xbox360Pad = Xbox360Pad;
  24483. })(BABYLON || (BABYLON = {}));
  24484. //# sourceMappingURL=babylon.gamepads.js.map
  24485. var BABYLON;
  24486. (function (BABYLON) {
  24487. // We're mainly based on the logic defined into the FreeCamera code
  24488. var GamepadCamera = (function (_super) {
  24489. __extends(GamepadCamera, _super);
  24490. function GamepadCamera(name, position, scene) {
  24491. var _this = this;
  24492. _super.call(this, name, position, scene);
  24493. this.angularSensibility = 200;
  24494. this.moveSensibility = 75;
  24495. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  24496. _this._onNewGameConnected(gamepad);
  24497. });
  24498. }
  24499. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  24500. // Only the first gamepad can control the camera
  24501. if (gamepad.index === 0) {
  24502. this._gamepad = gamepad;
  24503. }
  24504. };
  24505. GamepadCamera.prototype._checkInputs = function () {
  24506. if (!this._gamepad) {
  24507. return;
  24508. }
  24509. var LSValues = this._gamepad.leftStick;
  24510. var normalizedLX = LSValues.x / this.moveSensibility;
  24511. var normalizedLY = LSValues.y / this.moveSensibility;
  24512. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  24513. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  24514. var RSValues = this._gamepad.rightStick;
  24515. var normalizedRX = RSValues.x / this.angularSensibility;
  24516. var normalizedRY = RSValues.y / this.angularSensibility;
  24517. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  24518. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  24519. ;
  24520. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24521. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  24522. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24523. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  24524. };
  24525. GamepadCamera.prototype.dispose = function () {
  24526. this._gamepads.dispose();
  24527. _super.prototype.dispose.call(this);
  24528. };
  24529. return GamepadCamera;
  24530. })(BABYLON.FreeCamera);
  24531. BABYLON.GamepadCamera = GamepadCamera;
  24532. })(BABYLON || (BABYLON = {}));
  24533. //# sourceMappingURL=babylon.gamepadCamera.js.map
  24534. var BABYLON;
  24535. (function (BABYLON) {
  24536. var LinesMesh = (function (_super) {
  24537. __extends(LinesMesh, _super);
  24538. function LinesMesh(name, scene, updatable) {
  24539. if (updatable === void 0) { updatable = false; }
  24540. _super.call(this, name, scene);
  24541. this.color = new BABYLON.Color3(1, 1, 1);
  24542. this.alpha = 1;
  24543. this._indices = new Array();
  24544. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  24545. attributes: ["position"],
  24546. uniforms: ["worldViewProjection", "color"],
  24547. needAlphaBlending: true
  24548. });
  24549. }
  24550. Object.defineProperty(LinesMesh.prototype, "material", {
  24551. get: function () {
  24552. return this._colorShader;
  24553. },
  24554. enumerable: true,
  24555. configurable: true
  24556. });
  24557. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  24558. get: function () {
  24559. return false;
  24560. },
  24561. enumerable: true,
  24562. configurable: true
  24563. });
  24564. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  24565. get: function () {
  24566. return false;
  24567. },
  24568. enumerable: true,
  24569. configurable: true
  24570. });
  24571. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  24572. var engine = this.getScene().getEngine();
  24573. var indexToBind = this._geometry.getIndexBuffer();
  24574. // VBOs
  24575. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  24576. // Color
  24577. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  24578. };
  24579. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  24580. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24581. return;
  24582. }
  24583. var engine = this.getScene().getEngine();
  24584. // Draw order
  24585. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  24586. };
  24587. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  24588. return null;
  24589. };
  24590. LinesMesh.prototype.dispose = function (doNotRecurse) {
  24591. this._colorShader.dispose();
  24592. _super.prototype.dispose.call(this, doNotRecurse);
  24593. };
  24594. return LinesMesh;
  24595. })(BABYLON.Mesh);
  24596. BABYLON.LinesMesh = LinesMesh;
  24597. })(BABYLON || (BABYLON = {}));
  24598. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  24599. (function (BABYLON) {
  24600. var OutlineRenderer = (function () {
  24601. function OutlineRenderer(scene) {
  24602. this._scene = scene;
  24603. }
  24604. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  24605. if (useOverlay === void 0) { useOverlay = false; }
  24606. var scene = this._scene;
  24607. var engine = this._scene.getEngine();
  24608. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24609. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  24610. return;
  24611. }
  24612. var mesh = subMesh.getRenderingMesh();
  24613. var material = subMesh.getMaterial();
  24614. engine.enableEffect(this._effect);
  24615. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  24616. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  24617. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24618. // Bones
  24619. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  24620. if (useBones) {
  24621. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24622. }
  24623. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  24624. // Alpha test
  24625. if (material && material.needAlphaTesting()) {
  24626. var alphaTexture = material.getAlphaTestTexture();
  24627. this._effect.setTexture("diffuseSampler", alphaTexture);
  24628. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  24629. }
  24630. if (hardwareInstancedRendering) {
  24631. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  24632. }
  24633. else {
  24634. if (batch.renderSelf[subMesh._id]) {
  24635. this._effect.setMatrix("world", mesh.getWorldMatrix());
  24636. // Draw
  24637. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  24638. }
  24639. if (batch.visibleInstances[subMesh._id]) {
  24640. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  24641. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  24642. this._effect.setMatrix("world", instance.getWorldMatrix());
  24643. // Draw
  24644. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  24645. }
  24646. }
  24647. }
  24648. };
  24649. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  24650. var defines = [];
  24651. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  24652. var mesh = subMesh.getMesh();
  24653. var material = subMesh.getMaterial();
  24654. // Alpha test
  24655. if (material && material.needAlphaTesting()) {
  24656. defines.push("#define ALPHATEST");
  24657. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24658. attribs.push(BABYLON.VertexBuffer.UVKind);
  24659. defines.push("#define UV1");
  24660. }
  24661. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24662. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  24663. defines.push("#define UV2");
  24664. }
  24665. }
  24666. // Bones
  24667. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24668. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24669. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24670. defines.push("#define BONES");
  24671. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24672. }
  24673. // Instances
  24674. if (useInstances) {
  24675. defines.push("#define INSTANCES");
  24676. attribs.push("world0");
  24677. attribs.push("world1");
  24678. attribs.push("world2");
  24679. attribs.push("world3");
  24680. }
  24681. // Get correct effect
  24682. var join = defines.join("\n");
  24683. if (this._cachedDefines != join) {
  24684. this._cachedDefines = join;
  24685. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  24686. }
  24687. return this._effect.isReady();
  24688. };
  24689. return OutlineRenderer;
  24690. })();
  24691. BABYLON.OutlineRenderer = OutlineRenderer;
  24692. })(BABYLON || (BABYLON = {}));
  24693. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  24694. (function (BABYLON) {
  24695. var MeshAssetTask = (function () {
  24696. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  24697. this.name = name;
  24698. this.meshesNames = meshesNames;
  24699. this.rootUrl = rootUrl;
  24700. this.sceneFilename = sceneFilename;
  24701. this.isCompleted = false;
  24702. }
  24703. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24704. var _this = this;
  24705. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  24706. _this.loadedMeshes = meshes;
  24707. _this.loadedParticleSystems = particleSystems;
  24708. _this.loadedSkeletons = skeletons;
  24709. _this.isCompleted = true;
  24710. if (_this.onSuccess) {
  24711. _this.onSuccess(_this);
  24712. }
  24713. onSuccess();
  24714. }, null, function () {
  24715. if (_this.onError) {
  24716. _this.onError(_this);
  24717. }
  24718. onError();
  24719. });
  24720. };
  24721. return MeshAssetTask;
  24722. })();
  24723. BABYLON.MeshAssetTask = MeshAssetTask;
  24724. var TextFileAssetTask = (function () {
  24725. function TextFileAssetTask(name, url) {
  24726. this.name = name;
  24727. this.url = url;
  24728. this.isCompleted = false;
  24729. }
  24730. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24731. var _this = this;
  24732. BABYLON.Tools.LoadFile(this.url, function (data) {
  24733. _this.text = data;
  24734. _this.isCompleted = true;
  24735. if (_this.onSuccess) {
  24736. _this.onSuccess(_this);
  24737. }
  24738. onSuccess();
  24739. }, null, scene.database, false, function () {
  24740. if (_this.onError) {
  24741. _this.onError(_this);
  24742. }
  24743. onError();
  24744. });
  24745. };
  24746. return TextFileAssetTask;
  24747. })();
  24748. BABYLON.TextFileAssetTask = TextFileAssetTask;
  24749. var BinaryFileAssetTask = (function () {
  24750. function BinaryFileAssetTask(name, url) {
  24751. this.name = name;
  24752. this.url = url;
  24753. this.isCompleted = false;
  24754. }
  24755. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24756. var _this = this;
  24757. BABYLON.Tools.LoadFile(this.url, function (data) {
  24758. _this.data = data;
  24759. _this.isCompleted = true;
  24760. if (_this.onSuccess) {
  24761. _this.onSuccess(_this);
  24762. }
  24763. onSuccess();
  24764. }, null, scene.database, true, function () {
  24765. if (_this.onError) {
  24766. _this.onError(_this);
  24767. }
  24768. onError();
  24769. });
  24770. };
  24771. return BinaryFileAssetTask;
  24772. })();
  24773. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  24774. var ImageAssetTask = (function () {
  24775. function ImageAssetTask(name, url) {
  24776. this.name = name;
  24777. this.url = url;
  24778. this.isCompleted = false;
  24779. }
  24780. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24781. var _this = this;
  24782. var img = new Image();
  24783. img.onload = function () {
  24784. _this.image = img;
  24785. _this.isCompleted = true;
  24786. if (_this.onSuccess) {
  24787. _this.onSuccess(_this);
  24788. }
  24789. onSuccess();
  24790. };
  24791. img.onerror = function () {
  24792. if (_this.onError) {
  24793. _this.onError(_this);
  24794. }
  24795. onError();
  24796. };
  24797. img.src = this.url;
  24798. };
  24799. return ImageAssetTask;
  24800. })();
  24801. BABYLON.ImageAssetTask = ImageAssetTask;
  24802. var TextureAssetTask = (function () {
  24803. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  24804. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24805. this.name = name;
  24806. this.url = url;
  24807. this.noMipmap = noMipmap;
  24808. this.invertY = invertY;
  24809. this.samplingMode = samplingMode;
  24810. this.isCompleted = false;
  24811. }
  24812. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24813. var _this = this;
  24814. var onload = function () {
  24815. _this.isCompleted = true;
  24816. if (_this.onSuccess) {
  24817. _this.onSuccess(_this);
  24818. }
  24819. onSuccess();
  24820. };
  24821. var onerror = function () {
  24822. if (_this.onError) {
  24823. _this.onError(_this);
  24824. }
  24825. onError();
  24826. };
  24827. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  24828. };
  24829. return TextureAssetTask;
  24830. })();
  24831. BABYLON.TextureAssetTask = TextureAssetTask;
  24832. var AssetsManager = (function () {
  24833. function AssetsManager(scene) {
  24834. this._tasks = new Array();
  24835. this._waitingTasksCount = 0;
  24836. this.useDefaultLoadingScreen = true;
  24837. this._scene = scene;
  24838. }
  24839. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  24840. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  24841. this._tasks.push(task);
  24842. return task;
  24843. };
  24844. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  24845. var task = new TextFileAssetTask(taskName, url);
  24846. this._tasks.push(task);
  24847. return task;
  24848. };
  24849. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  24850. var task = new BinaryFileAssetTask(taskName, url);
  24851. this._tasks.push(task);
  24852. return task;
  24853. };
  24854. AssetsManager.prototype.addImageTask = function (taskName, url) {
  24855. var task = new ImageAssetTask(taskName, url);
  24856. this._tasks.push(task);
  24857. return task;
  24858. };
  24859. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  24860. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24861. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  24862. this._tasks.push(task);
  24863. return task;
  24864. };
  24865. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  24866. this._waitingTasksCount--;
  24867. if (this._waitingTasksCount === 0) {
  24868. if (this.onFinish) {
  24869. this.onFinish(this._tasks);
  24870. }
  24871. this._scene.getEngine().hideLoadingUI();
  24872. }
  24873. };
  24874. AssetsManager.prototype._runTask = function (task) {
  24875. var _this = this;
  24876. task.run(this._scene, function () {
  24877. if (_this.onTaskSuccess) {
  24878. _this.onTaskSuccess(task);
  24879. }
  24880. _this._decreaseWaitingTasksCount();
  24881. }, function () {
  24882. if (_this.onTaskError) {
  24883. _this.onTaskError(task);
  24884. }
  24885. _this._decreaseWaitingTasksCount();
  24886. });
  24887. };
  24888. AssetsManager.prototype.reset = function () {
  24889. this._tasks = new Array();
  24890. return this;
  24891. };
  24892. AssetsManager.prototype.load = function () {
  24893. this._waitingTasksCount = this._tasks.length;
  24894. if (this._waitingTasksCount === 0) {
  24895. if (this.onFinish) {
  24896. this.onFinish(this._tasks);
  24897. }
  24898. return this;
  24899. }
  24900. if (this.useDefaultLoadingScreen) {
  24901. this._scene.getEngine().displayLoadingUI();
  24902. }
  24903. for (var index = 0; index < this._tasks.length; index++) {
  24904. var task = this._tasks[index];
  24905. this._runTask(task);
  24906. }
  24907. return this;
  24908. };
  24909. return AssetsManager;
  24910. })();
  24911. BABYLON.AssetsManager = AssetsManager;
  24912. })(BABYLON || (BABYLON = {}));
  24913. //# sourceMappingURL=babylon.assetsManager.js.map
  24914. var BABYLON;
  24915. (function (BABYLON) {
  24916. var VRDeviceOrientationCamera = (function (_super) {
  24917. __extends(VRDeviceOrientationCamera, _super);
  24918. function VRDeviceOrientationCamera(name, position, scene) {
  24919. _super.call(this, name, position, scene);
  24920. this._alpha = 0;
  24921. this._beta = 0;
  24922. this._gamma = 0;
  24923. }
  24924. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  24925. this._alpha = +evt.alpha | 0;
  24926. this._beta = +evt.beta | 0;
  24927. this._gamma = +evt.gamma | 0;
  24928. if (this._gamma < 0) {
  24929. this._gamma = 90 + this._gamma;
  24930. }
  24931. else {
  24932. // Incline it in the correct angle.
  24933. this._gamma = 270 - this._gamma;
  24934. }
  24935. this.rotation.x = this._gamma / 180.0 * Math.PI;
  24936. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  24937. this.rotation.z = this._beta / 180.0 * Math.PI;
  24938. };
  24939. return VRDeviceOrientationCamera;
  24940. })(BABYLON.OculusCamera);
  24941. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  24942. })(BABYLON || (BABYLON = {}));
  24943. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  24944. var BABYLON;
  24945. (function (BABYLON) {
  24946. var WebVRCamera = (function (_super) {
  24947. __extends(WebVRCamera, _super);
  24948. function WebVRCamera(name, position, scene) {
  24949. _super.call(this, name, position, scene);
  24950. this._hmdDevice = null;
  24951. this._sensorDevice = null;
  24952. this._cacheState = null;
  24953. this._cacheQuaternion = new BABYLON.Quaternion();
  24954. this._cacheRotation = BABYLON.Vector3.Zero();
  24955. this._vrEnabled = false;
  24956. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  24957. }
  24958. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  24959. var size = devices.length;
  24960. var i = 0;
  24961. // Reset devices.
  24962. this._sensorDevice = null;
  24963. this._hmdDevice = null;
  24964. while (i < size && this._hmdDevice === null) {
  24965. if (devices[i] instanceof HMDVRDevice) {
  24966. this._hmdDevice = devices[i];
  24967. }
  24968. i++;
  24969. }
  24970. i = 0;
  24971. while (i < size && this._sensorDevice === null) {
  24972. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  24973. this._sensorDevice = devices[i];
  24974. }
  24975. i++;
  24976. }
  24977. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  24978. };
  24979. WebVRCamera.prototype._update = function () {
  24980. if (this._vrEnabled) {
  24981. this._cacheState = this._sensorDevice.getState();
  24982. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  24983. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  24984. this.rotation.x = -this._cacheRotation.z;
  24985. this.rotation.y = -this._cacheRotation.y;
  24986. this.rotation.z = this._cacheRotation.x;
  24987. }
  24988. _super.prototype._update.call(this);
  24989. };
  24990. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  24991. _super.prototype.attachControl.call(this, element, noPreventDefault);
  24992. if (navigator.getVRDevices) {
  24993. navigator.getVRDevices().then(this._getWebVRDevices);
  24994. }
  24995. else if (navigator.mozGetVRDevices) {
  24996. navigator.mozGetVRDevices(this._getWebVRDevices);
  24997. }
  24998. };
  24999. WebVRCamera.prototype.detachControl = function (element) {
  25000. _super.prototype.detachControl.call(this, element);
  25001. this._vrEnabled = false;
  25002. };
  25003. return WebVRCamera;
  25004. })(BABYLON.OculusCamera);
  25005. BABYLON.WebVRCamera = WebVRCamera;
  25006. })(BABYLON || (BABYLON = {}));
  25007. //# sourceMappingURL=babylon.webVRCamera.js.map
  25008. var BABYLON;
  25009. (function (BABYLON) {
  25010. // Standard optimizations
  25011. var SceneOptimization = (function () {
  25012. function SceneOptimization(priority) {
  25013. if (priority === void 0) { priority = 0; }
  25014. this.priority = priority;
  25015. this.apply = function (scene) {
  25016. return true; // Return true if everything that can be done was applied
  25017. };
  25018. }
  25019. return SceneOptimization;
  25020. })();
  25021. BABYLON.SceneOptimization = SceneOptimization;
  25022. var TextureOptimization = (function (_super) {
  25023. __extends(TextureOptimization, _super);
  25024. function TextureOptimization(priority, maximumSize) {
  25025. var _this = this;
  25026. if (priority === void 0) { priority = 0; }
  25027. if (maximumSize === void 0) { maximumSize = 1024; }
  25028. _super.call(this, priority);
  25029. this.priority = priority;
  25030. this.maximumSize = maximumSize;
  25031. this.apply = function (scene) {
  25032. var allDone = true;
  25033. for (var index = 0; index < scene.textures.length; index++) {
  25034. var texture = scene.textures[index];
  25035. if (!texture.canRescale) {
  25036. continue;
  25037. }
  25038. var currentSize = texture.getSize();
  25039. var maxDimension = Math.max(currentSize.width, currentSize.height);
  25040. if (maxDimension > _this.maximumSize) {
  25041. texture.scale(0.5);
  25042. allDone = false;
  25043. }
  25044. }
  25045. return allDone;
  25046. };
  25047. }
  25048. return TextureOptimization;
  25049. })(SceneOptimization);
  25050. BABYLON.TextureOptimization = TextureOptimization;
  25051. var HardwareScalingOptimization = (function (_super) {
  25052. __extends(HardwareScalingOptimization, _super);
  25053. function HardwareScalingOptimization(priority, maximumScale) {
  25054. var _this = this;
  25055. if (priority === void 0) { priority = 0; }
  25056. if (maximumScale === void 0) { maximumScale = 2; }
  25057. _super.call(this, priority);
  25058. this.priority = priority;
  25059. this.maximumScale = maximumScale;
  25060. this._currentScale = 1;
  25061. this.apply = function (scene) {
  25062. _this._currentScale++;
  25063. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  25064. return _this._currentScale >= _this.maximumScale;
  25065. };
  25066. }
  25067. return HardwareScalingOptimization;
  25068. })(SceneOptimization);
  25069. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  25070. var ShadowsOptimization = (function (_super) {
  25071. __extends(ShadowsOptimization, _super);
  25072. function ShadowsOptimization() {
  25073. _super.apply(this, arguments);
  25074. this.apply = function (scene) {
  25075. scene.shadowsEnabled = false;
  25076. return true;
  25077. };
  25078. }
  25079. return ShadowsOptimization;
  25080. })(SceneOptimization);
  25081. BABYLON.ShadowsOptimization = ShadowsOptimization;
  25082. var PostProcessesOptimization = (function (_super) {
  25083. __extends(PostProcessesOptimization, _super);
  25084. function PostProcessesOptimization() {
  25085. _super.apply(this, arguments);
  25086. this.apply = function (scene) {
  25087. scene.postProcessesEnabled = false;
  25088. return true;
  25089. };
  25090. }
  25091. return PostProcessesOptimization;
  25092. })(SceneOptimization);
  25093. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  25094. var LensFlaresOptimization = (function (_super) {
  25095. __extends(LensFlaresOptimization, _super);
  25096. function LensFlaresOptimization() {
  25097. _super.apply(this, arguments);
  25098. this.apply = function (scene) {
  25099. scene.lensFlaresEnabled = false;
  25100. return true;
  25101. };
  25102. }
  25103. return LensFlaresOptimization;
  25104. })(SceneOptimization);
  25105. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  25106. var ParticlesOptimization = (function (_super) {
  25107. __extends(ParticlesOptimization, _super);
  25108. function ParticlesOptimization() {
  25109. _super.apply(this, arguments);
  25110. this.apply = function (scene) {
  25111. scene.particlesEnabled = false;
  25112. return true;
  25113. };
  25114. }
  25115. return ParticlesOptimization;
  25116. })(SceneOptimization);
  25117. BABYLON.ParticlesOptimization = ParticlesOptimization;
  25118. var RenderTargetsOptimization = (function (_super) {
  25119. __extends(RenderTargetsOptimization, _super);
  25120. function RenderTargetsOptimization() {
  25121. _super.apply(this, arguments);
  25122. this.apply = function (scene) {
  25123. scene.renderTargetsEnabled = false;
  25124. return true;
  25125. };
  25126. }
  25127. return RenderTargetsOptimization;
  25128. })(SceneOptimization);
  25129. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  25130. var MergeMeshesOptimization = (function (_super) {
  25131. __extends(MergeMeshesOptimization, _super);
  25132. function MergeMeshesOptimization() {
  25133. var _this = this;
  25134. _super.apply(this, arguments);
  25135. this._canBeMerged = function (abstractMesh) {
  25136. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  25137. return false;
  25138. }
  25139. var mesh = abstractMesh;
  25140. if (!mesh.isVisible || !mesh.isEnabled()) {
  25141. return false;
  25142. }
  25143. if (mesh.instances.length > 0) {
  25144. return false;
  25145. }
  25146. if (mesh.skeleton || mesh.hasLODLevels) {
  25147. return false;
  25148. }
  25149. return true;
  25150. };
  25151. this.apply = function (scene) {
  25152. var globalPool = scene.meshes.slice(0);
  25153. var globalLength = globalPool.length;
  25154. for (var index = 0; index < globalLength; index++) {
  25155. var currentPool = new Array();
  25156. var current = globalPool[index];
  25157. // Checks
  25158. if (!_this._canBeMerged(current)) {
  25159. continue;
  25160. }
  25161. currentPool.push(current);
  25162. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  25163. var otherMesh = globalPool[subIndex];
  25164. if (!_this._canBeMerged(otherMesh)) {
  25165. continue;
  25166. }
  25167. if (otherMesh.material !== current.material) {
  25168. continue;
  25169. }
  25170. if (otherMesh.checkCollisions !== current.checkCollisions) {
  25171. continue;
  25172. }
  25173. currentPool.push(otherMesh);
  25174. globalLength--;
  25175. globalPool.splice(subIndex, 1);
  25176. subIndex--;
  25177. }
  25178. if (currentPool.length < 2) {
  25179. continue;
  25180. }
  25181. // Merge meshes
  25182. BABYLON.Mesh.MergeMeshes(currentPool);
  25183. }
  25184. return true;
  25185. };
  25186. }
  25187. return MergeMeshesOptimization;
  25188. })(SceneOptimization);
  25189. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  25190. // Options
  25191. var SceneOptimizerOptions = (function () {
  25192. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  25193. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  25194. if (trackerDuration === void 0) { trackerDuration = 2000; }
  25195. this.targetFrameRate = targetFrameRate;
  25196. this.trackerDuration = trackerDuration;
  25197. this.optimizations = new Array();
  25198. }
  25199. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  25200. var result = new SceneOptimizerOptions(targetFrameRate);
  25201. var priority = 0;
  25202. result.optimizations.push(new MergeMeshesOptimization(priority));
  25203. result.optimizations.push(new ShadowsOptimization(priority));
  25204. result.optimizations.push(new LensFlaresOptimization(priority));
  25205. // Next priority
  25206. priority++;
  25207. result.optimizations.push(new PostProcessesOptimization(priority));
  25208. result.optimizations.push(new ParticlesOptimization(priority));
  25209. // Next priority
  25210. priority++;
  25211. result.optimizations.push(new TextureOptimization(priority, 1024));
  25212. return result;
  25213. };
  25214. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  25215. var result = new SceneOptimizerOptions(targetFrameRate);
  25216. var priority = 0;
  25217. result.optimizations.push(new MergeMeshesOptimization(priority));
  25218. result.optimizations.push(new ShadowsOptimization(priority));
  25219. result.optimizations.push(new LensFlaresOptimization(priority));
  25220. // Next priority
  25221. priority++;
  25222. result.optimizations.push(new PostProcessesOptimization(priority));
  25223. result.optimizations.push(new ParticlesOptimization(priority));
  25224. // Next priority
  25225. priority++;
  25226. result.optimizations.push(new TextureOptimization(priority, 512));
  25227. // Next priority
  25228. priority++;
  25229. result.optimizations.push(new RenderTargetsOptimization(priority));
  25230. // Next priority
  25231. priority++;
  25232. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  25233. return result;
  25234. };
  25235. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  25236. var result = new SceneOptimizerOptions(targetFrameRate);
  25237. var priority = 0;
  25238. result.optimizations.push(new MergeMeshesOptimization(priority));
  25239. result.optimizations.push(new ShadowsOptimization(priority));
  25240. result.optimizations.push(new LensFlaresOptimization(priority));
  25241. // Next priority
  25242. priority++;
  25243. result.optimizations.push(new PostProcessesOptimization(priority));
  25244. result.optimizations.push(new ParticlesOptimization(priority));
  25245. // Next priority
  25246. priority++;
  25247. result.optimizations.push(new TextureOptimization(priority, 256));
  25248. // Next priority
  25249. priority++;
  25250. result.optimizations.push(new RenderTargetsOptimization(priority));
  25251. // Next priority
  25252. priority++;
  25253. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  25254. return result;
  25255. };
  25256. return SceneOptimizerOptions;
  25257. })();
  25258. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  25259. // Scene optimizer tool
  25260. var SceneOptimizer = (function () {
  25261. function SceneOptimizer() {
  25262. }
  25263. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  25264. // TODO: add an epsilon
  25265. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  25266. if (onSuccess) {
  25267. onSuccess();
  25268. }
  25269. return;
  25270. }
  25271. // Apply current level of optimizations
  25272. var allDone = true;
  25273. var noOptimizationApplied = true;
  25274. for (var index = 0; index < options.optimizations.length; index++) {
  25275. var optimization = options.optimizations[index];
  25276. if (optimization.priority === currentPriorityLevel) {
  25277. noOptimizationApplied = false;
  25278. allDone = allDone && optimization.apply(scene);
  25279. }
  25280. }
  25281. // If no optimization was applied, this is a failure :(
  25282. if (noOptimizationApplied) {
  25283. if (onFailure) {
  25284. onFailure();
  25285. }
  25286. return;
  25287. }
  25288. // If all optimizations were done, move to next level
  25289. if (allDone) {
  25290. currentPriorityLevel++;
  25291. }
  25292. // Let's the system running for a specific amount of time before checking FPS
  25293. scene.executeWhenReady(function () {
  25294. setTimeout(function () {
  25295. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  25296. }, options.trackerDuration);
  25297. });
  25298. };
  25299. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  25300. if (!options) {
  25301. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  25302. }
  25303. // Let's the system running for a specific amount of time before checking FPS
  25304. scene.executeWhenReady(function () {
  25305. setTimeout(function () {
  25306. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  25307. }, options.trackerDuration);
  25308. });
  25309. };
  25310. return SceneOptimizer;
  25311. })();
  25312. BABYLON.SceneOptimizer = SceneOptimizer;
  25313. })(BABYLON || (BABYLON = {}));
  25314. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  25315. (function (BABYLON) {
  25316. var Internals;
  25317. (function (Internals) {
  25318. var MeshLODLevel = (function () {
  25319. function MeshLODLevel(distance, mesh) {
  25320. this.distance = distance;
  25321. this.mesh = mesh;
  25322. }
  25323. return MeshLODLevel;
  25324. })();
  25325. Internals.MeshLODLevel = MeshLODLevel;
  25326. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25327. })(BABYLON || (BABYLON = {}));
  25328. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  25329. (function (BABYLON) {
  25330. var AudioEngine = (function () {
  25331. function AudioEngine() {
  25332. this.audioContext = null;
  25333. this.canUseWebAudio = false;
  25334. this.WarnedWebAudioUnsupported = false;
  25335. try {
  25336. if (typeof AudioContext !== 'undefined') {
  25337. this.audioContext = new AudioContext();
  25338. this.canUseWebAudio = true;
  25339. }
  25340. else if (typeof webkitAudioContext !== 'undefined') {
  25341. this.audioContext = new webkitAudioContext();
  25342. this.canUseWebAudio = true;
  25343. }
  25344. }
  25345. catch (e) {
  25346. this.canUseWebAudio = false;
  25347. BABYLON.Tools.Error("Web Audio: " + e.message);
  25348. }
  25349. // create a global volume gain node
  25350. if (this.canUseWebAudio) {
  25351. this.masterGain = this.audioContext.createGain();
  25352. this.masterGain.gain.value = 1;
  25353. this.masterGain.connect(this.audioContext.destination);
  25354. }
  25355. }
  25356. AudioEngine.prototype.dispose = function () {
  25357. if (this.canUseWebAudio) {
  25358. if (this._connectedAnalyser) {
  25359. this._connectedAnalyser.stopDebugCanvas();
  25360. this._connectedAnalyser.dispose();
  25361. this.masterGain.disconnect();
  25362. this.masterGain.connect(this.audioContext.destination);
  25363. this._connectedAnalyser = null;
  25364. }
  25365. this.masterGain.gain.value = 1;
  25366. }
  25367. this.WarnedWebAudioUnsupported = false;
  25368. };
  25369. AudioEngine.prototype.getGlobalVolume = function () {
  25370. if (this.canUseWebAudio) {
  25371. return this.masterGain.gain.value;
  25372. }
  25373. else {
  25374. return -1;
  25375. }
  25376. };
  25377. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  25378. if (this.canUseWebAudio) {
  25379. this.masterGain.gain.value = newVolume;
  25380. }
  25381. };
  25382. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  25383. if (this._connectedAnalyser) {
  25384. this._connectedAnalyser.stopDebugCanvas();
  25385. }
  25386. this._connectedAnalyser = analyser;
  25387. if (this.canUseWebAudio) {
  25388. this.masterGain.disconnect();
  25389. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  25390. }
  25391. };
  25392. return AudioEngine;
  25393. })();
  25394. BABYLON.AudioEngine = AudioEngine;
  25395. })(BABYLON || (BABYLON = {}));
  25396. //# sourceMappingURL=babylon.audioengine.js.mapvar BABYLON;
  25397. (function (BABYLON) {
  25398. var Sound = (function () {
  25399. /**
  25400. * Create a sound and attach it to a scene
  25401. * @param name Name of your sound
  25402. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  25403. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  25404. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  25405. */
  25406. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  25407. var _this = this;
  25408. this.autoplay = false;
  25409. this.loop = false;
  25410. this.useCustomAttenuation = false;
  25411. this.spatialSound = false;
  25412. this.refDistance = 1;
  25413. this.rolloffFactor = 1;
  25414. this.maxDistance = 100;
  25415. this.distanceModel = "linear";
  25416. this.panningModel = "HRTF";
  25417. this._playbackRate = 1;
  25418. this._startTime = 0;
  25419. this._startOffset = 0;
  25420. this._position = BABYLON.Vector3.Zero();
  25421. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  25422. this._volume = 1;
  25423. this._isLoaded = false;
  25424. this._isReadyToPlay = false;
  25425. this._isPlaying = false;
  25426. this._isDirectional = false;
  25427. // Used if you'd like to create a directional sound.
  25428. // If not set, the sound will be omnidirectional
  25429. this._coneInnerAngle = 360;
  25430. this._coneOuterAngle = 360;
  25431. this._coneOuterGain = 0;
  25432. this.name = name;
  25433. this._scene = scene;
  25434. this._readyToPlayCallback = readyToPlayCallback;
  25435. // Default custom attenuation function is a linear attenuation
  25436. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  25437. if (currentDistance < maxDistance) {
  25438. return currentVolume * (1 - currentDistance / maxDistance);
  25439. }
  25440. else {
  25441. return 0;
  25442. }
  25443. };
  25444. if (options) {
  25445. this.autoplay = options.autoplay || false;
  25446. this.loop = options.loop || false;
  25447. // if volume === 0, we need another way to check this option
  25448. if (options.volume !== undefined) {
  25449. this._volume = options.volume;
  25450. }
  25451. this.spatialSound = options.spatialSound || false;
  25452. this.maxDistance = options.maxDistance || 100;
  25453. this.useCustomAttenuation = options.useCustomAttenuation || false;
  25454. this.rolloffFactor = options.rolloffFactor || 1;
  25455. this.refDistance = options.refDistance || 1;
  25456. this.distanceModel = options.distanceModel || "linear";
  25457. this.panningModel = options.panningModel || "HRTF";
  25458. this._playbackRate = options.playbackRate || 1;
  25459. }
  25460. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25461. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  25462. this._soundGain.gain.value = this._volume;
  25463. this._inputAudioNode = this._soundGain;
  25464. this._ouputAudioNode = this._soundGain;
  25465. if (this.spatialSound) {
  25466. this._createSpatialParameters();
  25467. }
  25468. this._scene.mainSoundTrack.AddSound(this);
  25469. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  25470. if (urlOrArrayBuffer) {
  25471. // If it's an URL
  25472. if (typeof (urlOrArrayBuffer) === "string") {
  25473. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  25474. _this._soundLoaded(data);
  25475. }, null, null, true);
  25476. }
  25477. else {
  25478. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  25479. this._soundLoaded(urlOrArrayBuffer);
  25480. }
  25481. else {
  25482. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  25483. }
  25484. }
  25485. }
  25486. }
  25487. else {
  25488. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  25489. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  25490. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  25491. }
  25492. }
  25493. }
  25494. Sound.prototype.dispose = function () {
  25495. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  25496. if (this._isPlaying) {
  25497. this.stop();
  25498. }
  25499. this._isReadyToPlay = false;
  25500. if (this.soundTrackId === -1) {
  25501. this._scene.mainSoundTrack.RemoveSound(this);
  25502. }
  25503. else {
  25504. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  25505. }
  25506. this._soundGain.disconnect();
  25507. this._soundSource.disconnect();
  25508. if (this._soundPanner) {
  25509. this._soundPanner.disconnect();
  25510. this._soundPanner = null;
  25511. }
  25512. this._audioBuffer = null;
  25513. this._soundGain = null;
  25514. this._soundSource = null;
  25515. if (this._connectedMesh) {
  25516. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  25517. this._connectedMesh = null;
  25518. }
  25519. }
  25520. };
  25521. Sound.prototype._soundLoaded = function (audioData) {
  25522. var _this = this;
  25523. this._isLoaded = true;
  25524. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  25525. _this._audioBuffer = buffer;
  25526. _this._isReadyToPlay = true;
  25527. if (_this.autoplay) {
  25528. _this.play();
  25529. }
  25530. if (_this._readyToPlayCallback) {
  25531. _this._readyToPlayCallback();
  25532. }
  25533. }, function (error) {
  25534. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  25535. });
  25536. };
  25537. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  25538. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25539. this._audioBuffer = audioBuffer;
  25540. this._isReadyToPlay = true;
  25541. }
  25542. };
  25543. Sound.prototype.updateOptions = function (options) {
  25544. if (options) {
  25545. this.loop = options.loop || this.loop;
  25546. this.maxDistance = options.maxDistance || this.maxDistance;
  25547. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  25548. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  25549. this.refDistance = options.refDistance || this.refDistance;
  25550. this.distanceModel = options.distanceModel || this.distanceModel;
  25551. this.panningModel = options.panningModel || this.panningModel;
  25552. this._playbackRate = options.playbackRate || this._playbackRate;
  25553. }
  25554. };
  25555. Sound.prototype._createSpatialParameters = function () {
  25556. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25557. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  25558. if (this.useCustomAttenuation) {
  25559. // Tricks to disable in a way embedded Web Audio attenuation
  25560. this._soundPanner.distanceModel = "linear";
  25561. this._soundPanner.maxDistance = Number.MAX_VALUE;
  25562. this._soundPanner.refDistance = 1;
  25563. this._soundPanner.rolloffFactor = 1;
  25564. this._soundPanner.panningModel = "HRTF";
  25565. }
  25566. else {
  25567. this._soundPanner.distanceModel = this.distanceModel;
  25568. this._soundPanner.maxDistance = this.maxDistance;
  25569. this._soundPanner.refDistance = this.refDistance;
  25570. this._soundPanner.rolloffFactor = this.rolloffFactor;
  25571. this._soundPanner.panningModel = this.panningModel;
  25572. }
  25573. this._soundPanner.connect(this._ouputAudioNode);
  25574. this._inputAudioNode = this._soundPanner;
  25575. }
  25576. };
  25577. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  25578. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25579. this._ouputAudioNode.disconnect();
  25580. this._ouputAudioNode.connect(soundTrackAudioNode);
  25581. }
  25582. };
  25583. /**
  25584. * Transform this sound into a directional source
  25585. * @param coneInnerAngle Size of the inner cone in degree
  25586. * @param coneOuterAngle Size of the outer cone in degree
  25587. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  25588. */
  25589. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25590. if (coneOuterAngle < coneInnerAngle) {
  25591. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  25592. return;
  25593. }
  25594. this._coneInnerAngle = coneInnerAngle;
  25595. this._coneOuterAngle = coneOuterAngle;
  25596. this._coneOuterGain = coneOuterGain;
  25597. this._isDirectional = true;
  25598. if (this._isPlaying && this.loop) {
  25599. this.stop();
  25600. this.play();
  25601. }
  25602. };
  25603. Sound.prototype.setPosition = function (newPosition) {
  25604. this._position = newPosition;
  25605. if (this._isPlaying && this.spatialSound) {
  25606. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25607. }
  25608. };
  25609. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  25610. this._localDirection = newLocalDirection;
  25611. if (this._connectedMesh && this._isPlaying) {
  25612. this._updateDirection();
  25613. }
  25614. };
  25615. Sound.prototype._updateDirection = function () {
  25616. var mat = this._connectedMesh.getWorldMatrix();
  25617. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  25618. direction.normalize();
  25619. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  25620. };
  25621. Sound.prototype.updateDistanceFromListener = function () {
  25622. if (this._connectedMesh && this.useCustomAttenuation) {
  25623. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  25624. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  25625. }
  25626. };
  25627. Sound.prototype.setAttenuationFunction = function (callback) {
  25628. this._customAttenuationFunction = callback;
  25629. };
  25630. /**
  25631. * Play the sound
  25632. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  25633. */
  25634. Sound.prototype.play = function (time) {
  25635. if (this._isReadyToPlay) {
  25636. try {
  25637. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  25638. if (!this._soundSource) {
  25639. if (this.spatialSound) {
  25640. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25641. if (this._isDirectional) {
  25642. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  25643. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  25644. this._soundPanner.coneOuterGain = this._coneOuterGain;
  25645. if (this._connectedMesh) {
  25646. this._updateDirection();
  25647. }
  25648. else {
  25649. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  25650. }
  25651. }
  25652. }
  25653. }
  25654. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  25655. this._soundSource.buffer = this._audioBuffer;
  25656. this._soundSource.connect(this._inputAudioNode);
  25657. this._soundSource.loop = this.loop;
  25658. this._soundSource.playbackRate.value = this._playbackRate;
  25659. this._startTime = startTime;
  25660. if (this.onended) {
  25661. this._soundSource.onended = this.onended;
  25662. }
  25663. this._soundSource.start(startTime, this._startOffset % this._soundSource.buffer.duration);
  25664. this._isPlaying = true;
  25665. }
  25666. catch (ex) {
  25667. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  25668. }
  25669. }
  25670. };
  25671. /**
  25672. * Stop the sound
  25673. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  25674. */
  25675. Sound.prototype.stop = function (time) {
  25676. if (this._isPlaying) {
  25677. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  25678. this._soundSource.stop(stopTime);
  25679. this._isPlaying = false;
  25680. }
  25681. };
  25682. Sound.prototype.pause = function () {
  25683. if (this._isPlaying) {
  25684. this._soundSource.stop(0);
  25685. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  25686. }
  25687. };
  25688. Sound.prototype.setVolume = function (newVolume) {
  25689. this._volume = newVolume;
  25690. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25691. this._soundGain.gain.value = newVolume;
  25692. }
  25693. };
  25694. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  25695. this._playbackRate = newPlaybackRate;
  25696. if (this._isPlaying) {
  25697. this._soundSource.playbackRate.value = this._playbackRate;
  25698. }
  25699. };
  25700. Sound.prototype.getVolume = function () {
  25701. return this._volume;
  25702. };
  25703. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  25704. var _this = this;
  25705. this._connectedMesh = meshToConnectTo;
  25706. if (!this.spatialSound) {
  25707. this._createSpatialParameters();
  25708. this.spatialSound = true;
  25709. if (this._isPlaying && this.loop) {
  25710. this.stop();
  25711. this.play();
  25712. }
  25713. }
  25714. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  25715. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  25716. };
  25717. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  25718. this.setPosition(connectedMesh.position);
  25719. if (this._isDirectional && this._isPlaying) {
  25720. this._updateDirection();
  25721. }
  25722. };
  25723. return Sound;
  25724. })();
  25725. BABYLON.Sound = Sound;
  25726. })(BABYLON || (BABYLON = {}));
  25727. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  25728. (function (BABYLON) {
  25729. var SoundTrack = (function () {
  25730. function SoundTrack(scene, options) {
  25731. this.id = -1;
  25732. this._isMainTrack = false;
  25733. this._scene = scene;
  25734. this._audioEngine = BABYLON.Engine.audioEngine;
  25735. this.soundCollection = new Array();
  25736. if (this._audioEngine.canUseWebAudio) {
  25737. this._trackGain = this._audioEngine.audioContext.createGain();
  25738. this._trackGain.connect(this._audioEngine.masterGain);
  25739. if (options) {
  25740. if (options.volume) {
  25741. this._trackGain.gain.value = options.volume;
  25742. }
  25743. if (options.mainTrack) {
  25744. this._isMainTrack = options.mainTrack;
  25745. }
  25746. }
  25747. }
  25748. if (!this._isMainTrack) {
  25749. this._scene.soundTracks.push(this);
  25750. this.id = this._scene.soundTracks.length - 1;
  25751. }
  25752. }
  25753. SoundTrack.prototype.dispose = function () {
  25754. if (this._audioEngine.canUseWebAudio) {
  25755. if (this._connectedAnalyser) {
  25756. this._connectedAnalyser.stopDebugCanvas();
  25757. }
  25758. while (this.soundCollection.length) {
  25759. this.soundCollection[0].dispose();
  25760. }
  25761. this._trackGain.disconnect();
  25762. this._trackGain = null;
  25763. }
  25764. };
  25765. SoundTrack.prototype.AddSound = function (sound) {
  25766. sound.connectToSoundTrackAudioNode(this._trackGain);
  25767. if (sound.soundTrackId) {
  25768. if (sound.soundTrackId === -1) {
  25769. this._scene.mainSoundTrack.RemoveSound(sound);
  25770. }
  25771. else {
  25772. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  25773. }
  25774. }
  25775. this.soundCollection.push(sound);
  25776. sound.soundTrackId = this.id;
  25777. };
  25778. SoundTrack.prototype.RemoveSound = function (sound) {
  25779. var index = this.soundCollection.indexOf(sound);
  25780. if (index !== -1) {
  25781. this.soundCollection.splice(index, 1);
  25782. }
  25783. };
  25784. SoundTrack.prototype.setVolume = function (newVolume) {
  25785. if (this._audioEngine.canUseWebAudio) {
  25786. this._trackGain.gain.value = newVolume;
  25787. }
  25788. };
  25789. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  25790. if (this._connectedAnalyser) {
  25791. this._connectedAnalyser.stopDebugCanvas();
  25792. }
  25793. this._connectedAnalyser = analyser;
  25794. if (this._audioEngine.canUseWebAudio) {
  25795. this._trackGain.disconnect();
  25796. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  25797. }
  25798. };
  25799. return SoundTrack;
  25800. })();
  25801. BABYLON.SoundTrack = SoundTrack;
  25802. })(BABYLON || (BABYLON = {}));
  25803. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  25804. (function (BABYLON) {
  25805. var DebugLayer = (function () {
  25806. function DebugLayer(scene) {
  25807. var _this = this;
  25808. this._enabled = false;
  25809. this._labelsEnabled = false;
  25810. this._displayStatistics = true;
  25811. this._displayTree = false;
  25812. this._displayLogs = false;
  25813. this._identityMatrix = BABYLON.Matrix.Identity();
  25814. this.axisRatio = 0.02;
  25815. this.accentColor = "orange";
  25816. this._scene = scene;
  25817. this._syncPositions = function () {
  25818. var engine = _this._scene.getEngine();
  25819. var canvasRect = engine.getRenderingCanvasClientRect();
  25820. if (_this._showUI) {
  25821. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  25822. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  25823. _this._statsDiv.style.width = "400px";
  25824. _this._statsDiv.style.height = "auto";
  25825. _this._statsSubsetDiv.style.maxHeight = "240px";
  25826. _this._optionsDiv.style.left = "0px";
  25827. _this._optionsDiv.style.top = "10px";
  25828. _this._optionsDiv.style.width = "200px";
  25829. _this._optionsDiv.style.height = "auto";
  25830. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  25831. _this._logDiv.style.left = "0px";
  25832. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  25833. _this._logDiv.style.width = "600px";
  25834. _this._logDiv.style.height = "160px";
  25835. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  25836. _this._treeDiv.style.top = "10px";
  25837. _this._treeDiv.style.width = "300px";
  25838. _this._treeDiv.style.height = "auto";
  25839. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  25840. }
  25841. _this._globalDiv.style.left = canvasRect.left + "px";
  25842. _this._globalDiv.style.top = canvasRect.top + "px";
  25843. _this._drawingCanvas.style.left = "0px";
  25844. _this._drawingCanvas.style.top = "0px";
  25845. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  25846. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  25847. var devicePixelRatio = window.devicePixelRatio || 1;
  25848. var context = _this._drawingContext;
  25849. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  25850. _this._ratio = devicePixelRatio / backingStoreRatio;
  25851. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  25852. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  25853. };
  25854. this._onCanvasClick = function (evt) {
  25855. _this._clickPosition = {
  25856. x: evt.clientX * _this._ratio,
  25857. y: evt.clientY * _this._ratio
  25858. };
  25859. };
  25860. this._syncData = function () {
  25861. if (_this._showUI) {
  25862. if (_this._displayStatistics) {
  25863. _this._displayStats();
  25864. _this._statsDiv.style.display = "";
  25865. }
  25866. else {
  25867. _this._statsDiv.style.display = "none";
  25868. }
  25869. if (_this._displayLogs) {
  25870. _this._logDiv.style.display = "";
  25871. }
  25872. else {
  25873. _this._logDiv.style.display = "none";
  25874. }
  25875. if (_this._displayTree) {
  25876. _this._treeDiv.style.display = "";
  25877. if (_this._needToRefreshMeshesTree) {
  25878. _this._needToRefreshMeshesTree = false;
  25879. _this._refreshMeshesTreeContent();
  25880. }
  25881. }
  25882. else {
  25883. _this._treeDiv.style.display = "none";
  25884. }
  25885. }
  25886. if (_this._labelsEnabled || !_this._showUI) {
  25887. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  25888. var engine = _this._scene.getEngine();
  25889. var viewport = _this._scene.activeCamera.viewport;
  25890. var globalViewport = viewport.toGlobal(engine);
  25891. // Meshes
  25892. var meshes = _this._scene.getActiveMeshes();
  25893. for (var index = 0; index < meshes.length; index++) {
  25894. var mesh = meshes.data[index];
  25895. var position = mesh.getBoundingInfo().boundingSphere.center;
  25896. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25897. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  25898. _this._renderAxis(projectedPosition, mesh, globalViewport);
  25899. }
  25900. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  25901. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  25902. mesh.renderOverlay = !mesh.renderOverlay;
  25903. }, function () {
  25904. return mesh.renderOverlay ? 'red' : 'black';
  25905. });
  25906. }
  25907. }
  25908. // Cameras
  25909. var cameras = _this._scene.cameras;
  25910. for (index = 0; index < cameras.length; index++) {
  25911. var camera = cameras[index];
  25912. if (camera === _this._scene.activeCamera) {
  25913. continue;
  25914. }
  25915. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25916. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  25917. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  25918. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  25919. _this._scene.activeCamera = camera;
  25920. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  25921. }, function () {
  25922. return "purple";
  25923. });
  25924. }
  25925. }
  25926. // Lights
  25927. var lights = _this._scene.lights;
  25928. for (index = 0; index < lights.length; index++) {
  25929. var light = lights[index];
  25930. if (light.position) {
  25931. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  25932. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  25933. _this._renderLabel(light.name, projectedPosition, -20, function () {
  25934. light.setEnabled(!light.isEnabled());
  25935. }, function () {
  25936. return light.isEnabled() ? "orange" : "gray";
  25937. });
  25938. }
  25939. }
  25940. }
  25941. }
  25942. _this._clickPosition = undefined;
  25943. };
  25944. }
  25945. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  25946. while (this._treeSubsetDiv.hasChildNodes()) {
  25947. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  25948. }
  25949. // Add meshes
  25950. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  25951. sortedArray.sort(function (a, b) {
  25952. if (a.name === b.name) {
  25953. return 0;
  25954. }
  25955. return (a.name > b.name) ? 1 : -1;
  25956. });
  25957. for (var index = 0; index < sortedArray.length; index++) {
  25958. var mesh = sortedArray[index];
  25959. if (!mesh.isEnabled()) {
  25960. continue;
  25961. }
  25962. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  25963. m.isVisible = element.checked;
  25964. }, mesh);
  25965. }
  25966. };
  25967. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  25968. this._drawingContext.beginPath();
  25969. this._drawingContext.moveTo(zero.x, zero.y);
  25970. this._drawingContext.lineTo(unit.x, unit.y);
  25971. this._drawingContext.strokeStyle = color;
  25972. this._drawingContext.lineWidth = 4;
  25973. this._drawingContext.stroke();
  25974. this._drawingContext.font = "normal 14px Segoe UI";
  25975. this._drawingContext.fillStyle = color;
  25976. this._drawingContext.fillText(label, unitText.x, unitText.y);
  25977. };
  25978. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  25979. var position = mesh.getBoundingInfo().boundingSphere.center;
  25980. var worldMatrix = mesh.getWorldMatrix();
  25981. 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());
  25982. var unit = (unprojectedVector.subtract(position)).length();
  25983. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25984. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25985. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  25986. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25987. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25988. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  25989. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25990. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25991. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  25992. };
  25993. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  25994. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  25995. this._drawingContext.font = "normal 12px Segoe UI";
  25996. var textMetrics = this._drawingContext.measureText(text);
  25997. var centerX = projectedPosition.x - textMetrics.width / 2;
  25998. var centerY = projectedPosition.y;
  25999. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26000. onClick();
  26001. }
  26002. this._drawingContext.beginPath();
  26003. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26004. this._drawingContext.fillStyle = getFillStyle();
  26005. this._drawingContext.globalAlpha = 0.5;
  26006. this._drawingContext.fill();
  26007. this._drawingContext.globalAlpha = 1.0;
  26008. this._drawingContext.strokeStyle = '#FFFFFF';
  26009. this._drawingContext.lineWidth = 1;
  26010. this._drawingContext.stroke();
  26011. this._drawingContext.fillStyle = "#FFFFFF";
  26012. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26013. this._drawingContext.beginPath();
  26014. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26015. this._drawingContext.fill();
  26016. }
  26017. };
  26018. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26019. if (!this._clickPosition) {
  26020. return false;
  26021. }
  26022. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26023. return false;
  26024. }
  26025. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26026. return false;
  26027. }
  26028. return true;
  26029. };
  26030. DebugLayer.prototype.isVisible = function () {
  26031. return this._enabled;
  26032. };
  26033. DebugLayer.prototype.hide = function () {
  26034. if (!this._enabled) {
  26035. return;
  26036. }
  26037. this._enabled = false;
  26038. var engine = this._scene.getEngine();
  26039. this._scene.unregisterAfterRender(this._syncData);
  26040. document.body.removeChild(this._globalDiv);
  26041. window.removeEventListener("resize", this._syncPositions);
  26042. this._scene.forceShowBoundingBoxes = false;
  26043. this._scene.forceWireframe = false;
  26044. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26045. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26046. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26047. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26048. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26049. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26050. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26051. this._scene.shadowsEnabled = true;
  26052. this._scene.particlesEnabled = true;
  26053. this._scene.postProcessesEnabled = true;
  26054. this._scene.collisionsEnabled = true;
  26055. this._scene.lightsEnabled = true;
  26056. this._scene.texturesEnabled = true;
  26057. this._scene.lensFlaresEnabled = true;
  26058. this._scene.proceduralTexturesEnabled = true;
  26059. this._scene.renderTargetsEnabled = true;
  26060. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26061. };
  26062. DebugLayer.prototype.show = function (showUI) {
  26063. if (showUI === void 0) { showUI = true; }
  26064. if (this._enabled) {
  26065. return;
  26066. }
  26067. this._enabled = true;
  26068. this._showUI = showUI;
  26069. var engine = this._scene.getEngine();
  26070. this._globalDiv = document.createElement("div");
  26071. document.body.appendChild(this._globalDiv);
  26072. this._generateDOMelements();
  26073. window.addEventListener("resize", this._syncPositions);
  26074. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26075. this._syncPositions();
  26076. this._scene.registerAfterRender(this._syncData);
  26077. };
  26078. DebugLayer.prototype._clearLabels = function () {
  26079. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26080. for (var index = 0; index < this._scene.meshes.length; index++) {
  26081. var mesh = this._scene.meshes[index];
  26082. mesh.renderOverlay = false;
  26083. }
  26084. };
  26085. DebugLayer.prototype._generateheader = function (root, text) {
  26086. var header = document.createElement("div");
  26087. header.innerHTML = text + "&nbsp;";
  26088. header.style.textAlign = "right";
  26089. header.style.width = "100%";
  26090. header.style.color = "white";
  26091. header.style.backgroundColor = "Black";
  26092. header.style.padding = "5px 5px 4px 0px";
  26093. header.style.marginLeft = "-5px";
  26094. header.style.fontWeight = "bold";
  26095. root.appendChild(header);
  26096. };
  26097. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26098. var label = document.createElement("label");
  26099. label.innerHTML = title;
  26100. label.style.color = color;
  26101. root.appendChild(label);
  26102. root.appendChild(document.createElement("br"));
  26103. };
  26104. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26105. if (tag === void 0) { tag = null; }
  26106. var label = document.createElement("label");
  26107. var boundingBoxesCheckbox = document.createElement("input");
  26108. boundingBoxesCheckbox.type = "checkbox";
  26109. boundingBoxesCheckbox.checked = initialState;
  26110. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26111. task(evt.target, tag);
  26112. });
  26113. label.appendChild(boundingBoxesCheckbox);
  26114. var container = document.createElement("span");
  26115. var leftPart = document.createElement("span");
  26116. var rightPart = document.createElement("span");
  26117. rightPart.style.cssFloat = "right";
  26118. leftPart.innerHTML = leftTitle;
  26119. rightPart.innerHTML = rightTitle;
  26120. rightPart.style.fontSize = "12px";
  26121. rightPart.style.maxWidth = "200px";
  26122. container.appendChild(leftPart);
  26123. container.appendChild(rightPart);
  26124. label.appendChild(container);
  26125. root.appendChild(label);
  26126. root.appendChild(document.createElement("br"));
  26127. };
  26128. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  26129. if (tag === void 0) { tag = null; }
  26130. var label = document.createElement("label");
  26131. var boundingBoxesCheckbox = document.createElement("input");
  26132. boundingBoxesCheckbox.type = "checkbox";
  26133. boundingBoxesCheckbox.checked = initialState;
  26134. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26135. task(evt.target, tag);
  26136. });
  26137. label.appendChild(boundingBoxesCheckbox);
  26138. label.appendChild(document.createTextNode(title));
  26139. root.appendChild(label);
  26140. root.appendChild(document.createElement("br"));
  26141. };
  26142. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  26143. if (tag === void 0) { tag = null; }
  26144. var label = document.createElement("label");
  26145. var boundingBoxesRadio = document.createElement("input");
  26146. boundingBoxesRadio.type = "radio";
  26147. boundingBoxesRadio.name = name;
  26148. boundingBoxesRadio.checked = initialState;
  26149. boundingBoxesRadio.addEventListener("change", function (evt) {
  26150. task(evt.target, tag);
  26151. });
  26152. label.appendChild(boundingBoxesRadio);
  26153. label.appendChild(document.createTextNode(title));
  26154. root.appendChild(label);
  26155. root.appendChild(document.createElement("br"));
  26156. };
  26157. DebugLayer.prototype._generateDOMelements = function () {
  26158. var _this = this;
  26159. this._globalDiv.id = "DebugLayer";
  26160. this._globalDiv.style.position = "absolute";
  26161. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  26162. this._globalDiv.style.fontSize = "14px";
  26163. this._globalDiv.style.color = "white";
  26164. // Drawing canvas
  26165. this._drawingCanvas = document.createElement("canvas");
  26166. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  26167. this._drawingCanvas.style.position = "absolute";
  26168. this._drawingCanvas.style.pointerEvents = "none";
  26169. this._drawingContext = this._drawingCanvas.getContext("2d");
  26170. this._globalDiv.appendChild(this._drawingCanvas);
  26171. if (this._showUI) {
  26172. var background = "rgba(128, 128, 128, 0.4)";
  26173. var border = "rgb(180, 180, 180) solid 1px";
  26174. // Stats
  26175. this._statsDiv = document.createElement("div");
  26176. this._statsDiv.id = "DebugLayerStats";
  26177. this._statsDiv.style.border = border;
  26178. this._statsDiv.style.position = "absolute";
  26179. this._statsDiv.style.background = background;
  26180. this._statsDiv.style.padding = "0px 0px 0px 5px";
  26181. this._generateheader(this._statsDiv, "STATISTICS");
  26182. this._statsSubsetDiv = document.createElement("div");
  26183. this._statsSubsetDiv.style.paddingTop = "5px";
  26184. this._statsSubsetDiv.style.paddingBottom = "5px";
  26185. this._statsSubsetDiv.style.overflowY = "auto";
  26186. this._statsDiv.appendChild(this._statsSubsetDiv);
  26187. // Tree
  26188. this._treeDiv = document.createElement("div");
  26189. this._treeDiv.id = "DebugLayerTree";
  26190. this._treeDiv.style.border = border;
  26191. this._treeDiv.style.position = "absolute";
  26192. this._treeDiv.style.background = background;
  26193. this._treeDiv.style.padding = "0px 0px 0px 5px";
  26194. this._treeDiv.style.display = "none";
  26195. this._generateheader(this._treeDiv, "MESHES TREE");
  26196. this._treeSubsetDiv = document.createElement("div");
  26197. this._treeSubsetDiv.style.paddingTop = "5px";
  26198. this._treeSubsetDiv.style.paddingRight = "5px";
  26199. this._treeSubsetDiv.style.overflowY = "auto";
  26200. this._treeSubsetDiv.style.maxHeight = "300px";
  26201. this._treeDiv.appendChild(this._treeSubsetDiv);
  26202. this._needToRefreshMeshesTree = true;
  26203. // Logs
  26204. this._logDiv = document.createElement("div");
  26205. this._logDiv.style.border = border;
  26206. this._logDiv.id = "DebugLayerLogs";
  26207. this._logDiv.style.position = "absolute";
  26208. this._logDiv.style.background = background;
  26209. this._logDiv.style.padding = "0px 0px 0px 5px";
  26210. this._logDiv.style.display = "none";
  26211. this._generateheader(this._logDiv, "LOGS");
  26212. this._logSubsetDiv = document.createElement("div");
  26213. this._logSubsetDiv.style.height = "127px";
  26214. this._logSubsetDiv.style.paddingTop = "5px";
  26215. this._logSubsetDiv.style.overflowY = "auto";
  26216. this._logSubsetDiv.style.fontSize = "12px";
  26217. this._logSubsetDiv.style.fontFamily = "consolas";
  26218. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  26219. this._logDiv.appendChild(this._logSubsetDiv);
  26220. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  26221. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  26222. };
  26223. // Options
  26224. this._optionsDiv = document.createElement("div");
  26225. this._optionsDiv.id = "DebugLayerOptions";
  26226. this._optionsDiv.style.border = border;
  26227. this._optionsDiv.style.position = "absolute";
  26228. this._optionsDiv.style.background = background;
  26229. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  26230. this._optionsDiv.style.overflowY = "auto";
  26231. this._generateheader(this._optionsDiv, "OPTIONS");
  26232. this._optionsSubsetDiv = document.createElement("div");
  26233. this._optionsSubsetDiv.style.paddingTop = "5px";
  26234. this._optionsSubsetDiv.style.paddingBottom = "5px";
  26235. this._optionsSubsetDiv.style.overflowY = "auto";
  26236. this._optionsSubsetDiv.style.maxHeight = "200px";
  26237. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  26238. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  26239. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  26240. _this._displayStatistics = element.checked;
  26241. });
  26242. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  26243. _this._displayLogs = element.checked;
  26244. });
  26245. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  26246. _this._displayTree = element.checked;
  26247. _this._needToRefreshMeshesTree = true;
  26248. });
  26249. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26250. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  26251. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  26252. _this._scene.forceShowBoundingBoxes = element.checked;
  26253. });
  26254. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  26255. _this._labelsEnabled = element.checked;
  26256. if (!_this._labelsEnabled) {
  26257. _this._clearLabels();
  26258. }
  26259. });
  26260. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  26261. if (element.checked) {
  26262. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  26263. }
  26264. else {
  26265. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  26266. }
  26267. });
  26268. ;
  26269. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26270. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  26271. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  26272. if (element.checked) {
  26273. _this._scene.forceWireframe = false;
  26274. _this._scene.forcePointsCloud = false;
  26275. }
  26276. });
  26277. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  26278. if (element.checked) {
  26279. _this._scene.forceWireframe = true;
  26280. _this._scene.forcePointsCloud = false;
  26281. }
  26282. });
  26283. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  26284. if (element.checked) {
  26285. _this._scene.forceWireframe = false;
  26286. _this._scene.forcePointsCloud = true;
  26287. }
  26288. });
  26289. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26290. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  26291. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  26292. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  26293. });
  26294. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  26295. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  26296. });
  26297. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  26298. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  26299. });
  26300. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  26301. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  26302. });
  26303. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  26304. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  26305. });
  26306. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  26307. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  26308. });
  26309. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  26310. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  26311. });
  26312. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  26313. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  26314. });
  26315. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26316. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  26317. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  26318. _this._scene.animationsEnabled = element.checked;
  26319. });
  26320. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  26321. _this._scene.collisionsEnabled = element.checked;
  26322. });
  26323. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  26324. _this._scene.fogEnabled = element.checked;
  26325. });
  26326. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  26327. _this._scene.lensFlaresEnabled = element.checked;
  26328. });
  26329. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  26330. _this._scene.lightsEnabled = element.checked;
  26331. });
  26332. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  26333. _this._scene.particlesEnabled = element.checked;
  26334. });
  26335. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  26336. _this._scene.postProcessesEnabled = element.checked;
  26337. });
  26338. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  26339. _this._scene.proceduralTexturesEnabled = element.checked;
  26340. });
  26341. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  26342. _this._scene.renderTargetsEnabled = element.checked;
  26343. });
  26344. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  26345. _this._scene.shadowsEnabled = element.checked;
  26346. });
  26347. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  26348. _this._scene.skeletonsEnabled = element.checked;
  26349. });
  26350. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  26351. _this._scene.texturesEnabled = element.checked;
  26352. });
  26353. this._globalDiv.appendChild(this._statsDiv);
  26354. this._globalDiv.appendChild(this._logDiv);
  26355. this._globalDiv.appendChild(this._optionsDiv);
  26356. this._globalDiv.appendChild(this._treeDiv);
  26357. }
  26358. };
  26359. DebugLayer.prototype._displayStats = function () {
  26360. var scene = this._scene;
  26361. var engine = scene.getEngine();
  26362. var glInfo = engine.getGlInfo();
  26363. 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>";
  26364. if (this.customStatsFunction) {
  26365. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  26366. }
  26367. };
  26368. return DebugLayer;
  26369. })();
  26370. BABYLON.DebugLayer = DebugLayer;
  26371. })(BABYLON || (BABYLON = {}));
  26372. //# sourceMappingURL=babylon.debugLayer.js.map
  26373. var BABYLON;
  26374. (function (BABYLON) {
  26375. var RawTexture = (function (_super) {
  26376. __extends(RawTexture, _super);
  26377. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  26378. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26379. if (invertY === void 0) { invertY = false; }
  26380. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26381. _super.call(this, null, scene, !generateMipMaps, invertY);
  26382. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  26383. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26384. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26385. }
  26386. // Statics
  26387. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26388. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26389. if (invertY === void 0) { invertY = false; }
  26390. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26391. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  26392. };
  26393. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26394. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26395. if (invertY === void 0) { invertY = false; }
  26396. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26397. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26398. };
  26399. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26400. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26401. if (invertY === void 0) { invertY = false; }
  26402. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26403. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26404. };
  26405. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26406. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26407. if (invertY === void 0) { invertY = false; }
  26408. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26409. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  26410. };
  26411. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26412. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26413. if (invertY === void 0) { invertY = false; }
  26414. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26415. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  26416. };
  26417. return RawTexture;
  26418. })(BABYLON.Texture);
  26419. BABYLON.RawTexture = RawTexture;
  26420. })(BABYLON || (BABYLON = {}));
  26421. //# sourceMappingURL=babylon.rawTexture.js.map
  26422. var BABYLON;
  26423. (function (BABYLON) {
  26424. var IndexedVector2 = (function (_super) {
  26425. __extends(IndexedVector2, _super);
  26426. function IndexedVector2(original, index) {
  26427. _super.call(this, original.x, original.y);
  26428. this.index = index;
  26429. }
  26430. return IndexedVector2;
  26431. })(BABYLON.Vector2);
  26432. var PolygonPoints = (function () {
  26433. function PolygonPoints() {
  26434. this.elements = new Array();
  26435. }
  26436. PolygonPoints.prototype.add = function (originalPoints) {
  26437. var _this = this;
  26438. var result = new Array();
  26439. originalPoints.forEach(function (point) {
  26440. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  26441. var newPoint = new IndexedVector2(point, _this.elements.length);
  26442. result.push(newPoint);
  26443. _this.elements.push(newPoint);
  26444. }
  26445. });
  26446. return result;
  26447. };
  26448. PolygonPoints.prototype.computeBounds = function () {
  26449. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26450. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26451. this.elements.forEach(function (point) {
  26452. // x
  26453. if (point.x < lmin.x) {
  26454. lmin.x = point.x;
  26455. }
  26456. else if (point.x > lmax.x) {
  26457. lmax.x = point.x;
  26458. }
  26459. // y
  26460. if (point.y < lmin.y) {
  26461. lmin.y = point.y;
  26462. }
  26463. else if (point.y > lmax.y) {
  26464. lmax.y = point.y;
  26465. }
  26466. });
  26467. return {
  26468. min: lmin,
  26469. max: lmax,
  26470. width: lmax.x - lmin.x,
  26471. height: lmax.y - lmin.y
  26472. };
  26473. };
  26474. return PolygonPoints;
  26475. })();
  26476. var Polygon = (function () {
  26477. function Polygon() {
  26478. }
  26479. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  26480. return [
  26481. new BABYLON.Vector2(xmin, ymin),
  26482. new BABYLON.Vector2(xmax, ymin),
  26483. new BABYLON.Vector2(xmax, ymax),
  26484. new BABYLON.Vector2(xmin, ymax)
  26485. ];
  26486. };
  26487. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  26488. if (cx === void 0) { cx = 0; }
  26489. if (cy === void 0) { cy = 0; }
  26490. if (numberOfSides === void 0) { numberOfSides = 32; }
  26491. var result = new Array();
  26492. var angle = 0;
  26493. var increment = (Math.PI * 2) / numberOfSides;
  26494. for (var i = 0; i < numberOfSides; i++) {
  26495. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  26496. angle -= increment;
  26497. }
  26498. return result;
  26499. };
  26500. Polygon.Parse = function (input) {
  26501. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  26502. var i, result = [];
  26503. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  26504. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  26505. }
  26506. return result;
  26507. };
  26508. Polygon.StartingAt = function (x, y) {
  26509. return BABYLON.Path2.StartingAt(x, y);
  26510. };
  26511. return Polygon;
  26512. })();
  26513. BABYLON.Polygon = Polygon;
  26514. var PolygonMeshBuilder = (function () {
  26515. function PolygonMeshBuilder(name, contours, scene) {
  26516. this._points = new PolygonPoints();
  26517. if (!("poly2tri" in window)) {
  26518. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  26519. }
  26520. this._name = name;
  26521. this._scene = scene;
  26522. var points;
  26523. if (contours instanceof BABYLON.Path2) {
  26524. points = contours.getPoints();
  26525. }
  26526. else {
  26527. points = contours;
  26528. }
  26529. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  26530. }
  26531. PolygonMeshBuilder.prototype.addHole = function (hole) {
  26532. this._swctx.addHole(this._points.add(hole));
  26533. return this;
  26534. };
  26535. PolygonMeshBuilder.prototype.build = function (updatable) {
  26536. if (updatable === void 0) { updatable = false; }
  26537. var result = new BABYLON.Mesh(this._name, this._scene);
  26538. var normals = [];
  26539. var positions = [];
  26540. var uvs = [];
  26541. var bounds = this._points.computeBounds();
  26542. this._points.elements.forEach(function (p) {
  26543. normals.push(0, 1.0, 0);
  26544. positions.push(p.x, 0, p.y);
  26545. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  26546. });
  26547. var indices = [];
  26548. this._swctx.triangulate();
  26549. this._swctx.getTriangles().forEach(function (triangle) {
  26550. triangle.getPoints().forEach(function (point) {
  26551. indices.push(point.index);
  26552. });
  26553. });
  26554. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  26555. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  26556. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  26557. result.setIndices(indices);
  26558. return result;
  26559. };
  26560. return PolygonMeshBuilder;
  26561. })();
  26562. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  26563. })(BABYLON || (BABYLON = {}));
  26564. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  26565. (function (BABYLON) {
  26566. var SimplificationSettings = (function () {
  26567. function SimplificationSettings(quality, distance) {
  26568. this.quality = quality;
  26569. this.distance = distance;
  26570. }
  26571. return SimplificationSettings;
  26572. })();
  26573. BABYLON.SimplificationSettings = SimplificationSettings;
  26574. /**
  26575. * The implemented types of simplification.
  26576. * At the moment only Quadratic Error Decimation is implemented.
  26577. */
  26578. (function (SimplificationType) {
  26579. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  26580. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  26581. var SimplificationType = BABYLON.SimplificationType;
  26582. var DecimationTriangle = (function () {
  26583. function DecimationTriangle(vertices) {
  26584. this.vertices = vertices;
  26585. this.error = new Array(4);
  26586. this.deleted = false;
  26587. this.isDirty = false;
  26588. this.borderFactor = 0;
  26589. }
  26590. return DecimationTriangle;
  26591. })();
  26592. BABYLON.DecimationTriangle = DecimationTriangle;
  26593. var DecimationVertex = (function () {
  26594. function DecimationVertex(position, normal, uv, id) {
  26595. this.position = position;
  26596. this.normal = normal;
  26597. this.uv = uv;
  26598. this.id = id;
  26599. this.isBorder = true;
  26600. this.q = new QuadraticMatrix();
  26601. this.triangleCount = 0;
  26602. this.triangleStart = 0;
  26603. }
  26604. return DecimationVertex;
  26605. })();
  26606. BABYLON.DecimationVertex = DecimationVertex;
  26607. var QuadraticMatrix = (function () {
  26608. function QuadraticMatrix(data) {
  26609. this.data = new Array(10);
  26610. for (var i = 0; i < 10; ++i) {
  26611. if (data && data[i]) {
  26612. this.data[i] = data[i];
  26613. }
  26614. else {
  26615. this.data[i] = 0;
  26616. }
  26617. }
  26618. }
  26619. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  26620. 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];
  26621. return det;
  26622. };
  26623. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  26624. for (var i = 0; i < 10; ++i) {
  26625. this.data[i] += matrix.data[i];
  26626. }
  26627. };
  26628. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  26629. for (var i = 0; i < 10; ++i) {
  26630. this.data[i] += data[i];
  26631. }
  26632. };
  26633. QuadraticMatrix.prototype.add = function (matrix) {
  26634. var m = new QuadraticMatrix();
  26635. for (var i = 0; i < 10; ++i) {
  26636. m.data[i] = this.data[i] + matrix.data[i];
  26637. }
  26638. return m;
  26639. };
  26640. QuadraticMatrix.FromData = function (a, b, c, d) {
  26641. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  26642. };
  26643. //returning an array to avoid garbage collection
  26644. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  26645. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  26646. };
  26647. return QuadraticMatrix;
  26648. })();
  26649. BABYLON.QuadraticMatrix = QuadraticMatrix;
  26650. var Reference = (function () {
  26651. function Reference(vertexId, triangleId) {
  26652. this.vertexId = vertexId;
  26653. this.triangleId = triangleId;
  26654. }
  26655. return Reference;
  26656. })();
  26657. BABYLON.Reference = Reference;
  26658. /**
  26659. * An implementation of the Quadratic Error simplification algorithm.
  26660. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  26661. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  26662. * @author RaananW
  26663. */
  26664. var QuadraticErrorSimplification = (function () {
  26665. function QuadraticErrorSimplification(_mesh) {
  26666. this._mesh = _mesh;
  26667. this.initialised = false;
  26668. this.syncIterations = 5000;
  26669. this.aggressiveness = 7;
  26670. this.decimationIterations = 100;
  26671. }
  26672. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  26673. var _this = this;
  26674. this.initWithMesh(this._mesh, function () {
  26675. _this.runDecimation(settings, successCallback);
  26676. });
  26677. };
  26678. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  26679. var _this = this;
  26680. var targetCount = ~~(this.triangles.length * settings.quality);
  26681. var deletedTriangles = 0;
  26682. var triangleCount = this.triangles.length;
  26683. var iterationFunction = function (iteration, callback) {
  26684. setTimeout(function () {
  26685. if (iteration % 5 === 0) {
  26686. _this.updateMesh(iteration === 0);
  26687. }
  26688. for (var i = 0; i < _this.triangles.length; ++i) {
  26689. _this.triangles[i].isDirty = false;
  26690. }
  26691. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  26692. var trianglesIterator = function (i) {
  26693. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  26694. var t = _this.triangles[tIdx];
  26695. if (!t)
  26696. return;
  26697. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  26698. return;
  26699. }
  26700. for (var j = 0; j < 3; ++j) {
  26701. if (t.error[j] < threshold) {
  26702. var deleted0 = [];
  26703. var deleted1 = [];
  26704. var i0 = t.vertices[j];
  26705. var i1 = t.vertices[(j + 1) % 3];
  26706. var v0 = _this.vertices[i0];
  26707. var v1 = _this.vertices[i1];
  26708. if (v0.isBorder !== v1.isBorder)
  26709. continue;
  26710. var p = BABYLON.Vector3.Zero();
  26711. var n = BABYLON.Vector3.Zero();
  26712. var uv = BABYLON.Vector2.Zero();
  26713. var color = new BABYLON.Color4(0, 0, 0, 1);
  26714. _this.calculateError(v0, v1, p, n, uv, color);
  26715. var delTr = [];
  26716. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  26717. continue;
  26718. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  26719. continue;
  26720. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  26721. continue;
  26722. }
  26723. v0.normal = n;
  26724. if (v0.uv)
  26725. v0.uv = uv;
  26726. else if (v0.color)
  26727. v0.color = color;
  26728. v0.q = v1.q.add(v0.q);
  26729. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  26730. continue;
  26731. if (p.equals(v0.position))
  26732. continue;
  26733. v0.position = p;
  26734. var tStart = _this.references.length;
  26735. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  26736. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  26737. var tCount = _this.references.length - tStart;
  26738. if (tCount <= v0.triangleCount) {
  26739. if (tCount) {
  26740. for (var c = 0; c < tCount; c++) {
  26741. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  26742. }
  26743. }
  26744. }
  26745. else {
  26746. v0.triangleStart = tStart;
  26747. }
  26748. v0.triangleCount = tCount;
  26749. break;
  26750. }
  26751. }
  26752. };
  26753. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  26754. return (triangleCount - deletedTriangles <= targetCount);
  26755. });
  26756. }, 0);
  26757. };
  26758. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  26759. if (triangleCount - deletedTriangles <= targetCount)
  26760. loop.breakLoop();
  26761. else {
  26762. iterationFunction(loop.index, function () {
  26763. loop.executeNext();
  26764. });
  26765. }
  26766. }, function () {
  26767. setTimeout(function () {
  26768. successCallback(_this.reconstructMesh());
  26769. }, 0);
  26770. });
  26771. };
  26772. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  26773. var _this = this;
  26774. if (!mesh)
  26775. return;
  26776. this.vertices = [];
  26777. this.triangles = [];
  26778. this._mesh = mesh;
  26779. //It is assumed that a mesh has positions, normals and either uvs or colors.
  26780. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26781. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26782. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26783. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26784. var indices = mesh.getIndices();
  26785. var vertexInit = function (i) {
  26786. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), null, i);
  26787. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26788. vertex.uv = BABYLON.Vector2.FromArray(uvs, i * 2);
  26789. }
  26790. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26791. vertex.color = BABYLON.Color4.FromArray(colorsData, i * 4);
  26792. }
  26793. _this.vertices.push(vertex);
  26794. };
  26795. var totalVertices = mesh.getTotalVertices();
  26796. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  26797. var indicesInit = function (i) {
  26798. var pos = i * 3;
  26799. var i0 = indices[pos + 0];
  26800. var i1 = indices[pos + 1];
  26801. var i2 = indices[pos + 2];
  26802. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  26803. _this.triangles.push(triangle);
  26804. };
  26805. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  26806. _this.init(callback);
  26807. });
  26808. });
  26809. };
  26810. QuadraticErrorSimplification.prototype.init = function (callback) {
  26811. var _this = this;
  26812. var triangleInit1 = function (i) {
  26813. var t = _this.triangles[i];
  26814. 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();
  26815. for (var j = 0; j < 3; j++) {
  26816. _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))));
  26817. }
  26818. };
  26819. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  26820. var triangleInit2 = function (i) {
  26821. var t = _this.triangles[i];
  26822. for (var j = 0; j < 3; ++j) {
  26823. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  26824. }
  26825. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  26826. };
  26827. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  26828. _this.initialised = true;
  26829. callback();
  26830. });
  26831. });
  26832. };
  26833. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  26834. var newTriangles = [];
  26835. var i;
  26836. for (i = 0; i < this.vertices.length; ++i) {
  26837. this.vertices[i].triangleCount = 0;
  26838. }
  26839. var t;
  26840. var j;
  26841. for (i = 0; i < this.triangles.length; ++i) {
  26842. if (!this.triangles[i].deleted) {
  26843. t = this.triangles[i];
  26844. for (j = 0; j < 3; ++j) {
  26845. this.vertices[t.vertices[j]].triangleCount = 1;
  26846. }
  26847. newTriangles.push(t);
  26848. }
  26849. }
  26850. var newVerticesOrder = [];
  26851. //compact vertices, get the IDs of the vertices used.
  26852. var dst = 0;
  26853. for (i = 0; i < this.vertices.length; ++i) {
  26854. if (this.vertices[i].triangleCount) {
  26855. this.vertices[i].triangleStart = dst;
  26856. this.vertices[dst].position = this.vertices[i].position;
  26857. this.vertices[dst].normal = this.vertices[i].normal;
  26858. this.vertices[dst].uv = this.vertices[i].uv;
  26859. this.vertices[dst].color = this.vertices[i].color;
  26860. newVerticesOrder.push(i);
  26861. dst++;
  26862. }
  26863. }
  26864. for (i = 0; i < newTriangles.length; ++i) {
  26865. t = newTriangles[i];
  26866. for (j = 0; j < 3; ++j) {
  26867. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  26868. }
  26869. }
  26870. this.vertices = this.vertices.slice(0, dst);
  26871. var newPositionData = [];
  26872. var newNormalData = [];
  26873. var newUVsData = [];
  26874. var newColorsData = [];
  26875. for (i = 0; i < newVerticesOrder.length; ++i) {
  26876. newPositionData.push(this.vertices[i].position.x);
  26877. newPositionData.push(this.vertices[i].position.y);
  26878. newPositionData.push(this.vertices[i].position.z);
  26879. newNormalData.push(this.vertices[i].normal.x);
  26880. newNormalData.push(this.vertices[i].normal.y);
  26881. newNormalData.push(this.vertices[i].normal.z);
  26882. if (this.vertices[i].uv) {
  26883. newUVsData.push(this.vertices[i].uv.x);
  26884. newUVsData.push(this.vertices[i].uv.y);
  26885. }
  26886. else if (this.vertices[i].color) {
  26887. newColorsData.push(this.vertices[i].color.r);
  26888. newColorsData.push(this.vertices[i].color.g);
  26889. newColorsData.push(this.vertices[i].color.b);
  26890. newColorsData.push(this.vertices[i].color.a);
  26891. }
  26892. }
  26893. var newIndicesArray = [];
  26894. for (i = 0; i < newTriangles.length; ++i) {
  26895. newIndicesArray.push(newTriangles[i].vertices[0]);
  26896. newIndicesArray.push(newTriangles[i].vertices[1]);
  26897. newIndicesArray.push(newTriangles[i].vertices[2]);
  26898. }
  26899. //not cloning, to avoid geometry problems. Creating a whole new mesh.
  26900. var newMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  26901. newMesh.material = this._mesh.material;
  26902. newMesh.parent = this._mesh.parent;
  26903. newMesh.setIndices(newIndicesArray);
  26904. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  26905. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  26906. if (newUVsData.length > 0)
  26907. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  26908. if (newColorsData.length > 0)
  26909. newMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  26910. //preparing the skeleton support
  26911. if (this._mesh.skeleton) {
  26912. }
  26913. return newMesh;
  26914. };
  26915. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  26916. for (var i = 0; i < vertex1.triangleCount; ++i) {
  26917. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  26918. if (t.deleted)
  26919. continue;
  26920. var s = this.references[vertex1.triangleStart + i].vertexId;
  26921. var id1 = t.vertices[(s + 1) % 3];
  26922. var id2 = t.vertices[(s + 2) % 3];
  26923. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  26924. deletedArray[i] = true;
  26925. delTr.push(t);
  26926. continue;
  26927. }
  26928. var d1 = this.vertices[id1].position.subtract(point);
  26929. d1 = d1.normalize();
  26930. var d2 = this.vertices[id2].position.subtract(point);
  26931. d2 = d2.normalize();
  26932. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  26933. return true;
  26934. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  26935. deletedArray[i] = false;
  26936. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  26937. return true;
  26938. }
  26939. return false;
  26940. };
  26941. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  26942. var newDeleted = deletedTriangles;
  26943. for (var i = 0; i < vertex.triangleCount; ++i) {
  26944. var ref = this.references[vertex.triangleStart + i];
  26945. var t = this.triangles[ref.triangleId];
  26946. if (t.deleted)
  26947. continue;
  26948. if (deletedArray[i]) {
  26949. t.deleted = true;
  26950. newDeleted++;
  26951. continue;
  26952. }
  26953. t.vertices[ref.vertexId] = vertexId;
  26954. t.isDirty = true;
  26955. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  26956. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  26957. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  26958. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  26959. this.references.push(ref);
  26960. }
  26961. return newDeleted;
  26962. };
  26963. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  26964. for (var i = 0; i < this.vertices.length; ++i) {
  26965. var vCount = [];
  26966. var vId = [];
  26967. var v = this.vertices[i];
  26968. var j;
  26969. for (j = 0; j < v.triangleCount; ++j) {
  26970. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  26971. for (var ii = 0; ii < 3; ii++) {
  26972. var ofs = 0;
  26973. var id = triangle.vertices[ii];
  26974. while (ofs < vCount.length) {
  26975. if (vId[ofs] === id)
  26976. break;
  26977. ++ofs;
  26978. }
  26979. if (ofs === vCount.length) {
  26980. vCount.push(1);
  26981. vId.push(id);
  26982. }
  26983. else {
  26984. vCount[ofs]++;
  26985. }
  26986. }
  26987. }
  26988. for (j = 0; j < vCount.length; ++j) {
  26989. if (vCount[j] === 1) {
  26990. this.vertices[vId[j]].isBorder = true;
  26991. }
  26992. else {
  26993. this.vertices[vId[j]].isBorder = false;
  26994. }
  26995. }
  26996. }
  26997. };
  26998. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  26999. if (identifyBorders === void 0) { identifyBorders = false; }
  27000. var i;
  27001. if (!identifyBorders) {
  27002. var newTrianglesVector = [];
  27003. for (i = 0; i < this.triangles.length; ++i) {
  27004. if (!this.triangles[i].deleted) {
  27005. newTrianglesVector.push(this.triangles[i]);
  27006. }
  27007. }
  27008. this.triangles = newTrianglesVector;
  27009. }
  27010. for (i = 0; i < this.vertices.length; ++i) {
  27011. this.vertices[i].triangleCount = 0;
  27012. this.vertices[i].triangleStart = 0;
  27013. }
  27014. var t;
  27015. var j;
  27016. var v;
  27017. for (i = 0; i < this.triangles.length; ++i) {
  27018. t = this.triangles[i];
  27019. for (j = 0; j < 3; ++j) {
  27020. v = this.vertices[t.vertices[j]];
  27021. v.triangleCount++;
  27022. }
  27023. }
  27024. var tStart = 0;
  27025. for (i = 0; i < this.vertices.length; ++i) {
  27026. this.vertices[i].triangleStart = tStart;
  27027. tStart += this.vertices[i].triangleCount;
  27028. this.vertices[i].triangleCount = 0;
  27029. }
  27030. var newReferences = new Array(this.triangles.length * 3);
  27031. for (i = 0; i < this.triangles.length; ++i) {
  27032. t = this.triangles[i];
  27033. for (j = 0; j < 3; ++j) {
  27034. v = this.vertices[t.vertices[j]];
  27035. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  27036. v.triangleCount++;
  27037. }
  27038. }
  27039. this.references = newReferences;
  27040. if (identifyBorders) {
  27041. this.identifyBorder();
  27042. }
  27043. };
  27044. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  27045. var x = point.x;
  27046. var y = point.y;
  27047. var z = point.z;
  27048. 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];
  27049. };
  27050. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  27051. var q = vertex1.q.add(vertex2.q);
  27052. var border = vertex1.isBorder && vertex2.isBorder;
  27053. var error = 0;
  27054. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  27055. if (qDet !== 0 && !border) {
  27056. if (!pointResult) {
  27057. pointResult = BABYLON.Vector3.Zero();
  27058. }
  27059. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  27060. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  27061. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  27062. error = this.vertexError(q, pointResult);
  27063. //TODO this should be correctly calculated
  27064. if (normalResult) {
  27065. normalResult.copyFrom(vertex1.normal);
  27066. if (vertex1.uv)
  27067. uvResult.copyFrom(vertex1.uv);
  27068. else if (vertex1.color)
  27069. colorResult.copyFrom(vertex1.color);
  27070. }
  27071. }
  27072. else {
  27073. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  27074. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  27075. var error1 = this.vertexError(q, vertex1.position);
  27076. var error2 = this.vertexError(q, vertex2.position);
  27077. var error3 = this.vertexError(q, p3);
  27078. error = Math.min(error1, error2, error3);
  27079. if (error === error1) {
  27080. if (pointResult) {
  27081. pointResult.copyFrom(vertex1.position);
  27082. normalResult.copyFrom(vertex1.normal);
  27083. if (vertex1.uv)
  27084. uvResult.copyFrom(vertex1.uv);
  27085. else if (vertex1.color)
  27086. colorResult.copyFrom(vertex1.color);
  27087. }
  27088. }
  27089. else if (error === error2) {
  27090. if (pointResult) {
  27091. pointResult.copyFrom(vertex2.position);
  27092. normalResult.copyFrom(vertex2.normal);
  27093. if (vertex2.uv)
  27094. uvResult.copyFrom(vertex2.uv);
  27095. else if (vertex2.color)
  27096. colorResult.copyFrom(vertex2.color);
  27097. }
  27098. }
  27099. else {
  27100. if (pointResult) {
  27101. pointResult.copyFrom(p3);
  27102. normalResult.copyFrom(vertex1.normal);
  27103. if (vertex1.uv)
  27104. uvResult.copyFrom(vertex1.uv);
  27105. else if (vertex1.color)
  27106. colorResult.copyFrom(vertex1.color);
  27107. }
  27108. }
  27109. }
  27110. return error;
  27111. };
  27112. return QuadraticErrorSimplification;
  27113. })();
  27114. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  27115. })(BABYLON || (BABYLON = {}));
  27116. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  27117. (function (BABYLON) {
  27118. var Analyser = (function () {
  27119. function Analyser(scene) {
  27120. this.SMOOTHING = 0.75;
  27121. this.FFT_SIZE = 512;
  27122. this.BARGRAPHAMPLITUDE = 256;
  27123. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  27124. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  27125. this._scene = scene;
  27126. this._audioEngine = BABYLON.Engine.audioEngine;
  27127. if (this._audioEngine.canUseWebAudio) {
  27128. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  27129. this._webAudioAnalyser.minDecibels = -140;
  27130. this._webAudioAnalyser.maxDecibels = 0;
  27131. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27132. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27133. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  27134. }
  27135. }
  27136. Analyser.prototype.getFrequencyBinCount = function () {
  27137. if (this._audioEngine.canUseWebAudio) {
  27138. return this._webAudioAnalyser.frequencyBinCount;
  27139. }
  27140. else {
  27141. return 0;
  27142. }
  27143. };
  27144. Analyser.prototype.getByteFrequencyData = function () {
  27145. if (this._audioEngine.canUseWebAudio) {
  27146. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27147. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27148. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  27149. }
  27150. return this._byteFreqs;
  27151. };
  27152. Analyser.prototype.getByteTimeDomainData = function () {
  27153. if (this._audioEngine.canUseWebAudio) {
  27154. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27155. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27156. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  27157. }
  27158. return this._byteTime;
  27159. };
  27160. Analyser.prototype.getFloatFrequencyData = function () {
  27161. if (this._audioEngine.canUseWebAudio) {
  27162. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27163. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27164. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  27165. }
  27166. return this._floatFreqs;
  27167. };
  27168. Analyser.prototype.drawDebugCanvas = function () {
  27169. var _this = this;
  27170. if (this._audioEngine.canUseWebAudio) {
  27171. if (!this._debugCanvas) {
  27172. this._debugCanvas = document.createElement("canvas");
  27173. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  27174. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  27175. this._debugCanvas.style.position = "absolute";
  27176. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  27177. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  27178. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  27179. document.body.appendChild(this._debugCanvas);
  27180. this._registerFunc = function () {
  27181. _this.drawDebugCanvas();
  27182. };
  27183. this._scene.registerBeforeRender(this._registerFunc);
  27184. }
  27185. if (this._registerFunc) {
  27186. var workingArray = this.getByteFrequencyData();
  27187. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  27188. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  27189. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  27190. var value = workingArray[i];
  27191. var percent = value / this.BARGRAPHAMPLITUDE;
  27192. var height = this.DEBUGCANVASSIZE.height * percent;
  27193. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  27194. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  27195. var hue = i / this.getFrequencyBinCount() * 360;
  27196. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  27197. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  27198. }
  27199. }
  27200. }
  27201. };
  27202. Analyser.prototype.stopDebugCanvas = function () {
  27203. if (this._debugCanvas) {
  27204. this._scene.unregisterBeforeRender(this._registerFunc);
  27205. this._registerFunc = null;
  27206. document.body.removeChild(this._debugCanvas);
  27207. this._debugCanvas = null;
  27208. this._debugCanvasContext = null;
  27209. }
  27210. };
  27211. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  27212. if (this._audioEngine.canUseWebAudio) {
  27213. inputAudioNode.connect(this._webAudioAnalyser);
  27214. this._webAudioAnalyser.connect(outputAudioNode);
  27215. }
  27216. };
  27217. Analyser.prototype.dispose = function () {
  27218. if (this._audioEngine.canUseWebAudio) {
  27219. this._webAudioAnalyser.disconnect();
  27220. }
  27221. };
  27222. return Analyser;
  27223. })();
  27224. BABYLON.Analyser = Analyser;
  27225. })(BABYLON || (BABYLON = {}));
  27226. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  27227. (function (BABYLON) {
  27228. var DepthRenderer = (function () {
  27229. function DepthRenderer(scene, type) {
  27230. var _this = this;
  27231. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  27232. this._viewMatrix = BABYLON.Matrix.Zero();
  27233. this._projectionMatrix = BABYLON.Matrix.Zero();
  27234. this._transformMatrix = BABYLON.Matrix.Zero();
  27235. this._worldViewProjection = BABYLON.Matrix.Zero();
  27236. this._scene = scene;
  27237. var engine = scene.getEngine();
  27238. // Render target
  27239. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  27240. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27241. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27242. this._depthMap.refreshRate = 1;
  27243. this._depthMap.renderParticles = false;
  27244. this._depthMap.renderList = null;
  27245. // Custom render function
  27246. var renderSubMesh = function (subMesh) {
  27247. var mesh = subMesh.getRenderingMesh();
  27248. var scene = _this._scene;
  27249. var engine = scene.getEngine();
  27250. // Culling
  27251. engine.setState(subMesh.getMaterial().backFaceCulling);
  27252. // Managing instances
  27253. var batch = mesh._getInstancesRenderList(subMesh._id);
  27254. if (batch.mustReturn) {
  27255. return;
  27256. }
  27257. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  27258. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  27259. engine.enableEffect(_this._effect);
  27260. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  27261. var material = subMesh.getMaterial();
  27262. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27263. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  27264. // Alpha test
  27265. if (material && material.needAlphaTesting()) {
  27266. var alphaTexture = material.getAlphaTestTexture();
  27267. _this._effect.setTexture("diffuseSampler", alphaTexture);
  27268. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27269. }
  27270. // Bones
  27271. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  27272. if (useBones) {
  27273. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27274. }
  27275. if (hardwareInstancedRendering) {
  27276. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  27277. }
  27278. else {
  27279. if (batch.renderSelf[subMesh._id]) {
  27280. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  27281. // Draw
  27282. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  27283. }
  27284. if (batch.visibleInstances[subMesh._id]) {
  27285. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  27286. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  27287. _this._effect.setMatrix("world", instance.getWorldMatrix());
  27288. // Draw
  27289. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  27290. }
  27291. }
  27292. }
  27293. }
  27294. };
  27295. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  27296. var index;
  27297. for (index = 0; index < opaqueSubMeshes.length; index++) {
  27298. renderSubMesh(opaqueSubMeshes.data[index]);
  27299. }
  27300. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  27301. renderSubMesh(alphaTestSubMeshes.data[index]);
  27302. }
  27303. };
  27304. }
  27305. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  27306. var defines = [];
  27307. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27308. var mesh = subMesh.getMesh();
  27309. var scene = mesh.getScene();
  27310. var material = subMesh.getMaterial();
  27311. // Alpha test
  27312. if (material && material.needAlphaTesting()) {
  27313. defines.push("#define ALPHATEST");
  27314. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27315. attribs.push(BABYLON.VertexBuffer.UVKind);
  27316. defines.push("#define UV1");
  27317. }
  27318. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27319. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27320. defines.push("#define UV2");
  27321. }
  27322. }
  27323. // Bones
  27324. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27325. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27326. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27327. defines.push("#define BONES");
  27328. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27329. }
  27330. // Instances
  27331. if (useInstances) {
  27332. defines.push("#define INSTANCES");
  27333. attribs.push("world0");
  27334. attribs.push("world1");
  27335. attribs.push("world2");
  27336. attribs.push("world3");
  27337. }
  27338. // Get correct effect
  27339. var join = defines.join("\n");
  27340. if (this._cachedDefines !== join) {
  27341. this._cachedDefines = join;
  27342. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  27343. }
  27344. return this._effect.isReady();
  27345. };
  27346. DepthRenderer.prototype.getDepthMap = function () {
  27347. return this._depthMap;
  27348. };
  27349. // Methods
  27350. DepthRenderer.prototype.dispose = function () {
  27351. this._depthMap.dispose();
  27352. };
  27353. return DepthRenderer;
  27354. })();
  27355. BABYLON.DepthRenderer = DepthRenderer;
  27356. })(BABYLON || (BABYLON = {}));
  27357. //# sourceMappingURL=babylon.depthRenderer.js.map
  27358. var BABYLON;
  27359. (function (BABYLON) {
  27360. var SSAORenderingPipeline = (function (_super) {
  27361. __extends(SSAORenderingPipeline, _super);
  27362. function SSAORenderingPipeline(name, scene, ratio) {
  27363. var _this = this;
  27364. if (ratio === void 0) { ratio = 1.0; }
  27365. _super.call(this, scene.getEngine(), name);
  27366. // Members
  27367. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  27368. this.SSAORenderEffect = "SSAORenderEffect";
  27369. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  27370. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  27371. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  27372. this._scene = null;
  27373. this._depthTexture = null;
  27374. this._randomTexture = null;
  27375. this._originalColorPostProcess = null;
  27376. this._ssaoPostProcess = null;
  27377. this._blurHPostProcess = null;
  27378. this._blurVPostProcess = null;
  27379. this._ssaoCombinePostProcess = null;
  27380. this._firstUpdate = true;
  27381. this._scene = scene;
  27382. // Set up assets
  27383. this._createRandomTexture();
  27384. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  27385. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27386. this._createSSAOPostProcess(ratio);
  27387. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlur", new BABYLON.Vector2(1.0, 0.0), 1.0, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27388. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlur", new BABYLON.Vector2(0.0, 1.0), 1.0, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27389. this._createSSAOCombinePostProcess();
  27390. // Set up pipeline
  27391. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  27392. return _this._originalColorPostProcess;
  27393. }, true));
  27394. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  27395. return _this._ssaoPostProcess;
  27396. }, true));
  27397. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  27398. return _this._blurHPostProcess;
  27399. }, true));
  27400. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  27401. return _this._blurVPostProcess;
  27402. }, true));
  27403. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  27404. return _this._ssaoCombinePostProcess;
  27405. }, true));
  27406. // Finish
  27407. scene.postProcessRenderPipelineManager.addPipeline(this);
  27408. }
  27409. // Public Methods
  27410. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  27411. return this._blurHPostProcess;
  27412. };
  27413. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  27414. return this._blurVPostProcess;
  27415. };
  27416. // Private Methods
  27417. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  27418. var _this = this;
  27419. var sampleSphere = [
  27420. 0.5381,
  27421. 0.1856,
  27422. -0.4319,
  27423. 0.1379,
  27424. 0.2486,
  27425. 0.4430,
  27426. 0.3371,
  27427. 0.5679,
  27428. -0.0057,
  27429. -0.6999,
  27430. -0.0451,
  27431. -0.0019,
  27432. 0.0689,
  27433. -0.1598,
  27434. -0.8547,
  27435. 0.0560,
  27436. 0.0069,
  27437. -0.1843,
  27438. -0.0146,
  27439. 0.1402,
  27440. 0.0762,
  27441. 0.0100,
  27442. -0.1924,
  27443. -0.0344,
  27444. -0.3577,
  27445. -0.5301,
  27446. -0.4358,
  27447. -0.3169,
  27448. 0.1063,
  27449. 0.0158,
  27450. 0.0103,
  27451. -0.5869,
  27452. 0.0046,
  27453. -0.0897,
  27454. -0.4940,
  27455. 0.3287,
  27456. 0.7119,
  27457. -0.0154,
  27458. -0.0918,
  27459. -0.0533,
  27460. 0.0596,
  27461. -0.5411,
  27462. 0.0352,
  27463. -0.0631,
  27464. 0.5460,
  27465. -0.4776,
  27466. 0.2847,
  27467. -0.0271
  27468. ];
  27469. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  27470. this._ssaoPostProcess.onApply = function (effect) {
  27471. if (_this._firstUpdate === true) {
  27472. effect.setArray3("sampleSphere", sampleSphere);
  27473. _this._firstUpdate = false;
  27474. }
  27475. effect.setTexture("textureSampler", _this._depthTexture);
  27476. effect.setTexture("randomSampler", _this._randomTexture);
  27477. };
  27478. return this._ssaoPostProcess;
  27479. };
  27480. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function () {
  27481. var _this = this;
  27482. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  27483. this._ssaoCombinePostProcess.onApply = function (effect) {
  27484. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  27485. };
  27486. return this._ssaoCombinePostProcess;
  27487. };
  27488. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  27489. var size = 512;
  27490. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  27491. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  27492. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  27493. var context = this._randomTexture.getContext();
  27494. var rand = function (min, max) {
  27495. return Math.random() * (max - min) + min;
  27496. };
  27497. for (var x = 0; x < size; x++) {
  27498. for (var y = 0; y < size; y++) {
  27499. var randVector = BABYLON.Vector3.Zero();
  27500. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  27501. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  27502. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  27503. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  27504. context.fillRect(x, y, 1, 1);
  27505. }
  27506. }
  27507. this._randomTexture.update(false);
  27508. };
  27509. return SSAORenderingPipeline;
  27510. })(BABYLON.PostProcessRenderPipeline);
  27511. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  27512. })(BABYLON || (BABYLON = {}));
  27513. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map