ourOwnBabylon.js 1.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Color3 = (function () {
  4. function Color3(r, g, b) {
  5. if (typeof r === "undefined") { r = 0; }
  6. if (typeof g === "undefined") { g = 0; }
  7. if (typeof b === "undefined") { b = 0; }
  8. this.r = r;
  9. this.g = g;
  10. this.b = b;
  11. }
  12. Color3.prototype.toString = function () {
  13. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  14. };
  15. Color3.prototype.toArray = function (array, index) {
  16. if (index === undefined) {
  17. index = 0;
  18. }
  19. array[index] = this.r;
  20. array[index + 1] = this.g;
  21. array[index + 2] = this.b;
  22. };
  23. Color3.prototype.toColor4 = function (alpha) {
  24. if (typeof alpha === "undefined") { alpha = 1; }
  25. return new Color4(this.r, this.g, this.b, alpha);
  26. };
  27. Color3.prototype.asArray = function () {
  28. var result = [];
  29. this.toArray(result, 0);
  30. return result;
  31. };
  32. Color3.prototype.toLuminance = function () {
  33. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  34. };
  35. Color3.prototype.multiply = function (otherColor) {
  36. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  37. };
  38. Color3.prototype.multiplyToRef = function (otherColor, result) {
  39. result.r = this.r * otherColor.r;
  40. result.g = this.g * otherColor.g;
  41. result.b = this.b * otherColor.b;
  42. };
  43. Color3.prototype.equals = function (otherColor) {
  44. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  45. };
  46. Color3.prototype.scale = function (scale) {
  47. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  48. };
  49. Color3.prototype.scaleToRef = function (scale, result) {
  50. result.r = this.r * scale;
  51. result.g = this.g * scale;
  52. result.b = this.b * scale;
  53. };
  54. Color3.prototype.add = function (otherColor) {
  55. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  56. };
  57. Color3.prototype.addToRef = function (otherColor, result) {
  58. result.r = this.r + otherColor.r;
  59. result.g = this.g + otherColor.g;
  60. result.b = this.b + otherColor.b;
  61. };
  62. Color3.prototype.subtract = function (otherColor) {
  63. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  64. };
  65. Color3.prototype.subtractToRef = function (otherColor, result) {
  66. result.r = this.r - otherColor.r;
  67. result.g = this.g - otherColor.g;
  68. result.b = this.b - otherColor.b;
  69. };
  70. Color3.prototype.clone = function () {
  71. return new Color3(this.r, this.g, this.b);
  72. };
  73. Color3.prototype.copyFrom = function (source) {
  74. this.r = source.r;
  75. this.g = source.g;
  76. this.b = source.b;
  77. };
  78. Color3.prototype.copyFromFloats = function (r, g, b) {
  79. this.r = r;
  80. this.g = g;
  81. this.b = b;
  82. };
  83. Color3.FromArray = function (array) {
  84. return new Color3(array[0], array[1], array[2]);
  85. };
  86. Color3.FromInts = function (r, g, b) {
  87. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  88. };
  89. Color3.Lerp = function (start, end, amount) {
  90. var r = start.r + ((end.r - start.r) * amount);
  91. var g = start.g + ((end.g - start.g) * amount);
  92. var b = start.b + ((end.b - start.b) * amount);
  93. return new Color3(r, g, b);
  94. };
  95. Color3.Red = function () {
  96. return new Color3(1, 0, 0);
  97. };
  98. Color3.Green = function () {
  99. return new Color3(0, 1, 0);
  100. };
  101. Color3.Blue = function () {
  102. return new Color3(0, 0, 1);
  103. };
  104. Color3.Black = function () {
  105. return new Color3(0, 0, 0);
  106. };
  107. Color3.White = function () {
  108. return new Color3(1, 1, 1);
  109. };
  110. Color3.Purple = function () {
  111. return new Color3(0.5, 0, 0.5);
  112. };
  113. Color3.Magenta = function () {
  114. return new Color3(1, 0, 1);
  115. };
  116. Color3.Yellow = function () {
  117. return new Color3(1, 1, 0);
  118. };
  119. Color3.Gray = function () {
  120. return new Color3(0.5, 0.5, 0.5);
  121. };
  122. return Color3;
  123. })();
  124. BABYLON.Color3 = Color3;
  125. var Color4 = (function () {
  126. function Color4(r, g, b, a) {
  127. this.r = r;
  128. this.g = g;
  129. this.b = b;
  130. this.a = a;
  131. }
  132. Color4.prototype.addInPlace = function (right) {
  133. this.r += right.r;
  134. this.g += right.g;
  135. this.b += right.b;
  136. this.a += right.a;
  137. };
  138. Color4.prototype.asArray = function () {
  139. var result = [];
  140. this.toArray(result, 0);
  141. return result;
  142. };
  143. Color4.prototype.toArray = function (array, index) {
  144. if (index === undefined) {
  145. index = 0;
  146. }
  147. array[index] = this.r;
  148. array[index + 1] = this.g;
  149. array[index + 2] = this.b;
  150. array[index + 3] = this.a;
  151. };
  152. Color4.prototype.add = function (right) {
  153. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  154. };
  155. Color4.prototype.subtract = function (right) {
  156. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  157. };
  158. Color4.prototype.subtractToRef = function (right, result) {
  159. result.r = this.r - right.r;
  160. result.g = this.g - right.g;
  161. result.b = this.b - right.b;
  162. result.a = this.a - right.a;
  163. };
  164. Color4.prototype.scale = function (scale) {
  165. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  166. };
  167. Color4.prototype.scaleToRef = function (scale, result) {
  168. result.r = this.r * scale;
  169. result.g = this.g * scale;
  170. result.b = this.b * scale;
  171. result.a = this.a * scale;
  172. };
  173. Color4.prototype.toString = function () {
  174. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  175. };
  176. Color4.prototype.clone = function () {
  177. return new Color4(this.r, this.g, this.b, this.a);
  178. };
  179. Color4.Lerp = function (left, right, amount) {
  180. var result = new Color4(0, 0, 0, 0);
  181. BABYLON.Color4.LerpToRef(left, right, amount, result);
  182. return result;
  183. };
  184. Color4.LerpToRef = function (left, right, amount, result) {
  185. result.r = left.r + (right.r - left.r) * amount;
  186. result.g = left.g + (right.g - left.g) * amount;
  187. result.b = left.b + (right.b - left.b) * amount;
  188. result.a = left.a + (right.a - left.a) * amount;
  189. };
  190. Color4.FromArray = function (array, offset) {
  191. if (typeof offset === "undefined") { offset = 0; }
  192. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  193. };
  194. Color4.FromInts = function (r, g, b, a) {
  195. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  196. };
  197. return Color4;
  198. })();
  199. BABYLON.Color4 = Color4;
  200. var Vector2 = (function () {
  201. function Vector2(x, y) {
  202. this.x = x;
  203. this.y = y;
  204. }
  205. Vector2.prototype.toString = function () {
  206. return "{X: " + this.x + " Y:" + this.y + "}";
  207. };
  208. Vector2.prototype.toArray = function (array, index) {
  209. if (index === undefined) {
  210. index = 0;
  211. }
  212. array[index] = this.x;
  213. array[index + 1] = this.y;
  214. };
  215. Vector2.prototype.asArray = function () {
  216. var result = [];
  217. this.toArray(result, 0);
  218. return result;
  219. };
  220. Vector2.prototype.copyFrom = function (source) {
  221. this.x = source.x;
  222. this.y = source.y;
  223. };
  224. Vector2.prototype.copyFromFloats = function (x, y) {
  225. this.x = x;
  226. this.y = y;
  227. };
  228. Vector2.prototype.add = function (otherVector) {
  229. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  230. };
  231. Vector2.prototype.addVector3 = function (otherVector) {
  232. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  233. };
  234. Vector2.prototype.subtract = function (otherVector) {
  235. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  236. };
  237. Vector2.prototype.subtractInPlace = function (otherVector) {
  238. this.x -= otherVector.x;
  239. this.y -= otherVector.y;
  240. };
  241. Vector2.prototype.multiplyInPlace = function (otherVector) {
  242. this.x *= otherVector.x;
  243. this.y *= otherVector.y;
  244. };
  245. Vector2.prototype.multiply = function (otherVector) {
  246. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  247. };
  248. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  249. result.x = this.x * otherVector.x;
  250. result.y = this.y * otherVector.y;
  251. };
  252. Vector2.prototype.multiplyByFloats = function (x, y) {
  253. return new Vector2(this.x * x, this.y * y);
  254. };
  255. Vector2.prototype.divide = function (otherVector) {
  256. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  257. };
  258. Vector2.prototype.divideToRef = function (otherVector, result) {
  259. result.x = this.x / otherVector.x;
  260. result.y = this.y / otherVector.y;
  261. };
  262. Vector2.prototype.negate = function () {
  263. return new Vector2(-this.x, -this.y);
  264. };
  265. Vector2.prototype.scaleInPlace = function (scale) {
  266. this.x *= scale;
  267. this.y *= scale;
  268. return this;
  269. };
  270. Vector2.prototype.scale = function (scale) {
  271. return new Vector2(this.x * scale, this.y * scale);
  272. };
  273. Vector2.prototype.equals = function (otherVector) {
  274. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  275. };
  276. Vector2.prototype.length = function () {
  277. return Math.sqrt(this.x * this.x + this.y * this.y);
  278. };
  279. Vector2.prototype.lengthSquared = function () {
  280. return (this.x * this.x + this.y * this.y);
  281. };
  282. Vector2.prototype.normalize = function () {
  283. var len = this.length();
  284. if (len === 0)
  285. return this;
  286. var num = 1.0 / len;
  287. this.x *= num;
  288. this.y *= num;
  289. return this;
  290. };
  291. Vector2.prototype.clone = function () {
  292. return new Vector2(this.x, this.y);
  293. };
  294. Vector2.Zero = function () {
  295. return new Vector2(0, 0);
  296. };
  297. Vector2.FromArray = function (array, offset) {
  298. if (!offset) {
  299. offset = 0;
  300. }
  301. return new Vector2(array[offset], array[offset + 1]);
  302. };
  303. Vector2.FromArrayToRef = function (array, offset, result) {
  304. result.x = array[offset];
  305. result.y = array[offset + 1];
  306. };
  307. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  308. var squared = amount * amount;
  309. var cubed = amount * squared;
  310. 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));
  311. 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));
  312. return new Vector2(x, y);
  313. };
  314. Vector2.Clamp = function (value, min, max) {
  315. var x = value.x;
  316. x = (x > max.x) ? max.x : x;
  317. x = (x < min.x) ? min.x : x;
  318. var y = value.y;
  319. y = (y > max.y) ? max.y : y;
  320. y = (y < min.y) ? min.y : y;
  321. return new Vector2(x, y);
  322. };
  323. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  324. var squared = amount * amount;
  325. var cubed = amount * squared;
  326. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  327. var part2 = (-2.0 * cubed) + (3.0 * squared);
  328. var part3 = (cubed - (2.0 * squared)) + amount;
  329. var part4 = cubed - squared;
  330. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  331. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  332. return new Vector2(x, y);
  333. };
  334. Vector2.Lerp = function (start, end, amount) {
  335. var x = start.x + ((end.x - start.x) * amount);
  336. var y = start.y + ((end.y - start.y) * amount);
  337. return new Vector2(x, y);
  338. };
  339. Vector2.Dot = function (left, right) {
  340. return left.x * right.x + left.y * right.y;
  341. };
  342. Vector2.Normalize = function (vector) {
  343. var newVector = vector.clone();
  344. newVector.normalize();
  345. return newVector;
  346. };
  347. Vector2.Minimize = function (left, right) {
  348. var x = (left.x < right.x) ? left.x : right.x;
  349. var y = (left.y < right.y) ? left.y : right.y;
  350. return new Vector2(x, y);
  351. };
  352. Vector2.Maximize = function (left, right) {
  353. var x = (left.x > right.x) ? left.x : right.x;
  354. var y = (left.y > right.y) ? left.y : right.y;
  355. return new Vector2(x, y);
  356. };
  357. Vector2.Transform = function (vector, transformation) {
  358. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  359. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  360. return new Vector2(x, y);
  361. };
  362. Vector2.Distance = function (value1, value2) {
  363. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  364. };
  365. Vector2.DistanceSquared = function (value1, value2) {
  366. var x = value1.x - value2.x;
  367. var y = value1.y - value2.y;
  368. return (x * x) + (y * y);
  369. };
  370. return Vector2;
  371. })();
  372. BABYLON.Vector2 = Vector2;
  373. var Vector3 = (function () {
  374. function Vector3(x, y, z) {
  375. this.x = x;
  376. this.y = y;
  377. this.z = z;
  378. }
  379. Vector3.prototype.toString = function () {
  380. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  381. };
  382. Vector3.prototype.asArray = function () {
  383. var result = [];
  384. this.toArray(result, 0);
  385. return result;
  386. };
  387. Vector3.prototype.toArray = function (array, index) {
  388. if (index === undefined) {
  389. index = 0;
  390. }
  391. array[index] = this.x;
  392. array[index + 1] = this.y;
  393. array[index + 2] = this.z;
  394. };
  395. Vector3.prototype.addInPlace = function (otherVector) {
  396. this.x += otherVector.x;
  397. this.y += otherVector.y;
  398. this.z += otherVector.z;
  399. };
  400. Vector3.prototype.add = function (otherVector) {
  401. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  402. };
  403. Vector3.prototype.addToRef = function (otherVector, result) {
  404. result.x = this.x + otherVector.x;
  405. result.y = this.y + otherVector.y;
  406. result.z = this.z + otherVector.z;
  407. };
  408. Vector3.prototype.subtractInPlace = function (otherVector) {
  409. this.x -= otherVector.x;
  410. this.y -= otherVector.y;
  411. this.z -= otherVector.z;
  412. };
  413. Vector3.prototype.subtract = function (otherVector) {
  414. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  415. };
  416. Vector3.prototype.subtractToRef = function (otherVector, result) {
  417. result.x = this.x - otherVector.x;
  418. result.y = this.y - otherVector.y;
  419. result.z = this.z - otherVector.z;
  420. };
  421. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  422. return new Vector3(this.x - x, this.y - y, this.z - z);
  423. };
  424. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  425. result.x = this.x - x;
  426. result.y = this.y - y;
  427. result.z = this.z - z;
  428. };
  429. Vector3.prototype.negate = function () {
  430. return new Vector3(-this.x, -this.y, -this.z);
  431. };
  432. Vector3.prototype.scaleInPlace = function (scale) {
  433. this.x *= scale;
  434. this.y *= scale;
  435. this.z *= scale;
  436. return this;
  437. };
  438. Vector3.prototype.scale = function (scale) {
  439. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  440. };
  441. Vector3.prototype.scaleToRef = function (scale, result) {
  442. result.x = this.x * scale;
  443. result.y = this.y * scale;
  444. result.z = this.z * scale;
  445. };
  446. Vector3.prototype.equals = function (otherVector) {
  447. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  448. };
  449. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  450. 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;
  451. };
  452. Vector3.prototype.equalsToFloats = function (x, y, z) {
  453. return this.x === x && this.y === y && this.z === z;
  454. };
  455. Vector3.prototype.multiplyInPlace = function (otherVector) {
  456. this.x *= otherVector.x;
  457. this.y *= otherVector.y;
  458. this.z *= otherVector.z;
  459. };
  460. Vector3.prototype.multiply = function (otherVector) {
  461. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  462. };
  463. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  464. result.x = this.x * otherVector.x;
  465. result.y = this.y * otherVector.y;
  466. result.z = this.z * otherVector.z;
  467. };
  468. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  469. return new Vector3(this.x * x, this.y * y, this.z * z);
  470. };
  471. Vector3.prototype.divide = function (otherVector) {
  472. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  473. };
  474. Vector3.prototype.divideToRef = function (otherVector, result) {
  475. result.x = this.x / otherVector.x;
  476. result.y = this.y / otherVector.y;
  477. result.z = this.z / otherVector.z;
  478. };
  479. Vector3.prototype.MinimizeInPlace = function (other) {
  480. if (other.x < this.x)
  481. this.x = other.x;
  482. if (other.y < this.y)
  483. this.y = other.y;
  484. if (other.z < this.z)
  485. this.z = other.z;
  486. };
  487. Vector3.prototype.MaximizeInPlace = function (other) {
  488. if (other.x > this.x)
  489. this.x = other.x;
  490. if (other.y > this.y)
  491. this.y = other.y;
  492. if (other.z > this.z)
  493. this.z = other.z;
  494. };
  495. Vector3.prototype.length = function () {
  496. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  497. };
  498. Vector3.prototype.lengthSquared = function () {
  499. return (this.x * this.x + this.y * this.y + this.z * this.z);
  500. };
  501. Vector3.prototype.normalize = function () {
  502. var len = this.length();
  503. if (len === 0)
  504. return this;
  505. var num = 1.0 / len;
  506. this.x *= num;
  507. this.y *= num;
  508. this.z *= num;
  509. return this;
  510. };
  511. Vector3.prototype.clone = function () {
  512. return new Vector3(this.x, this.y, this.z);
  513. };
  514. Vector3.prototype.copyFrom = function (source) {
  515. this.x = source.x;
  516. this.y = source.y;
  517. this.z = source.z;
  518. };
  519. Vector3.prototype.copyFromFloats = function (x, y, z) {
  520. this.x = x;
  521. this.y = y;
  522. this.z = z;
  523. };
  524. Vector3.FromArray = function (array, offset) {
  525. if (!offset) {
  526. offset = 0;
  527. }
  528. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  529. };
  530. Vector3.FromArrayToRef = function (array, offset, result) {
  531. result.x = array[offset];
  532. result.y = array[offset + 1];
  533. result.z = array[offset + 2];
  534. };
  535. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  536. result.x = array[offset];
  537. result.y = array[offset + 1];
  538. result.z = array[offset + 2];
  539. };
  540. Vector3.FromFloatsToRef = function (x, y, z, result) {
  541. result.x = x;
  542. result.y = y;
  543. result.z = z;
  544. };
  545. Vector3.Zero = function () {
  546. return new Vector3(0, 0, 0);
  547. };
  548. Vector3.Up = function () {
  549. return new Vector3(0, 1.0, 0);
  550. };
  551. Vector3.TransformCoordinates = function (vector, transformation) {
  552. var result = Vector3.Zero();
  553. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  554. return result;
  555. };
  556. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  557. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  558. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  559. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  560. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  561. result.x = x / w;
  562. result.y = y / w;
  563. result.z = z / w;
  564. };
  565. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  566. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  567. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  568. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  569. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  570. result.x = rx / rw;
  571. result.y = ry / rw;
  572. result.z = rz / rw;
  573. };
  574. Vector3.TransformNormal = function (vector, transformation) {
  575. var result = Vector3.Zero();
  576. Vector3.TransformNormalToRef(vector, transformation, result);
  577. return result;
  578. };
  579. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  580. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  581. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  582. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  583. };
  584. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  585. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  586. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  587. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  588. };
  589. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  590. var squared = amount * amount;
  591. var cubed = amount * squared;
  592. 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));
  593. 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));
  594. 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));
  595. return new Vector3(x, y, z);
  596. };
  597. Vector3.Clamp = function (value, min, max) {
  598. var x = value.x;
  599. x = (x > max.x) ? max.x : x;
  600. x = (x < min.x) ? min.x : x;
  601. var y = value.y;
  602. y = (y > max.y) ? max.y : y;
  603. y = (y < min.y) ? min.y : y;
  604. var z = value.z;
  605. z = (z > max.z) ? max.z : z;
  606. z = (z < min.z) ? min.z : z;
  607. return new Vector3(x, y, z);
  608. };
  609. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  610. var squared = amount * amount;
  611. var cubed = amount * squared;
  612. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  613. var part2 = (-2.0 * cubed) + (3.0 * squared);
  614. var part3 = (cubed - (2.0 * squared)) + amount;
  615. var part4 = cubed - squared;
  616. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  617. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  618. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  619. return new Vector3(x, y, z);
  620. };
  621. Vector3.Lerp = function (start, end, amount) {
  622. var x = start.x + ((end.x - start.x) * amount);
  623. var y = start.y + ((end.y - start.y) * amount);
  624. var z = start.z + ((end.z - start.z) * amount);
  625. return new Vector3(x, y, z);
  626. };
  627. Vector3.Dot = function (left, right) {
  628. return (left.x * right.x + left.y * right.y + left.z * right.z);
  629. };
  630. Vector3.Cross = function (left, right) {
  631. var result = Vector3.Zero();
  632. Vector3.CrossToRef(left, right, result);
  633. return result;
  634. };
  635. Vector3.CrossToRef = function (left, right, result) {
  636. result.x = left.y * right.z - left.z * right.y;
  637. result.y = left.z * right.x - left.x * right.z;
  638. result.z = left.x * right.y - left.y * right.x;
  639. };
  640. Vector3.Normalize = function (vector) {
  641. var result = Vector3.Zero();
  642. Vector3.NormalizeToRef(vector, result);
  643. return result;
  644. };
  645. Vector3.NormalizeToRef = function (vector, result) {
  646. result.copyFrom(vector);
  647. result.normalize();
  648. };
  649. Vector3.Project = function (vector, world, transform, viewport) {
  650. var cw = viewport.width;
  651. var ch = viewport.height;
  652. var cx = viewport.x;
  653. var cy = viewport.y;
  654. var viewportMatrix = BABYLON.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);
  655. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  656. return Vector3.TransformCoordinates(vector, finalMatrix);
  657. };
  658. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  659. var matrix = world.multiply(view).multiply(projection);
  660. matrix.invert();
  661. source.x = source.x / viewportWidth * 2 - 1;
  662. source.y = -(source.y / viewportHeight * 2 - 1);
  663. var vector = BABYLON.Vector3.TransformCoordinates(source, matrix);
  664. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  665. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  666. vector = vector.scale(1.0 / num);
  667. }
  668. return vector;
  669. };
  670. Vector3.Minimize = function (left, right) {
  671. var min = left.clone();
  672. min.MinimizeInPlace(right);
  673. return min;
  674. };
  675. Vector3.Maximize = function (left, right) {
  676. var max = left.clone();
  677. max.MaximizeInPlace(right);
  678. return max;
  679. };
  680. Vector3.Distance = function (value1, value2) {
  681. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  682. };
  683. Vector3.DistanceSquared = function (value1, value2) {
  684. var x = value1.x - value2.x;
  685. var y = value1.y - value2.y;
  686. var z = value1.z - value2.z;
  687. return (x * x) + (y * y) + (z * z);
  688. };
  689. Vector3.Center = function (value1, value2) {
  690. var center = value1.add(value2);
  691. center.scaleInPlace(0.5);
  692. return center;
  693. };
  694. return Vector3;
  695. })();
  696. BABYLON.Vector3 = Vector3;
  697. var Quaternion = (function () {
  698. function Quaternion(x, y, z, w) {
  699. if (typeof x === "undefined") { x = 0; }
  700. if (typeof y === "undefined") { y = 0; }
  701. if (typeof z === "undefined") { z = 0; }
  702. if (typeof w === "undefined") { w = 1; }
  703. this.x = x;
  704. this.y = y;
  705. this.z = z;
  706. this.w = w;
  707. }
  708. Quaternion.prototype.toString = function () {
  709. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  710. };
  711. Quaternion.prototype.asArray = function () {
  712. return [this.x, this.y, this.z, this.w];
  713. };
  714. Quaternion.prototype.equals = function (otherQuaternion) {
  715. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  716. };
  717. Quaternion.prototype.clone = function () {
  718. return new Quaternion(this.x, this.y, this.z, this.w);
  719. };
  720. Quaternion.prototype.copyFrom = function (other) {
  721. this.x = other.x;
  722. this.y = other.y;
  723. this.z = other.z;
  724. this.w = other.w;
  725. };
  726. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  727. this.x = x;
  728. this.y = y;
  729. this.z = z;
  730. this.w = w;
  731. };
  732. Quaternion.prototype.add = function (other) {
  733. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  734. };
  735. Quaternion.prototype.subtract = function (other) {
  736. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  737. };
  738. Quaternion.prototype.scale = function (value) {
  739. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  740. };
  741. Quaternion.prototype.multiply = function (q1) {
  742. var result = new Quaternion(0, 0, 0, 1.0);
  743. this.multiplyToRef(q1, result);
  744. return result;
  745. };
  746. Quaternion.prototype.multiplyToRef = function (q1, result) {
  747. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  748. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  749. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  750. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  751. };
  752. Quaternion.prototype.length = function () {
  753. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  754. };
  755. Quaternion.prototype.normalize = function () {
  756. var length = 1.0 / this.length();
  757. this.x *= length;
  758. this.y *= length;
  759. this.z *= length;
  760. this.w *= length;
  761. };
  762. Quaternion.prototype.toEulerAngles = function () {
  763. var result = Vector3.Zero();
  764. this.toEulerAnglesToRef(result);
  765. return result;
  766. };
  767. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  768. var qx = this.x;
  769. var qy = this.y;
  770. var qz = this.z;
  771. var qw = this.w;
  772. var sqx = qx * qx;
  773. var sqy = qy * qy;
  774. var sqz = qz * qz;
  775. var yaw = Math.atan2(2.0 * (qy * qw - qx * qz), 1.0 - 2.0 * (sqy + sqz));
  776. var pitch = Math.asin(2.0 * (qx * qy + qz * qw));
  777. var roll = Math.atan2(2.0 * (qx * qw - qy * qz), 1.0 - 2.0 * (sqx + sqz));
  778. var gimbaLockTest = qx * qy + qz * qw;
  779. if (gimbaLockTest > 0.499) {
  780. yaw = 2.0 * Math.atan2(qx, qw);
  781. roll = 0;
  782. } else if (gimbaLockTest < -0.499) {
  783. yaw = -2.0 * Math.atan2(qx, qw);
  784. roll = 0;
  785. }
  786. result.x = pitch;
  787. result.y = yaw;
  788. result.z = roll;
  789. };
  790. Quaternion.prototype.toRotationMatrix = function (result) {
  791. var xx = this.x * this.x;
  792. var yy = this.y * this.y;
  793. var zz = this.z * this.z;
  794. var xy = this.x * this.y;
  795. var zw = this.z * this.w;
  796. var zx = this.z * this.x;
  797. var yw = this.y * this.w;
  798. var yz = this.y * this.z;
  799. var xw = this.x * this.w;
  800. result.m[0] = 1.0 - (2.0 * (yy + zz));
  801. result.m[1] = 2.0 * (xy + zw);
  802. result.m[2] = 2.0 * (zx - yw);
  803. result.m[3] = 0;
  804. result.m[4] = 2.0 * (xy - zw);
  805. result.m[5] = 1.0 - (2.0 * (zz + xx));
  806. result.m[6] = 2.0 * (yz + xw);
  807. result.m[7] = 0;
  808. result.m[8] = 2.0 * (zx + yw);
  809. result.m[9] = 2.0 * (yz - xw);
  810. result.m[10] = 1.0 - (2.0 * (yy + xx));
  811. result.m[11] = 0;
  812. result.m[12] = 0;
  813. result.m[13] = 0;
  814. result.m[14] = 0;
  815. result.m[15] = 1.0;
  816. };
  817. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  818. var data = matrix.m;
  819. var m11 = data[0], m12 = data[4], m13 = data[8];
  820. var m21 = data[1], m22 = data[5], m23 = data[9];
  821. var m31 = data[2], m32 = data[6], m33 = data[10];
  822. var trace = m11 + m22 + m33;
  823. var s;
  824. if (trace > 0) {
  825. s = 0.5 / Math.sqrt(trace + 1.0);
  826. this.w = 0.25 / s;
  827. this.x = (m32 - m23) * s;
  828. this.y = (m13 - m31) * s;
  829. this.z = (m21 - m12) * s;
  830. return;
  831. }
  832. if (m11 > m22 && m11 > m33) {
  833. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  834. this.w = (m32 - m23) / s;
  835. this.x = 0.25 * s;
  836. this.y = (m12 + m21) / s;
  837. this.z = (m13 + m31) / s;
  838. return;
  839. }
  840. if (m22 > m33) {
  841. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  842. this.w = (m13 - m31) / s;
  843. this.x = (m12 + m21) / s;
  844. this.y = 0.25 * s;
  845. this.z = (m23 + m32) / s;
  846. return;
  847. }
  848. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  849. this.w = (m21 - m12) / s;
  850. this.x = (m13 + m31) / s;
  851. this.y = (m23 + m32) / s;
  852. this.z = 0.25 * s;
  853. };
  854. Quaternion.Inverse = function (q) {
  855. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  856. };
  857. Quaternion.RotationAxis = function (axis, angle) {
  858. var result = new Quaternion();
  859. var sin = Math.sin(angle / 2);
  860. result.w = Math.cos(angle / 2);
  861. result.x = axis.x * sin;
  862. result.y = axis.y * sin;
  863. result.z = axis.z * sin;
  864. return result;
  865. };
  866. Quaternion.FromArray = function (array, offset) {
  867. if (!offset) {
  868. offset = 0;
  869. }
  870. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  871. };
  872. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  873. var result = new Quaternion();
  874. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  875. return result;
  876. };
  877. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  878. var halfRoll = roll * 0.5;
  879. var halfPitch = pitch * 0.5;
  880. var halfYaw = yaw * 0.5;
  881. var sinRoll = Math.sin(halfRoll);
  882. var cosRoll = Math.cos(halfRoll);
  883. var sinPitch = Math.sin(halfPitch);
  884. var cosPitch = Math.cos(halfPitch);
  885. var sinYaw = Math.sin(halfYaw);
  886. var cosYaw = Math.cos(halfYaw);
  887. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  888. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  889. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  890. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  891. };
  892. Quaternion.Slerp = function (left, right, amount) {
  893. var num2;
  894. var num3;
  895. var num = amount;
  896. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  897. var flag = false;
  898. if (num4 < 0) {
  899. flag = true;
  900. num4 = -num4;
  901. }
  902. if (num4 > 0.999999) {
  903. num3 = 1 - num;
  904. num2 = flag ? -num : num;
  905. } else {
  906. var num5 = Math.acos(num4);
  907. var num6 = (1.0 / Math.sin(num5));
  908. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  909. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  910. }
  911. 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));
  912. };
  913. return Quaternion;
  914. })();
  915. BABYLON.Quaternion = Quaternion;
  916. var Matrix = (function () {
  917. function Matrix() {
  918. this.m = new Float32Array(16);
  919. }
  920. Matrix.prototype.isIdentity = function () {
  921. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  922. return false;
  923. 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)
  924. return false;
  925. return true;
  926. };
  927. Matrix.prototype.determinant = function () {
  928. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  929. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  930. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  931. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  932. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  933. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  934. 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))));
  935. };
  936. Matrix.prototype.toArray = function () {
  937. return this.m;
  938. };
  939. Matrix.prototype.asArray = function () {
  940. return this.toArray();
  941. };
  942. Matrix.prototype.invert = function () {
  943. this.invertToRef(this);
  944. };
  945. Matrix.prototype.invertToRef = function (other) {
  946. var l1 = this.m[0];
  947. var l2 = this.m[1];
  948. var l3 = this.m[2];
  949. var l4 = this.m[3];
  950. var l5 = this.m[4];
  951. var l6 = this.m[5];
  952. var l7 = this.m[6];
  953. var l8 = this.m[7];
  954. var l9 = this.m[8];
  955. var l10 = this.m[9];
  956. var l11 = this.m[10];
  957. var l12 = this.m[11];
  958. var l13 = this.m[12];
  959. var l14 = this.m[13];
  960. var l15 = this.m[14];
  961. var l16 = this.m[15];
  962. var l17 = (l11 * l16) - (l12 * l15);
  963. var l18 = (l10 * l16) - (l12 * l14);
  964. var l19 = (l10 * l15) - (l11 * l14);
  965. var l20 = (l9 * l16) - (l12 * l13);
  966. var l21 = (l9 * l15) - (l11 * l13);
  967. var l22 = (l9 * l14) - (l10 * l13);
  968. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  969. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  970. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  971. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  972. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  973. var l28 = (l7 * l16) - (l8 * l15);
  974. var l29 = (l6 * l16) - (l8 * l14);
  975. var l30 = (l6 * l15) - (l7 * l14);
  976. var l31 = (l5 * l16) - (l8 * l13);
  977. var l32 = (l5 * l15) - (l7 * l13);
  978. var l33 = (l5 * l14) - (l6 * l13);
  979. var l34 = (l7 * l12) - (l8 * l11);
  980. var l35 = (l6 * l12) - (l8 * l10);
  981. var l36 = (l6 * l11) - (l7 * l10);
  982. var l37 = (l5 * l12) - (l8 * l9);
  983. var l38 = (l5 * l11) - (l7 * l9);
  984. var l39 = (l5 * l10) - (l6 * l9);
  985. other.m[0] = l23 * l27;
  986. other.m[4] = l24 * l27;
  987. other.m[8] = l25 * l27;
  988. other.m[12] = l26 * l27;
  989. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  990. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  991. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  992. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  993. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  994. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  995. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  996. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  997. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  998. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  999. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1000. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1001. };
  1002. Matrix.prototype.setTranslation = function (vector3) {
  1003. this.m[12] = vector3.x;
  1004. this.m[13] = vector3.y;
  1005. this.m[14] = vector3.z;
  1006. };
  1007. Matrix.prototype.multiply = function (other) {
  1008. var result = new Matrix();
  1009. this.multiplyToRef(other, result);
  1010. return result;
  1011. };
  1012. Matrix.prototype.copyFrom = function (other) {
  1013. for (var index = 0; index < 16; index++) {
  1014. this.m[index] = other.m[index];
  1015. }
  1016. };
  1017. Matrix.prototype.copyToArray = function (array, offset) {
  1018. if (typeof offset === "undefined") { offset = 0; }
  1019. for (var index = 0; index < 16; index++) {
  1020. array[offset + index] = this.m[index];
  1021. }
  1022. };
  1023. Matrix.prototype.multiplyToRef = function (other, result) {
  1024. this.multiplyToArray(other, result.m, 0);
  1025. };
  1026. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1027. var tm0 = this.m[0];
  1028. var tm1 = this.m[1];
  1029. var tm2 = this.m[2];
  1030. var tm3 = this.m[3];
  1031. var tm4 = this.m[4];
  1032. var tm5 = this.m[5];
  1033. var tm6 = this.m[6];
  1034. var tm7 = this.m[7];
  1035. var tm8 = this.m[8];
  1036. var tm9 = this.m[9];
  1037. var tm10 = this.m[10];
  1038. var tm11 = this.m[11];
  1039. var tm12 = this.m[12];
  1040. var tm13 = this.m[13];
  1041. var tm14 = this.m[14];
  1042. var tm15 = this.m[15];
  1043. var om0 = other.m[0];
  1044. var om1 = other.m[1];
  1045. var om2 = other.m[2];
  1046. var om3 = other.m[3];
  1047. var om4 = other.m[4];
  1048. var om5 = other.m[5];
  1049. var om6 = other.m[6];
  1050. var om7 = other.m[7];
  1051. var om8 = other.m[8];
  1052. var om9 = other.m[9];
  1053. var om10 = other.m[10];
  1054. var om11 = other.m[11];
  1055. var om12 = other.m[12];
  1056. var om13 = other.m[13];
  1057. var om14 = other.m[14];
  1058. var om15 = other.m[15];
  1059. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1060. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1061. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1062. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1063. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1064. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1065. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1066. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1067. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1068. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1069. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1070. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1071. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1072. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1073. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1074. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1075. };
  1076. Matrix.prototype.equals = function (value) {
  1077. 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]);
  1078. };
  1079. Matrix.prototype.clone = function () {
  1080. 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]);
  1081. };
  1082. Matrix.FromArray = function (array, offset) {
  1083. var result = new Matrix();
  1084. if (!offset) {
  1085. offset = 0;
  1086. }
  1087. Matrix.FromArrayToRef(array, offset, result);
  1088. return result;
  1089. };
  1090. Matrix.FromArrayToRef = function (array, offset, result) {
  1091. for (var index = 0; index < 16; index++) {
  1092. result.m[index] = array[index + offset];
  1093. }
  1094. };
  1095. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1096. result.m[0] = initialM11;
  1097. result.m[1] = initialM12;
  1098. result.m[2] = initialM13;
  1099. result.m[3] = initialM14;
  1100. result.m[4] = initialM21;
  1101. result.m[5] = initialM22;
  1102. result.m[6] = initialM23;
  1103. result.m[7] = initialM24;
  1104. result.m[8] = initialM31;
  1105. result.m[9] = initialM32;
  1106. result.m[10] = initialM33;
  1107. result.m[11] = initialM34;
  1108. result.m[12] = initialM41;
  1109. result.m[13] = initialM42;
  1110. result.m[14] = initialM43;
  1111. result.m[15] = initialM44;
  1112. };
  1113. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1114. var result = new Matrix();
  1115. result.m[0] = initialM11;
  1116. result.m[1] = initialM12;
  1117. result.m[2] = initialM13;
  1118. result.m[3] = initialM14;
  1119. result.m[4] = initialM21;
  1120. result.m[5] = initialM22;
  1121. result.m[6] = initialM23;
  1122. result.m[7] = initialM24;
  1123. result.m[8] = initialM31;
  1124. result.m[9] = initialM32;
  1125. result.m[10] = initialM33;
  1126. result.m[11] = initialM34;
  1127. result.m[12] = initialM41;
  1128. result.m[13] = initialM42;
  1129. result.m[14] = initialM43;
  1130. result.m[15] = initialM44;
  1131. return result;
  1132. };
  1133. Matrix.Identity = function () {
  1134. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1135. };
  1136. Matrix.IdentityToRef = function (result) {
  1137. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1138. };
  1139. Matrix.Zero = function () {
  1140. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1141. };
  1142. Matrix.RotationX = function (angle) {
  1143. var result = new Matrix();
  1144. Matrix.RotationXToRef(angle, result);
  1145. return result;
  1146. };
  1147. Matrix.RotationXToRef = function (angle, result) {
  1148. var s = Math.sin(angle);
  1149. var c = Math.cos(angle);
  1150. result.m[0] = 1.0;
  1151. result.m[15] = 1.0;
  1152. result.m[5] = c;
  1153. result.m[10] = c;
  1154. result.m[9] = -s;
  1155. result.m[6] = s;
  1156. result.m[1] = 0;
  1157. result.m[2] = 0;
  1158. result.m[3] = 0;
  1159. result.m[4] = 0;
  1160. result.m[7] = 0;
  1161. result.m[8] = 0;
  1162. result.m[11] = 0;
  1163. result.m[12] = 0;
  1164. result.m[13] = 0;
  1165. result.m[14] = 0;
  1166. };
  1167. Matrix.RotationY = function (angle) {
  1168. var result = new Matrix();
  1169. Matrix.RotationYToRef(angle, result);
  1170. return result;
  1171. };
  1172. Matrix.RotationYToRef = function (angle, result) {
  1173. var s = Math.sin(angle);
  1174. var c = Math.cos(angle);
  1175. result.m[5] = 1.0;
  1176. result.m[15] = 1.0;
  1177. result.m[0] = c;
  1178. result.m[2] = -s;
  1179. result.m[8] = s;
  1180. result.m[10] = c;
  1181. result.m[1] = 0;
  1182. result.m[3] = 0;
  1183. result.m[4] = 0;
  1184. result.m[6] = 0;
  1185. result.m[7] = 0;
  1186. result.m[9] = 0;
  1187. result.m[11] = 0;
  1188. result.m[12] = 0;
  1189. result.m[13] = 0;
  1190. result.m[14] = 0;
  1191. };
  1192. Matrix.RotationZ = function (angle) {
  1193. var result = new Matrix();
  1194. Matrix.RotationZToRef(angle, result);
  1195. return result;
  1196. };
  1197. Matrix.RotationZToRef = function (angle, result) {
  1198. var s = Math.sin(angle);
  1199. var c = Math.cos(angle);
  1200. result.m[10] = 1.0;
  1201. result.m[15] = 1.0;
  1202. result.m[0] = c;
  1203. result.m[1] = s;
  1204. result.m[4] = -s;
  1205. result.m[5] = c;
  1206. result.m[2] = 0;
  1207. result.m[3] = 0;
  1208. result.m[6] = 0;
  1209. result.m[7] = 0;
  1210. result.m[8] = 0;
  1211. result.m[9] = 0;
  1212. result.m[11] = 0;
  1213. result.m[12] = 0;
  1214. result.m[13] = 0;
  1215. result.m[14] = 0;
  1216. };
  1217. Matrix.RotationAxis = function (axis, angle) {
  1218. var s = Math.sin(-angle);
  1219. var c = Math.cos(-angle);
  1220. var c1 = 1 - c;
  1221. axis.normalize();
  1222. var result = Matrix.Zero();
  1223. result.m[0] = (axis.x * axis.x) * c1 + c;
  1224. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1225. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1226. result.m[3] = 0.0;
  1227. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1228. result.m[5] = (axis.y * axis.y) * c1 + c;
  1229. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1230. result.m[7] = 0.0;
  1231. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1232. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1233. result.m[10] = (axis.z * axis.z) * c1 + c;
  1234. result.m[11] = 0.0;
  1235. result.m[15] = 1.0;
  1236. return result;
  1237. };
  1238. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1239. var result = new Matrix();
  1240. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1241. return result;
  1242. };
  1243. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1244. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1245. this._tempQuaternion.toRotationMatrix(result);
  1246. };
  1247. Matrix.Scaling = function (x, y, z) {
  1248. var result = Matrix.Zero();
  1249. Matrix.ScalingToRef(x, y, z, result);
  1250. return result;
  1251. };
  1252. Matrix.ScalingToRef = function (x, y, z, result) {
  1253. result.m[0] = x;
  1254. result.m[1] = 0;
  1255. result.m[2] = 0;
  1256. result.m[3] = 0;
  1257. result.m[4] = 0;
  1258. result.m[5] = y;
  1259. result.m[6] = 0;
  1260. result.m[7] = 0;
  1261. result.m[8] = 0;
  1262. result.m[9] = 0;
  1263. result.m[10] = z;
  1264. result.m[11] = 0;
  1265. result.m[12] = 0;
  1266. result.m[13] = 0;
  1267. result.m[14] = 0;
  1268. result.m[15] = 1.0;
  1269. };
  1270. Matrix.Translation = function (x, y, z) {
  1271. var result = Matrix.Identity();
  1272. Matrix.TranslationToRef(x, y, z, result);
  1273. return result;
  1274. };
  1275. Matrix.TranslationToRef = function (x, y, z, result) {
  1276. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1277. };
  1278. Matrix.LookAtLH = function (eye, target, up) {
  1279. var result = Matrix.Zero();
  1280. Matrix.LookAtLHToRef(eye, target, up, result);
  1281. return result;
  1282. };
  1283. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1284. target.subtractToRef(eye, this._zAxis);
  1285. this._zAxis.normalize();
  1286. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1287. this._xAxis.normalize();
  1288. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1289. this._yAxis.normalize();
  1290. var ex = -Vector3.Dot(this._xAxis, eye);
  1291. var ey = -Vector3.Dot(this._yAxis, eye);
  1292. var ez = -Vector3.Dot(this._zAxis, eye);
  1293. 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);
  1294. };
  1295. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1296. var hw = 2.0 / width;
  1297. var hh = 2.0 / height;
  1298. var id = 1.0 / (zfar - znear);
  1299. var nid = znear / (znear - zfar);
  1300. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1301. };
  1302. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1303. var matrix = Matrix.Zero();
  1304. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1305. return matrix;
  1306. };
  1307. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1308. result.m[0] = 2.0 / (right - left);
  1309. result.m[1] = result.m[2] = result.m[3] = 0;
  1310. result.m[5] = 2.0 / (top - bottom);
  1311. result.m[4] = result.m[6] = result.m[7] = 0;
  1312. result.m[10] = -1.0 / (znear - zfar);
  1313. result.m[8] = result.m[9] = result.m[11] = 0;
  1314. result.m[12] = (left + right) / (left - right);
  1315. result.m[13] = (top + bottom) / (bottom - top);
  1316. result.m[14] = znear / (znear - zfar);
  1317. result.m[15] = 1.0;
  1318. };
  1319. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1320. var matrix = Matrix.Zero();
  1321. matrix.m[0] = (2.0 * znear) / width;
  1322. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1323. matrix.m[5] = (2.0 * znear) / height;
  1324. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1325. matrix.m[10] = -zfar / (znear - zfar);
  1326. matrix.m[8] = matrix.m[9] = 0.0;
  1327. matrix.m[11] = 1.0;
  1328. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1329. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1330. return matrix;
  1331. };
  1332. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1333. var matrix = Matrix.Zero();
  1334. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1335. return matrix;
  1336. };
  1337. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1338. var tan = 1.0 / (Math.tan(fov * 0.5));
  1339. result.m[0] = tan / aspect;
  1340. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1341. result.m[5] = tan;
  1342. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1343. result.m[8] = result.m[9] = 0.0;
  1344. result.m[10] = -zfar / (znear - zfar);
  1345. result.m[11] = 1.0;
  1346. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1347. result.m[14] = (znear * zfar) / (znear - zfar);
  1348. };
  1349. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1350. var cw = viewport.width;
  1351. var ch = viewport.height;
  1352. var cx = viewport.x;
  1353. var cy = viewport.y;
  1354. 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);
  1355. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1356. };
  1357. Matrix.Transpose = function (matrix) {
  1358. var result = new Matrix();
  1359. result.m[0] = matrix.m[0];
  1360. result.m[1] = matrix.m[4];
  1361. result.m[2] = matrix.m[8];
  1362. result.m[3] = matrix.m[12];
  1363. result.m[4] = matrix.m[1];
  1364. result.m[5] = matrix.m[5];
  1365. result.m[6] = matrix.m[9];
  1366. result.m[7] = matrix.m[13];
  1367. result.m[8] = matrix.m[2];
  1368. result.m[9] = matrix.m[6];
  1369. result.m[10] = matrix.m[10];
  1370. result.m[11] = matrix.m[14];
  1371. result.m[12] = matrix.m[3];
  1372. result.m[13] = matrix.m[7];
  1373. result.m[14] = matrix.m[11];
  1374. result.m[15] = matrix.m[15];
  1375. return result;
  1376. };
  1377. Matrix.Reflection = function (plane) {
  1378. var matrix = new Matrix();
  1379. Matrix.ReflectionToRef(plane, matrix);
  1380. return matrix;
  1381. };
  1382. Matrix.ReflectionToRef = function (plane, result) {
  1383. plane.normalize();
  1384. var x = plane.normal.x;
  1385. var y = plane.normal.y;
  1386. var z = plane.normal.z;
  1387. var temp = -2 * x;
  1388. var temp2 = -2 * y;
  1389. var temp3 = -2 * z;
  1390. result.m[0] = (temp * x) + 1;
  1391. result.m[1] = temp2 * x;
  1392. result.m[2] = temp3 * x;
  1393. result.m[3] = 0.0;
  1394. result.m[4] = temp * y;
  1395. result.m[5] = (temp2 * y) + 1;
  1396. result.m[6] = temp3 * y;
  1397. result.m[7] = 0.0;
  1398. result.m[8] = temp * z;
  1399. result.m[9] = temp2 * z;
  1400. result.m[10] = (temp3 * z) + 1;
  1401. result.m[11] = 0.0;
  1402. result.m[12] = temp * plane.d;
  1403. result.m[13] = temp2 * plane.d;
  1404. result.m[14] = temp3 * plane.d;
  1405. result.m[15] = 1.0;
  1406. };
  1407. Matrix._tempQuaternion = new Quaternion();
  1408. Matrix._xAxis = Vector3.Zero();
  1409. Matrix._yAxis = Vector3.Zero();
  1410. Matrix._zAxis = Vector3.Zero();
  1411. return Matrix;
  1412. })();
  1413. BABYLON.Matrix = Matrix;
  1414. var Plane = (function () {
  1415. function Plane(a, b, c, d) {
  1416. this.normal = new Vector3(a, b, c);
  1417. this.d = d;
  1418. }
  1419. Plane.prototype.asArray = function () {
  1420. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1421. };
  1422. Plane.prototype.clone = function () {
  1423. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1424. };
  1425. Plane.prototype.normalize = function () {
  1426. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1427. var magnitude = 0;
  1428. if (norm != 0) {
  1429. magnitude = 1.0 / norm;
  1430. }
  1431. this.normal.x *= magnitude;
  1432. this.normal.y *= magnitude;
  1433. this.normal.z *= magnitude;
  1434. this.d *= magnitude;
  1435. };
  1436. Plane.prototype.transform = function (transformation) {
  1437. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1438. var x = this.normal.x;
  1439. var y = this.normal.y;
  1440. var z = this.normal.z;
  1441. var d = this.d;
  1442. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1443. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1444. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1445. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1446. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1447. };
  1448. Plane.prototype.dotCoordinate = function (point) {
  1449. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1450. };
  1451. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1452. var x1 = point2.x - point1.x;
  1453. var y1 = point2.y - point1.y;
  1454. var z1 = point2.z - point1.z;
  1455. var x2 = point3.x - point1.x;
  1456. var y2 = point3.y - point1.y;
  1457. var z2 = point3.z - point1.z;
  1458. var yz = (y1 * z2) - (z1 * y2);
  1459. var xz = (z1 * x2) - (x1 * z2);
  1460. var xy = (x1 * y2) - (y1 * x2);
  1461. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1462. var invPyth;
  1463. if (pyth != 0) {
  1464. invPyth = 1.0 / pyth;
  1465. } else {
  1466. invPyth = 0;
  1467. }
  1468. this.normal.x = yz * invPyth;
  1469. this.normal.y = xz * invPyth;
  1470. this.normal.z = xy * invPyth;
  1471. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1472. };
  1473. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1474. var dot = Vector3.Dot(this.normal, direction);
  1475. return (dot <= epsilon);
  1476. };
  1477. Plane.prototype.signedDistanceTo = function (point) {
  1478. return Vector3.Dot(point, this.normal) + this.d;
  1479. };
  1480. Plane.FromArray = function (array) {
  1481. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1482. };
  1483. Plane.FromPoints = function (point1, point2, point3) {
  1484. var result = new BABYLON.Plane(0, 0, 0, 0);
  1485. result.copyFromPoints(point1, point2, point3);
  1486. return result;
  1487. };
  1488. Plane.FromPositionAndNormal = function (origin, normal) {
  1489. var result = new BABYLON.Plane(0, 0, 0, 0);
  1490. normal.normalize();
  1491. result.normal = normal;
  1492. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1493. return result;
  1494. };
  1495. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1496. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1497. return Vector3.Dot(point, normal) + d;
  1498. };
  1499. return Plane;
  1500. })();
  1501. BABYLON.Plane = Plane;
  1502. var Viewport = (function () {
  1503. function Viewport(x, y, width, height) {
  1504. this.x = x;
  1505. this.y = y;
  1506. this.width = width;
  1507. this.height = height;
  1508. }
  1509. Viewport.prototype.toGlobal = function (engine) {
  1510. var width = engine.getRenderWidth();
  1511. var height = engine.getRenderHeight();
  1512. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1513. };
  1514. return Viewport;
  1515. })();
  1516. BABYLON.Viewport = Viewport;
  1517. var Frustum = (function () {
  1518. function Frustum() {
  1519. }
  1520. Frustum.GetPlanes = function (transform) {
  1521. var frustumPlanes = [];
  1522. for (var index = 0; index < 6; index++) {
  1523. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1524. }
  1525. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1526. return frustumPlanes;
  1527. };
  1528. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1529. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1530. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1531. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1532. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1533. frustumPlanes[0].normalize();
  1534. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1535. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1536. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1537. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1538. frustumPlanes[1].normalize();
  1539. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1540. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1541. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1542. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1543. frustumPlanes[2].normalize();
  1544. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1545. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1546. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1547. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1548. frustumPlanes[3].normalize();
  1549. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1550. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1551. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1552. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1553. frustumPlanes[4].normalize();
  1554. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1555. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1556. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1557. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1558. frustumPlanes[5].normalize();
  1559. };
  1560. return Frustum;
  1561. })();
  1562. BABYLON.Frustum = Frustum;
  1563. var Ray = (function () {
  1564. function Ray(origin, direction) {
  1565. this.origin = origin;
  1566. this.direction = direction;
  1567. }
  1568. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1569. var d = 0.0;
  1570. var maxValue = Number.MAX_VALUE;
  1571. if (Math.abs(this.direction.x) < 0.0000001) {
  1572. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1573. return false;
  1574. }
  1575. } else {
  1576. var inv = 1.0 / this.direction.x;
  1577. var min = (minimum.x - this.origin.x) * inv;
  1578. var max = (maximum.x - this.origin.x) * inv;
  1579. if (min > max) {
  1580. var temp = min;
  1581. min = max;
  1582. max = temp;
  1583. }
  1584. d = Math.max(min, d);
  1585. maxValue = Math.min(max, maxValue);
  1586. if (d > maxValue) {
  1587. return false;
  1588. }
  1589. }
  1590. if (Math.abs(this.direction.y) < 0.0000001) {
  1591. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1592. return false;
  1593. }
  1594. } else {
  1595. inv = 1.0 / this.direction.y;
  1596. min = (minimum.y - this.origin.y) * inv;
  1597. max = (maximum.y - this.origin.y) * inv;
  1598. if (min > max) {
  1599. temp = min;
  1600. min = max;
  1601. max = temp;
  1602. }
  1603. d = Math.max(min, d);
  1604. maxValue = Math.min(max, maxValue);
  1605. if (d > maxValue) {
  1606. return false;
  1607. }
  1608. }
  1609. if (Math.abs(this.direction.z) < 0.0000001) {
  1610. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1611. return false;
  1612. }
  1613. } else {
  1614. inv = 1.0 / this.direction.z;
  1615. min = (minimum.z - this.origin.z) * inv;
  1616. max = (maximum.z - this.origin.z) * inv;
  1617. if (min > max) {
  1618. temp = min;
  1619. min = max;
  1620. max = temp;
  1621. }
  1622. d = Math.max(min, d);
  1623. maxValue = Math.min(max, maxValue);
  1624. if (d > maxValue) {
  1625. return false;
  1626. }
  1627. }
  1628. return true;
  1629. };
  1630. Ray.prototype.intersectsBox = function (box) {
  1631. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1632. };
  1633. Ray.prototype.intersectsSphere = function (sphere) {
  1634. var x = sphere.center.x - this.origin.x;
  1635. var y = sphere.center.y - this.origin.y;
  1636. var z = sphere.center.z - this.origin.z;
  1637. var pyth = (x * x) + (y * y) + (z * z);
  1638. var rr = sphere.radius * sphere.radius;
  1639. if (pyth <= rr) {
  1640. return true;
  1641. }
  1642. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1643. if (dot < 0.0) {
  1644. return false;
  1645. }
  1646. var temp = pyth - (dot * dot);
  1647. return temp <= rr;
  1648. };
  1649. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1650. if (!this._edge1) {
  1651. this._edge1 = BABYLON.Vector3.Zero();
  1652. this._edge2 = BABYLON.Vector3.Zero();
  1653. this._pvec = BABYLON.Vector3.Zero();
  1654. this._tvec = BABYLON.Vector3.Zero();
  1655. this._qvec = BABYLON.Vector3.Zero();
  1656. }
  1657. vertex1.subtractToRef(vertex0, this._edge1);
  1658. vertex2.subtractToRef(vertex0, this._edge2);
  1659. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1660. var det = Vector3.Dot(this._edge1, this._pvec);
  1661. if (det === 0) {
  1662. return null;
  1663. }
  1664. var invdet = 1 / det;
  1665. this.origin.subtractToRef(vertex0, this._tvec);
  1666. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1667. if (bu < 0 || bu > 1.0) {
  1668. return null;
  1669. }
  1670. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1671. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1672. if (bv < 0 || bu + bv > 1.0) {
  1673. return null;
  1674. }
  1675. return new BABYLON.IntersectionInfo(bu, bv, Vector3.Dot(this._edge2, this._qvec) * invdet);
  1676. };
  1677. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1678. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1679. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1680. var direction = end.subtract(start);
  1681. direction.normalize();
  1682. return new Ray(start, direction);
  1683. };
  1684. Ray.Transform = function (ray, matrix) {
  1685. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1686. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1687. return new Ray(newOrigin, newDirection);
  1688. };
  1689. return Ray;
  1690. })();
  1691. BABYLON.Ray = Ray;
  1692. (function (Space) {
  1693. Space[Space["LOCAL"] = 0] = "LOCAL";
  1694. Space[Space["WORLD"] = 1] = "WORLD";
  1695. })(BABYLON.Space || (BABYLON.Space = {}));
  1696. var Space = BABYLON.Space;
  1697. var Axis = (function () {
  1698. function Axis() {
  1699. }
  1700. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1701. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1702. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1703. return Axis;
  1704. })();
  1705. BABYLON.Axis = Axis;
  1706. ;
  1707. })(BABYLON || (BABYLON = {}));
  1708. var BABYLON;
  1709. (function (BABYLON) {
  1710. var Database = (function () {
  1711. function Database(urlToScene, callbackManifestChecked) {
  1712. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  1713. this.callbackManifestChecked = callbackManifestChecked;
  1714. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  1715. this.db = null;
  1716. this.enableSceneOffline = false;
  1717. this.enableTexturesOffline = false;
  1718. this.manifestVersionFound = 0;
  1719. this.mustUpdateRessources = false;
  1720. this.hasReachedQuota = false;
  1721. this.checkManifestFile();
  1722. }
  1723. Database.prototype.checkManifestFile = function () {
  1724. var _this = this;
  1725. function noManifestFile() {
  1726. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  1727. that.enableSceneOffline = false;
  1728. that.enableTexturesOffline = false;
  1729. that.callbackManifestChecked(false);
  1730. }
  1731. var that = this;
  1732. var manifestURL = this.currentSceneUrl + ".manifest";
  1733. var xhr = new XMLHttpRequest();
  1734. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  1735. xhr.open("GET", manifestURLTimeStamped, true);
  1736. xhr.addEventListener("load", function () {
  1737. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  1738. try {
  1739. var manifestFile = JSON.parse(xhr.response);
  1740. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  1741. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  1742. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  1743. _this.manifestVersionFound = manifestFile.version;
  1744. }
  1745. if (_this.callbackManifestChecked) {
  1746. _this.callbackManifestChecked(true);
  1747. }
  1748. } catch (ex) {
  1749. noManifestFile();
  1750. }
  1751. } else {
  1752. noManifestFile();
  1753. }
  1754. }, false);
  1755. xhr.addEventListener("error", function (event) {
  1756. noManifestFile();
  1757. }, false);
  1758. try {
  1759. xhr.send();
  1760. } catch (ex) {
  1761. BABYLON.Tools.Error("Error on XHR send request.");
  1762. that.callbackManifestChecked(false);
  1763. }
  1764. };
  1765. Database.prototype.openAsync = function (successCallback, errorCallback) {
  1766. var _this = this;
  1767. function handleError() {
  1768. that.isSupported = false;
  1769. if (errorCallback)
  1770. errorCallback();
  1771. }
  1772. var that = this;
  1773. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  1774. this.isSupported = false;
  1775. if (errorCallback)
  1776. errorCallback();
  1777. } else {
  1778. if (!this.db) {
  1779. this.hasReachedQuota = false;
  1780. this.isSupported = true;
  1781. var request = this.idbFactory.open("babylonjs", 1);
  1782. request.onerror = function (event) {
  1783. handleError();
  1784. };
  1785. request.onblocked = function (event) {
  1786. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  1787. handleError();
  1788. };
  1789. request.onsuccess = function (event) {
  1790. _this.db = request.result;
  1791. successCallback();
  1792. };
  1793. request.onupgradeneeded = function (event) {
  1794. _this.db = (event.target).result;
  1795. try {
  1796. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  1797. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  1798. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  1799. } catch (ex) {
  1800. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  1801. handleError();
  1802. }
  1803. };
  1804. } else {
  1805. if (successCallback)
  1806. successCallback();
  1807. }
  1808. }
  1809. };
  1810. Database.prototype.loadImageFromDB = function (url, image) {
  1811. var _this = this;
  1812. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  1813. var saveAndLoadImage = function () {
  1814. if (!_this.hasReachedQuota && _this.db !== null) {
  1815. _this._saveImageIntoDBAsync(completeURL, image);
  1816. } else {
  1817. image.src = url;
  1818. }
  1819. };
  1820. if (!this.mustUpdateRessources) {
  1821. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  1822. } else {
  1823. saveAndLoadImage();
  1824. }
  1825. };
  1826. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  1827. if (this.isSupported && this.db !== null) {
  1828. var texture;
  1829. var transaction = this.db.transaction(["textures"]);
  1830. transaction.onabort = function (event) {
  1831. image.src = url;
  1832. };
  1833. transaction.oncomplete = function (event) {
  1834. var blobTextureURL;
  1835. if (texture) {
  1836. var URL = window.URL || window.webkitURL;
  1837. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  1838. image.onerror = function () {
  1839. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  1840. image.src = url;
  1841. };
  1842. image.src = blobTextureURL;
  1843. } else {
  1844. notInDBCallback();
  1845. }
  1846. };
  1847. var getRequest = transaction.objectStore("textures").get(url);
  1848. getRequest.onsuccess = function (event) {
  1849. texture = (event.target).result;
  1850. };
  1851. getRequest.onerror = function (event) {
  1852. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  1853. image.src = url;
  1854. };
  1855. } else {
  1856. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  1857. image.src = url;
  1858. }
  1859. };
  1860. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  1861. var _this = this;
  1862. if (this.isSupported) {
  1863. var generateBlobUrl = function () {
  1864. var blobTextureURL;
  1865. if (blob) {
  1866. var URL = window.URL || window.webkitURL;
  1867. try {
  1868. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  1869. } catch (ex) {
  1870. blobTextureURL = URL.createObjectURL(blob);
  1871. }
  1872. }
  1873. image.src = blobTextureURL;
  1874. };
  1875. if (BABYLON.Database.isUASupportingBlobStorage) {
  1876. var xhr = new XMLHttpRequest(), blob;
  1877. xhr.open("GET", url, true);
  1878. xhr.responseType = "blob";
  1879. xhr.addEventListener("load", function () {
  1880. if (xhr.status === 200) {
  1881. blob = xhr.response;
  1882. var transaction = _this.db.transaction(["textures"], "readwrite");
  1883. transaction.onabort = function (event) {
  1884. try {
  1885. if (event.srcElement.error.name === "QuotaExceededError") {
  1886. this.hasReachedQuota = true;
  1887. }
  1888. } catch (ex) {
  1889. }
  1890. generateBlobUrl();
  1891. };
  1892. transaction.oncomplete = function (event) {
  1893. generateBlobUrl();
  1894. };
  1895. var newTexture = { textureUrl: url, data: blob };
  1896. try {
  1897. var addRequest = transaction.objectStore("textures").put(newTexture);
  1898. addRequest.onsuccess = function (event) {
  1899. };
  1900. addRequest.onerror = function (event) {
  1901. generateBlobUrl();
  1902. };
  1903. } catch (ex) {
  1904. if (ex.code === 25) {
  1905. BABYLON.Database.isUASupportingBlobStorage = false;
  1906. }
  1907. image.src = url;
  1908. }
  1909. } else {
  1910. image.src = url;
  1911. }
  1912. }, false);
  1913. xhr.addEventListener("error", function (event) {
  1914. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  1915. image.src = url;
  1916. }, false);
  1917. xhr.send();
  1918. } else {
  1919. image.src = url;
  1920. }
  1921. } else {
  1922. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  1923. image.src = url;
  1924. }
  1925. };
  1926. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  1927. var _this = this;
  1928. var updateVersion = function (event) {
  1929. _this._saveVersionIntoDBAsync(url, versionLoaded);
  1930. };
  1931. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  1932. };
  1933. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  1934. var _this = this;
  1935. if (this.isSupported) {
  1936. var version;
  1937. try {
  1938. var transaction = this.db.transaction(["versions"]);
  1939. transaction.oncomplete = function (event) {
  1940. if (version) {
  1941. if (_this.manifestVersionFound > version.data) {
  1942. _this.mustUpdateRessources = true;
  1943. updateInDBCallback();
  1944. } else {
  1945. callback(version.data);
  1946. }
  1947. } else {
  1948. _this.mustUpdateRessources = true;
  1949. updateInDBCallback();
  1950. }
  1951. };
  1952. transaction.onabort = function (event) {
  1953. callback(-1);
  1954. };
  1955. var getRequest = transaction.objectStore("versions").get(url);
  1956. getRequest.onsuccess = function (event) {
  1957. version = (event.target).result;
  1958. };
  1959. getRequest.onerror = function (event) {
  1960. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  1961. callback(-1);
  1962. };
  1963. } catch (ex) {
  1964. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  1965. callback(-1);
  1966. }
  1967. } else {
  1968. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  1969. callback(-1);
  1970. }
  1971. };
  1972. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  1973. var _this = this;
  1974. if (this.isSupported && !this.hasReachedQuota) {
  1975. try {
  1976. var transaction = this.db.transaction(["versions"], "readwrite");
  1977. transaction.onabort = function (event) {
  1978. try {
  1979. if (event.srcElement.error.name === "QuotaExceededError") {
  1980. _this.hasReachedQuota = true;
  1981. }
  1982. } catch (ex) {
  1983. }
  1984. callback(-1);
  1985. };
  1986. transaction.oncomplete = function (event) {
  1987. callback(_this.manifestVersionFound);
  1988. };
  1989. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  1990. var addRequest = transaction.objectStore("versions").put(newVersion);
  1991. addRequest.onsuccess = function (event) {
  1992. };
  1993. addRequest.onerror = function (event) {
  1994. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  1995. };
  1996. } catch (ex) {
  1997. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  1998. callback(-1);
  1999. }
  2000. } else {
  2001. callback(-1);
  2002. }
  2003. };
  2004. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  2005. var _this = this;
  2006. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  2007. var saveAndLoadFile = function (event) {
  2008. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  2009. };
  2010. this._checkVersionFromDB(completeUrl, function (version) {
  2011. if (version !== -1) {
  2012. if (!_this.mustUpdateRessources) {
  2013. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  2014. } else {
  2015. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  2016. }
  2017. } else {
  2018. errorCallback();
  2019. }
  2020. });
  2021. };
  2022. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  2023. if (this.isSupported) {
  2024. var targetStore;
  2025. if (url.indexOf(".babylon") !== -1) {
  2026. targetStore = "scenes";
  2027. } else {
  2028. targetStore = "textures";
  2029. }
  2030. var file;
  2031. var transaction = this.db.transaction([targetStore]);
  2032. transaction.oncomplete = function (event) {
  2033. if (file) {
  2034. callback(file.data);
  2035. } else {
  2036. notInDBCallback();
  2037. }
  2038. };
  2039. transaction.onabort = function (event) {
  2040. notInDBCallback();
  2041. };
  2042. var getRequest = transaction.objectStore(targetStore).get(url);
  2043. getRequest.onsuccess = function (event) {
  2044. file = (event.target).result;
  2045. };
  2046. getRequest.onerror = function (event) {
  2047. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  2048. notInDBCallback();
  2049. };
  2050. } else {
  2051. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  2052. callback();
  2053. }
  2054. };
  2055. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  2056. var _this = this;
  2057. if (this.isSupported) {
  2058. var targetStore;
  2059. if (url.indexOf(".babylon") !== -1) {
  2060. targetStore = "scenes";
  2061. } else {
  2062. targetStore = "textures";
  2063. }
  2064. var xhr = new XMLHttpRequest(), fileData;
  2065. xhr.open("GET", url, true);
  2066. if (useArrayBuffer) {
  2067. xhr.responseType = "arraybuffer";
  2068. }
  2069. xhr.onprogress = progressCallback;
  2070. xhr.addEventListener("load", function () {
  2071. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  2072. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  2073. if (!_this.hasReachedQuota) {
  2074. var transaction = _this.db.transaction([targetStore], "readwrite");
  2075. transaction.onabort = function (event) {
  2076. try {
  2077. if (event.srcElement.error.name === "QuotaExceededError") {
  2078. this.hasReachedQuota = true;
  2079. }
  2080. } catch (ex) {
  2081. }
  2082. callback(fileData);
  2083. };
  2084. transaction.oncomplete = function (event) {
  2085. callback(fileData);
  2086. };
  2087. var newFile;
  2088. if (targetStore === "scenes") {
  2089. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  2090. } else {
  2091. newFile = { textureUrl: url, data: fileData };
  2092. }
  2093. try {
  2094. var addRequest = transaction.objectStore(targetStore).put(newFile);
  2095. addRequest.onsuccess = function (event) {
  2096. };
  2097. addRequest.onerror = function (event) {
  2098. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  2099. };
  2100. } catch (ex) {
  2101. callback(fileData);
  2102. }
  2103. } else {
  2104. callback(fileData);
  2105. }
  2106. } else {
  2107. callback();
  2108. }
  2109. }, false);
  2110. xhr.addEventListener("error", function (event) {
  2111. BABYLON.Tools.Error("error on XHR request.");
  2112. callback();
  2113. }, false);
  2114. xhr.send();
  2115. } else {
  2116. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  2117. callback();
  2118. }
  2119. };
  2120. Database.isUASupportingBlobStorage = true;
  2121. Database.parseURL = function (url) {
  2122. var a = document.createElement('a');
  2123. a.href = url;
  2124. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  2125. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  2126. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  2127. return absLocation;
  2128. };
  2129. Database.ReturnFullUrlLocation = function (url) {
  2130. if (url.indexOf("http:/") === -1) {
  2131. return (BABYLON.Database.parseURL(window.location.href) + url);
  2132. } else {
  2133. return url;
  2134. }
  2135. };
  2136. return Database;
  2137. })();
  2138. BABYLON.Database = Database;
  2139. })(BABYLON || (BABYLON = {}));
  2140. /**
  2141. * Based on jsTGALoader - Javascript loader for TGA file
  2142. * By Vincent Thibault
  2143. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  2144. */
  2145. var BABYLON;
  2146. (function (BABYLON) {
  2147. (function (Internals) {
  2148. var TGATools = (function () {
  2149. function TGATools() {
  2150. }
  2151. TGATools.GetTGAHeader = function (data) {
  2152. var offset = 0;
  2153. var header = {
  2154. id_length: data[offset++],
  2155. colormap_type: data[offset++],
  2156. image_type: data[offset++],
  2157. colormap_index: data[offset++] | data[offset++] << 8,
  2158. colormap_length: data[offset++] | data[offset++] << 8,
  2159. colormap_size: data[offset++],
  2160. origin: [
  2161. data[offset++] | data[offset++] << 8,
  2162. data[offset++] | data[offset++] << 8
  2163. ],
  2164. width: data[offset++] | data[offset++] << 8,
  2165. height: data[offset++] | data[offset++] << 8,
  2166. pixel_size: data[offset++],
  2167. flags: data[offset++]
  2168. };
  2169. return header;
  2170. };
  2171. TGATools.UploadContent = function (gl, data) {
  2172. if (data.length < 19) {
  2173. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  2174. return;
  2175. }
  2176. var offset = 18;
  2177. var header = TGATools.GetTGAHeader(data);
  2178. if (header.id_length + offset > data.length) {
  2179. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  2180. return;
  2181. }
  2182. offset += header.id_length;
  2183. var use_rle = false;
  2184. var use_pal = false;
  2185. var use_rgb = false;
  2186. var use_grey = false;
  2187. switch (header.image_type) {
  2188. case TGATools._TYPE_RLE_INDEXED:
  2189. use_rle = true;
  2190. case TGATools._TYPE_INDEXED:
  2191. use_pal = true;
  2192. break;
  2193. case TGATools._TYPE_RLE_RGB:
  2194. use_rle = true;
  2195. case TGATools._TYPE_RGB:
  2196. use_rgb = true;
  2197. break;
  2198. case TGATools._TYPE_RLE_GREY:
  2199. use_rle = true;
  2200. case TGATools._TYPE_GREY:
  2201. use_grey = true;
  2202. break;
  2203. }
  2204. var pixel_data;
  2205. var numAlphaBits = header.flags & 0xf;
  2206. var pixel_size = header.pixel_size >> 3;
  2207. var pixel_total = header.width * header.height * pixel_size;
  2208. var palettes;
  2209. if (use_pal) {
  2210. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  2211. }
  2212. if (use_rle) {
  2213. pixel_data = new Uint8Array(pixel_total);
  2214. var c, count, i;
  2215. var localOffset = 0;
  2216. var pixels = new Uint8Array(pixel_size);
  2217. while (offset < pixel_total && localOffset < pixel_total) {
  2218. c = data[offset++];
  2219. count = (c & 0x7f) + 1;
  2220. if (c & 0x80) {
  2221. for (i = 0; i < pixel_size; ++i) {
  2222. pixels[i] = data[offset++];
  2223. }
  2224. for (i = 0; i < count; ++i) {
  2225. pixel_data.set(pixels, localOffset + i * pixel_size);
  2226. }
  2227. localOffset += pixel_size * count;
  2228. } else {
  2229. count *= pixel_size;
  2230. for (i = 0; i < count; ++i) {
  2231. pixel_data[localOffset + i] = data[offset++];
  2232. }
  2233. localOffset += count;
  2234. }
  2235. }
  2236. } else {
  2237. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  2238. }
  2239. var x_start, y_start, x_step, y_step, y_end, x_end;
  2240. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  2241. default:
  2242. case TGATools._ORIGIN_UL:
  2243. x_start = 0;
  2244. x_step = 1;
  2245. x_end = header.width;
  2246. y_start = 0;
  2247. y_step = 1;
  2248. y_end = header.height;
  2249. break;
  2250. case TGATools._ORIGIN_BL:
  2251. x_start = 0;
  2252. x_step = 1;
  2253. x_end = header.width;
  2254. y_start = header.height - 1;
  2255. y_step = -1;
  2256. y_end = -1;
  2257. break;
  2258. case TGATools._ORIGIN_UR:
  2259. x_start = header.width - 1;
  2260. x_step = -1;
  2261. x_end = -1;
  2262. y_start = 0;
  2263. y_step = 1;
  2264. y_end = header.height;
  2265. break;
  2266. case TGATools._ORIGIN_BR:
  2267. x_start = header.width - 1;
  2268. x_step = -1;
  2269. x_end = -1;
  2270. y_start = header.height - 1;
  2271. y_step = -1;
  2272. y_end = -1;
  2273. break;
  2274. }
  2275. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  2276. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  2277. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  2278. };
  2279. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  2280. var image = pixel_data, colormap = palettes;
  2281. var width = header.width, height = header.height;
  2282. var color, i = 0, x, y;
  2283. var imageData = new Uint8Array(width * height * 4);
  2284. for (y = y_start; y !== y_end; y += y_step) {
  2285. for (x = x_start; x !== x_end; x += x_step, i++) {
  2286. color = image[i];
  2287. imageData[(x + width * y) * 4 + 3] = 255;
  2288. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  2289. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  2290. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  2291. }
  2292. }
  2293. return imageData;
  2294. };
  2295. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  2296. var image = pixel_data;
  2297. var width = header.width, height = header.height;
  2298. var color, i = 0, x, y;
  2299. var imageData = new Uint8Array(width * height * 4);
  2300. for (y = y_start; y !== y_end; y += y_step) {
  2301. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  2302. color = image[i + 0] + (image[i + 1] << 8);
  2303. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  2304. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  2305. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  2306. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  2307. }
  2308. }
  2309. return imageData;
  2310. };
  2311. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  2312. var image = pixel_data;
  2313. var width = header.width, height = header.height;
  2314. var i = 0, x, y;
  2315. var imageData = new Uint8Array(width * height * 4);
  2316. for (y = y_start; y !== y_end; y += y_step) {
  2317. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  2318. imageData[(x + width * y) * 4 + 3] = 255;
  2319. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  2320. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  2321. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  2322. }
  2323. }
  2324. return imageData;
  2325. };
  2326. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  2327. var image = pixel_data;
  2328. var width = header.width, height = header.height;
  2329. var i = 0, x, y;
  2330. var imageData = new Uint8Array(width * height * 4);
  2331. for (y = y_start; y !== y_end; y += y_step) {
  2332. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  2333. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  2334. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  2335. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  2336. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  2337. }
  2338. }
  2339. return imageData;
  2340. };
  2341. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  2342. var image = pixel_data;
  2343. var width = header.width, height = header.height;
  2344. var color, i = 0, x, y;
  2345. var imageData = new Uint8Array(width * height * 4);
  2346. for (y = y_start; y !== y_end; y += y_step) {
  2347. for (x = x_start; x !== x_end; x += x_step, i++) {
  2348. color = image[i];
  2349. imageData[(x + width * y) * 4 + 0] = color;
  2350. imageData[(x + width * y) * 4 + 1] = color;
  2351. imageData[(x + width * y) * 4 + 2] = color;
  2352. imageData[(x + width * y) * 4 + 3] = 255;
  2353. }
  2354. }
  2355. return imageData;
  2356. };
  2357. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  2358. var image = pixel_data;
  2359. var width = header.width, height = header.height;
  2360. var i = 0, x, y;
  2361. var imageData = new Uint8Array(width * height * 4);
  2362. for (y = y_start; y !== y_end; y += y_step) {
  2363. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  2364. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  2365. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  2366. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  2367. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  2368. }
  2369. }
  2370. return imageData;
  2371. };
  2372. TGATools._TYPE_NO_DATA = 0;
  2373. TGATools._TYPE_INDEXED = 1;
  2374. TGATools._TYPE_RGB = 2;
  2375. TGATools._TYPE_GREY = 3;
  2376. TGATools._TYPE_RLE_INDEXED = 9;
  2377. TGATools._TYPE_RLE_RGB = 10;
  2378. TGATools._TYPE_RLE_GREY = 11;
  2379. TGATools._ORIGIN_MASK = 0x30;
  2380. TGATools._ORIGIN_SHIFT = 0x04;
  2381. TGATools._ORIGIN_BL = 0x00;
  2382. TGATools._ORIGIN_BR = 0x01;
  2383. TGATools._ORIGIN_UL = 0x02;
  2384. TGATools._ORIGIN_UR = 0x03;
  2385. return TGATools;
  2386. })();
  2387. Internals.TGATools = TGATools;
  2388. })(BABYLON.Internals || (BABYLON.Internals = {}));
  2389. var Internals = BABYLON.Internals;
  2390. })(BABYLON || (BABYLON = {}));
  2391. var BABYLON;
  2392. (function (BABYLON) {
  2393. (function (Internals) {
  2394. var DDS_MAGIC = 0x20534444;
  2395. 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;
  2396. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  2397. 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;
  2398. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  2399. function FourCCToInt32(value) {
  2400. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  2401. }
  2402. function Int32ToFourCC(value) {
  2403. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  2404. }
  2405. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  2406. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  2407. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  2408. var headerLengthInt = 31;
  2409. var off_magic = 0;
  2410. var off_size = 1;
  2411. var off_flags = 2;
  2412. var off_height = 3;
  2413. var off_width = 4;
  2414. var off_mipmapCount = 7;
  2415. var off_pfFlags = 20;
  2416. var off_pfFourCC = 21;
  2417. var off_RGBbpp = 22;
  2418. var off_RMask = 23;
  2419. var off_GMask = 24;
  2420. var off_BMask = 25;
  2421. var off_AMask = 26;
  2422. var off_caps1 = 27;
  2423. var off_caps2 = 28;
  2424. ;
  2425. var DDSTools = (function () {
  2426. function DDSTools() {
  2427. }
  2428. DDSTools.GetDDSInfo = function (arrayBuffer) {
  2429. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  2430. var mipmapCount = 1;
  2431. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  2432. mipmapCount = Math.max(1, header[off_mipmapCount]);
  2433. }
  2434. return {
  2435. width: header[off_width],
  2436. height: header[off_height],
  2437. mipmapCount: mipmapCount,
  2438. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  2439. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  2440. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  2441. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  2442. };
  2443. };
  2444. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  2445. var byteArray = new Uint8Array(dataLength);
  2446. var srcData = new Uint8Array(arrayBuffer);
  2447. var index = 0;
  2448. for (var y = height - 1; y >= 0; y--) {
  2449. for (var x = 0; x < width; x++) {
  2450. var srcPos = dataOffset + (x + y * width) * 4;
  2451. byteArray[index + 2] = srcData[srcPos];
  2452. byteArray[index + 1] = srcData[srcPos + 1];
  2453. byteArray[index] = srcData[srcPos + 2];
  2454. byteArray[index + 3] = srcData[srcPos + 3];
  2455. index += 4;
  2456. }
  2457. }
  2458. return byteArray;
  2459. };
  2460. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  2461. var byteArray = new Uint8Array(dataLength);
  2462. var srcData = new Uint8Array(arrayBuffer);
  2463. var index = 0;
  2464. for (var y = height - 1; y >= 0; y--) {
  2465. for (var x = 0; x < width; x++) {
  2466. var srcPos = dataOffset + (x + y * width) * 3;
  2467. byteArray[index + 2] = srcData[srcPos];
  2468. byteArray[index + 1] = srcData[srcPos + 1];
  2469. byteArray[index] = srcData[srcPos + 2];
  2470. index += 3;
  2471. }
  2472. }
  2473. return byteArray;
  2474. };
  2475. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  2476. var byteArray = new Uint8Array(dataLength);
  2477. var srcData = new Uint8Array(arrayBuffer);
  2478. var index = 0;
  2479. for (var y = height - 1; y >= 0; y--) {
  2480. for (var x = 0; x < width; x++) {
  2481. var srcPos = dataOffset + (x + y * width);
  2482. byteArray[index] = srcData[srcPos];
  2483. index++;
  2484. }
  2485. }
  2486. return byteArray;
  2487. };
  2488. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  2489. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  2490. if (header[off_magic] != DDS_MAGIC) {
  2491. BABYLON.Tools.Error("Invalid magic number in DDS header");
  2492. return;
  2493. }
  2494. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  2495. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  2496. return;
  2497. }
  2498. if (info.isFourCC) {
  2499. fourCC = header[off_pfFourCC];
  2500. switch (fourCC) {
  2501. case FOURCC_DXT1:
  2502. blockBytes = 8;
  2503. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  2504. break;
  2505. case FOURCC_DXT3:
  2506. blockBytes = 16;
  2507. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  2508. break;
  2509. case FOURCC_DXT5:
  2510. blockBytes = 16;
  2511. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  2512. break;
  2513. default:
  2514. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  2515. return;
  2516. }
  2517. }
  2518. mipmapCount = 1;
  2519. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  2520. mipmapCount = Math.max(1, header[off_mipmapCount]);
  2521. }
  2522. var bpp = header[off_RGBbpp];
  2523. for (var face = 0; face < faces; face++) {
  2524. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  2525. width = header[off_width];
  2526. height = header[off_height];
  2527. dataOffset = header[off_size] + 4;
  2528. for (i = 0; i < mipmapCount; ++i) {
  2529. if (info.isRGB) {
  2530. if (bpp == 24) {
  2531. dataLength = width * height * 3;
  2532. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  2533. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  2534. } else {
  2535. dataLength = width * height * 4;
  2536. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  2537. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  2538. }
  2539. } else if (info.isLuminance) {
  2540. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  2541. var unpaddedRowSize = width;
  2542. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  2543. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  2544. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  2545. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  2546. } else {
  2547. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  2548. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  2549. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  2550. }
  2551. dataOffset += dataLength;
  2552. width *= 0.5;
  2553. height *= 0.5;
  2554. width = Math.max(1.0, width);
  2555. height = Math.max(1.0, height);
  2556. }
  2557. }
  2558. };
  2559. return DDSTools;
  2560. })();
  2561. Internals.DDSTools = DDSTools;
  2562. })(BABYLON.Internals || (BABYLON.Internals = {}));
  2563. var Internals = BABYLON.Internals;
  2564. })(BABYLON || (BABYLON = {}));
  2565. var BABYLON;
  2566. (function (BABYLON) {
  2567. var SmartArray = (function () {
  2568. function SmartArray(capacity) {
  2569. this.length = 0;
  2570. this._duplicateId = 0;
  2571. this.data = new Array(capacity);
  2572. this._id = SmartArray._GlobalId++;
  2573. }
  2574. SmartArray.prototype.push = function (value) {
  2575. this.data[this.length++] = value;
  2576. if (this.length > this.data.length) {
  2577. this.data.length *= 2;
  2578. }
  2579. if (!value.__smartArrayFlags) {
  2580. value.__smartArrayFlags = {};
  2581. }
  2582. value.__smartArrayFlags[this._id] = this._duplicateId;
  2583. };
  2584. SmartArray.prototype.pushNoDuplicate = function (value) {
  2585. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  2586. return;
  2587. }
  2588. this.push(value);
  2589. };
  2590. SmartArray.prototype.sort = function (compareFn) {
  2591. this.data.sort(compareFn);
  2592. };
  2593. SmartArray.prototype.reset = function () {
  2594. this.length = 0;
  2595. this._duplicateId++;
  2596. };
  2597. SmartArray.prototype.concat = function (array) {
  2598. if (array.length === 0) {
  2599. return;
  2600. }
  2601. if (this.length + array.length > this.data.length) {
  2602. this.data.length = (this.length + array.length) * 2;
  2603. }
  2604. for (var index = 0; index < array.length; index++) {
  2605. this.data[this.length++] = (array.data || array)[index];
  2606. }
  2607. };
  2608. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  2609. if (array.length === 0) {
  2610. return;
  2611. }
  2612. if (this.length + array.length > this.data.length) {
  2613. this.data.length = (this.length + array.length) * 2;
  2614. }
  2615. for (var index = 0; index < array.length; index++) {
  2616. var item = (array.data || array)[index];
  2617. this.pushNoDuplicate(item);
  2618. }
  2619. };
  2620. SmartArray.prototype.indexOf = function (value) {
  2621. var position = this.data.indexOf(value);
  2622. if (position >= this.length) {
  2623. return -1;
  2624. }
  2625. return position;
  2626. };
  2627. SmartArray._GlobalId = 0;
  2628. return SmartArray;
  2629. })();
  2630. BABYLON.SmartArray = SmartArray;
  2631. })(BABYLON || (BABYLON = {}));
  2632. var BABYLON;
  2633. (function (BABYLON) {
  2634. var screenshotCanvas;
  2635. var fpsRange = 60;
  2636. var previousFramesDuration = [];
  2637. var fps = 60;
  2638. var deltaTime = 0;
  2639. var cloneValue = function (source, destinationObject) {
  2640. if (!source)
  2641. return null;
  2642. if (source instanceof BABYLON.Mesh) {
  2643. return null;
  2644. }
  2645. if (source instanceof BABYLON.SubMesh) {
  2646. return source.clone(destinationObject);
  2647. } else if (source.clone) {
  2648. return source.clone();
  2649. }
  2650. return null;
  2651. };
  2652. var Tools = (function () {
  2653. function Tools() {
  2654. }
  2655. Tools.GetFilename = function (path) {
  2656. var index = path.lastIndexOf("/");
  2657. if (index < 0)
  2658. return path;
  2659. return path.substring(index + 1);
  2660. };
  2661. Tools.GetDOMTextContent = function (element) {
  2662. var result = "";
  2663. var child = element.firstChild;
  2664. while (child) {
  2665. if (child.nodeType == 3) {
  2666. result += child.textContent;
  2667. }
  2668. child = child.nextSibling;
  2669. }
  2670. return result;
  2671. };
  2672. Tools.ToDegrees = function (angle) {
  2673. return angle * 180 / Math.PI;
  2674. };
  2675. Tools.ToRadians = function (angle) {
  2676. return angle * Math.PI / 180;
  2677. };
  2678. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2679. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2680. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2681. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2682. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2683. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2684. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2685. }
  2686. return {
  2687. minimum: minimum,
  2688. maximum: maximum
  2689. };
  2690. };
  2691. Tools.ExtractMinAndMax = function (positions, start, count) {
  2692. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2693. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2694. for (var index = start; index < start + count; index++) {
  2695. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2696. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2697. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2698. }
  2699. return {
  2700. minimum: minimum,
  2701. maximum: maximum
  2702. };
  2703. };
  2704. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2705. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2706. return undefined;
  2707. return Array.isArray(obj) ? obj : [obj];
  2708. };
  2709. Tools.GetPointerPrefix = function () {
  2710. var eventPrefix = "pointer";
  2711. if (!navigator.pointerEnabled) {
  2712. eventPrefix = "mouse";
  2713. }
  2714. return eventPrefix;
  2715. };
  2716. Tools.QueueNewFrame = function (func) {
  2717. if (window.requestAnimationFrame)
  2718. window.requestAnimationFrame(func);
  2719. else if (window.msRequestAnimationFrame)
  2720. window.msRequestAnimationFrame(func);
  2721. else if (window.webkitRequestAnimationFrame)
  2722. window.webkitRequestAnimationFrame(func);
  2723. else if (window.mozRequestAnimationFrame)
  2724. window.mozRequestAnimationFrame(func);
  2725. else if (window.oRequestAnimationFrame)
  2726. window.oRequestAnimationFrame(func);
  2727. else {
  2728. window.setTimeout(func, 16);
  2729. }
  2730. };
  2731. Tools.RequestFullscreen = function (element) {
  2732. if (element.requestFullscreen)
  2733. element.requestFullscreen();
  2734. else if (element.msRequestFullscreen)
  2735. element.msRequestFullscreen();
  2736. else if (element.webkitRequestFullscreen)
  2737. element.webkitRequestFullscreen();
  2738. else if (element.mozRequestFullScreen)
  2739. element.mozRequestFullScreen();
  2740. };
  2741. Tools.ExitFullscreen = function () {
  2742. if (document.exitFullscreen) {
  2743. document.exitFullscreen();
  2744. } else if (document.mozCancelFullScreen) {
  2745. document.mozCancelFullScreen();
  2746. } else if (document.webkitCancelFullScreen) {
  2747. document.webkitCancelFullScreen();
  2748. } else if (document.msCancelFullScreen) {
  2749. document.msCancelFullScreen();
  2750. }
  2751. };
  2752. Tools.CleanUrl = function (url) {
  2753. url = url.replace(/#/mg, "%23");
  2754. return url;
  2755. };
  2756. Tools.LoadImage = function (url, onload, onerror, database) {
  2757. url = Tools.CleanUrl(url);
  2758. var img = new Image();
  2759. if (url.substr(0, 5) != "data:")
  2760. img.crossOrigin = 'anonymous';
  2761. img.onload = function () {
  2762. onload(img);
  2763. };
  2764. img.onerror = function (err) {
  2765. onerror(img, err);
  2766. };
  2767. var noIndexedDB = function () {
  2768. img.src = url;
  2769. };
  2770. var loadFromIndexedDB = function () {
  2771. database.loadImageFromDB(url, img);
  2772. };
  2773. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2774. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2775. } else {
  2776. if (url.indexOf("file:") === -1) {
  2777. noIndexedDB();
  2778. } else {
  2779. try {
  2780. var textureName = url.substring(5);
  2781. var blobURL;
  2782. try {
  2783. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2784. } catch (ex) {
  2785. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2786. }
  2787. img.src = blobURL;
  2788. } catch (e) {
  2789. Tools.Log("Error while trying to load texture: " + textureName);
  2790. img.src = null;
  2791. }
  2792. }
  2793. }
  2794. return img;
  2795. };
  2796. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2797. url = Tools.CleanUrl(url);
  2798. var noIndexedDB = function () {
  2799. var request = new XMLHttpRequest();
  2800. var loadUrl = Tools.BaseUrl + url;
  2801. request.open('GET', loadUrl, true);
  2802. if (useArrayBuffer) {
  2803. request.responseType = "arraybuffer";
  2804. }
  2805. request.onprogress = progressCallBack;
  2806. request.onreadystatechange = function () {
  2807. if (request.readyState == 4) {
  2808. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2809. callback(!useArrayBuffer ? request.responseText : request.response);
  2810. } else {
  2811. if (onError) {
  2812. onError();
  2813. } else {
  2814. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2815. }
  2816. }
  2817. }
  2818. };
  2819. request.send(null);
  2820. };
  2821. var loadFromIndexedDB = function () {
  2822. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2823. };
  2824. if (url.indexOf("file:") !== -1) {
  2825. var fileName = url.substring(5);
  2826. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2827. } else {
  2828. if (database && database.enableSceneOffline) {
  2829. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2830. } else {
  2831. noIndexedDB();
  2832. }
  2833. }
  2834. };
  2835. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2836. var reader = new FileReader();
  2837. reader.onload = function (e) {
  2838. callback(e.target.result);
  2839. };
  2840. reader.onprogress = progressCallback;
  2841. reader.readAsDataURL(fileToLoad);
  2842. };
  2843. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2844. var reader = new FileReader();
  2845. reader.onload = function (e) {
  2846. callback(e.target.result);
  2847. };
  2848. reader.onprogress = progressCallBack;
  2849. if (!useArrayBuffer) {
  2850. reader.readAsText(fileToLoad);
  2851. } else {
  2852. reader.readAsArrayBuffer(fileToLoad);
  2853. }
  2854. };
  2855. Tools.CheckExtends = function (v, min, max) {
  2856. if (v.x < min.x)
  2857. min.x = v.x;
  2858. if (v.y < min.y)
  2859. min.y = v.y;
  2860. if (v.z < min.z)
  2861. min.z = v.z;
  2862. if (v.x > max.x)
  2863. max.x = v.x;
  2864. if (v.y > max.y)
  2865. max.y = v.y;
  2866. if (v.z > max.z)
  2867. max.z = v.z;
  2868. };
  2869. Tools.WithinEpsilon = function (a, b) {
  2870. var num = a - b;
  2871. return -1.401298E-45 <= num && num <= 1.401298E-45;
  2872. };
  2873. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2874. for (var prop in source) {
  2875. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2876. continue;
  2877. }
  2878. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2879. continue;
  2880. }
  2881. var sourceValue = source[prop];
  2882. var typeOfSourceValue = typeof sourceValue;
  2883. if (typeOfSourceValue == "function") {
  2884. continue;
  2885. }
  2886. if (typeOfSourceValue == "object") {
  2887. if (sourceValue instanceof Array) {
  2888. destination[prop] = [];
  2889. if (sourceValue.length > 0) {
  2890. if (typeof sourceValue[0] == "object") {
  2891. for (var index = 0; index < sourceValue.length; index++) {
  2892. var clonedValue = cloneValue(sourceValue[index], destination);
  2893. if (destination[prop].indexOf(clonedValue) === -1) {
  2894. destination[prop].push(clonedValue);
  2895. }
  2896. }
  2897. } else {
  2898. destination[prop] = sourceValue.slice(0);
  2899. }
  2900. }
  2901. } else {
  2902. destination[prop] = cloneValue(sourceValue, destination);
  2903. }
  2904. } else {
  2905. destination[prop] = sourceValue;
  2906. }
  2907. }
  2908. };
  2909. Tools.IsEmpty = function (obj) {
  2910. for (var i in obj) {
  2911. return false;
  2912. }
  2913. return true;
  2914. };
  2915. Tools.RegisterTopRootEvents = function (events) {
  2916. for (var index = 0; index < events.length; index++) {
  2917. var event = events[index];
  2918. window.addEventListener(event.name, event.handler, false);
  2919. try {
  2920. if (window.parent) {
  2921. window.parent.addEventListener(event.name, event.handler, false);
  2922. }
  2923. } catch (e) {
  2924. }
  2925. }
  2926. };
  2927. Tools.UnregisterTopRootEvents = function (events) {
  2928. for (var index = 0; index < events.length; index++) {
  2929. var event = events[index];
  2930. window.removeEventListener(event.name, event.handler);
  2931. try {
  2932. if (window.parent) {
  2933. window.parent.removeEventListener(event.name, event.handler);
  2934. }
  2935. } catch (e) {
  2936. }
  2937. }
  2938. };
  2939. Tools.GetFps = function () {
  2940. return fps;
  2941. };
  2942. Tools.GetDeltaTime = function () {
  2943. return deltaTime;
  2944. };
  2945. Tools._MeasureFps = function () {
  2946. previousFramesDuration.push((new Date).getTime());
  2947. var length = previousFramesDuration.length;
  2948. if (length >= 2) {
  2949. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  2950. }
  2951. if (length >= fpsRange) {
  2952. if (length > fpsRange) {
  2953. previousFramesDuration.splice(0, 1);
  2954. length = previousFramesDuration.length;
  2955. }
  2956. var sum = 0;
  2957. for (var id = 0; id < length - 1; id++) {
  2958. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2959. }
  2960. fps = 1000.0 / (sum / (length - 1));
  2961. }
  2962. };
  2963. Tools.CreateScreenshot = function (engine, camera, size) {
  2964. var width;
  2965. var height;
  2966. var scene = camera.getScene();
  2967. var previousCamera = null;
  2968. if (scene.activeCamera !== camera) {
  2969. previousCamera = scene.activeCamera;
  2970. scene.activeCamera = camera;
  2971. }
  2972. if (size.precision) {
  2973. width = Math.round(engine.getRenderWidth() * size.precision);
  2974. height = Math.round(width / engine.getAspectRatio(camera));
  2975. size = { width: width, height: height };
  2976. } else if (size.width && size.height) {
  2977. width = size.width;
  2978. height = size.height;
  2979. } else if (size.width && !size.height) {
  2980. width = size.width;
  2981. height = Math.round(width / engine.getAspectRatio(camera));
  2982. size = { width: width, height: height };
  2983. } else if (size.height && !size.width) {
  2984. height = size.height;
  2985. width = Math.round(height * engine.getAspectRatio(camera));
  2986. size = { width: width, height: height };
  2987. } else if (!isNaN(size)) {
  2988. height = size;
  2989. width = size;
  2990. } else {
  2991. Tools.Error("Invalid 'size' parameter !");
  2992. return;
  2993. }
  2994. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2995. texture.renderList = engine.scenes[0].meshes;
  2996. texture.onAfterRender = function () {
  2997. var numberOfChannelsByLine = width * 4;
  2998. var halfHeight = height / 2;
  2999. var data = engine.readPixels(0, 0, width, height);
  3000. for (var i = 0; i < halfHeight; i++) {
  3001. for (var j = 0; j < numberOfChannelsByLine; j++) {
  3002. var currentCell = j + i * numberOfChannelsByLine;
  3003. var targetLine = height - i - 1;
  3004. var targetCell = j + targetLine * numberOfChannelsByLine;
  3005. var temp = data[currentCell];
  3006. data[currentCell] = data[targetCell];
  3007. data[targetCell] = temp;
  3008. }
  3009. }
  3010. if (!screenshotCanvas) {
  3011. screenshotCanvas = document.createElement('canvas');
  3012. }
  3013. screenshotCanvas.width = width;
  3014. screenshotCanvas.height = height;
  3015. var context = screenshotCanvas.getContext('2d');
  3016. var imageData = context.createImageData(width, height);
  3017. imageData.data.set(data);
  3018. context.putImageData(imageData, 0, 0);
  3019. var base64Image = screenshotCanvas.toDataURL();
  3020. if (("download" in document.createElement("a"))) {
  3021. var a = window.document.createElement("a");
  3022. a.href = base64Image;
  3023. var date = new Date();
  3024. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  3025. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  3026. window.document.body.appendChild(a);
  3027. a.addEventListener("click", function () {
  3028. a.parentElement.removeChild(a);
  3029. });
  3030. a.click();
  3031. } else {
  3032. var newWindow = window.open("");
  3033. var img = newWindow.document.createElement("img");
  3034. img.src = base64Image;
  3035. newWindow.document.body.appendChild(img);
  3036. }
  3037. };
  3038. texture.render(true);
  3039. texture.dispose();
  3040. if (previousCamera) {
  3041. scene.activeCamera = previousCamera;
  3042. }
  3043. };
  3044. Tools.ValidateXHRData = function (xhr, dataType) {
  3045. if (typeof dataType === "undefined") { dataType = 7; }
  3046. try {
  3047. if (dataType & 1) {
  3048. if (xhr.responseText && xhr.responseText.length > 0) {
  3049. return true;
  3050. } else if (dataType === 1) {
  3051. return false;
  3052. }
  3053. }
  3054. if (dataType & 2) {
  3055. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3056. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3057. return true;
  3058. } else if (dataType === 2) {
  3059. return false;
  3060. }
  3061. }
  3062. if (dataType & 4) {
  3063. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3064. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  3065. return true;
  3066. } else {
  3067. return false;
  3068. }
  3069. }
  3070. } catch (e) {
  3071. }
  3072. return false;
  3073. };
  3074. Object.defineProperty(Tools, "NoneLogLevel", {
  3075. get: function () {
  3076. return Tools._NoneLogLevel;
  3077. },
  3078. enumerable: true,
  3079. configurable: true
  3080. });
  3081. Object.defineProperty(Tools, "MessageLogLevel", {
  3082. get: function () {
  3083. return Tools._MessageLogLevel;
  3084. },
  3085. enumerable: true,
  3086. configurable: true
  3087. });
  3088. Object.defineProperty(Tools, "WarningLogLevel", {
  3089. get: function () {
  3090. return Tools._WarningLogLevel;
  3091. },
  3092. enumerable: true,
  3093. configurable: true
  3094. });
  3095. Object.defineProperty(Tools, "ErrorLogLevel", {
  3096. get: function () {
  3097. return Tools._ErrorLogLevel;
  3098. },
  3099. enumerable: true,
  3100. configurable: true
  3101. });
  3102. Object.defineProperty(Tools, "AllLogLevel", {
  3103. get: function () {
  3104. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3105. },
  3106. enumerable: true,
  3107. configurable: true
  3108. });
  3109. Tools._FormatMessage = function (message) {
  3110. var padStr = function (i) {
  3111. return (i < 10) ? "0" + i : "" + i;
  3112. };
  3113. var date = new Date();
  3114. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3115. };
  3116. Tools._LogDisabled = function (message) {
  3117. };
  3118. Tools._LogEnabled = function (message) {
  3119. console.log(Tools._FormatMessage(message));
  3120. };
  3121. Tools._WarnDisabled = function (message) {
  3122. };
  3123. Tools._WarnEnabled = function (message) {
  3124. console.warn(Tools._FormatMessage(message));
  3125. };
  3126. Tools._ErrorDisabled = function (message) {
  3127. };
  3128. Tools._ErrorEnabled = function (message) {
  3129. console.error(Tools._FormatMessage(message));
  3130. };
  3131. Object.defineProperty(Tools, "LogLevels", {
  3132. set: function (level) {
  3133. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3134. Tools.Log = Tools._LogEnabled;
  3135. } else {
  3136. Tools.Log = Tools._LogDisabled;
  3137. }
  3138. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3139. Tools.Warn = Tools._WarnEnabled;
  3140. } else {
  3141. Tools.Warn = Tools._WarnDisabled;
  3142. }
  3143. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3144. Tools.Error = Tools._ErrorEnabled;
  3145. } else {
  3146. Tools.Error = Tools._ErrorDisabled;
  3147. }
  3148. },
  3149. enumerable: true,
  3150. configurable: true
  3151. });
  3152. Tools.BaseUrl = "";
  3153. Tools.GetExponantOfTwo = function (value, max) {
  3154. var count = 1;
  3155. do {
  3156. count *= 2;
  3157. } while(count < value);
  3158. if (count > max)
  3159. count = max;
  3160. return count;
  3161. };
  3162. Tools._NoneLogLevel = 0;
  3163. Tools._MessageLogLevel = 1;
  3164. Tools._WarningLogLevel = 2;
  3165. Tools._ErrorLogLevel = 4;
  3166. Tools.Log = Tools._LogEnabled;
  3167. Tools.Warn = Tools._WarnEnabled;
  3168. Tools.Error = Tools._ErrorEnabled;
  3169. return Tools;
  3170. })();
  3171. BABYLON.Tools = Tools;
  3172. })(BABYLON || (BABYLON = {}));
  3173. var BABYLON;
  3174. (function (BABYLON) {
  3175. var _DepthCullingState = (function () {
  3176. function _DepthCullingState() {
  3177. this._isDepthTestDirty = false;
  3178. this._isDepthMaskDirty = false;
  3179. this._isDepthFuncDirty = false;
  3180. this._isCullFaceDirty = false;
  3181. this._isCullDirty = false;
  3182. }
  3183. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3184. get: function () {
  3185. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3186. },
  3187. enumerable: true,
  3188. configurable: true
  3189. });
  3190. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3191. get: function () {
  3192. return this._cullFace;
  3193. },
  3194. set: function (value) {
  3195. if (this._cullFace === value) {
  3196. return;
  3197. }
  3198. this._cullFace = value;
  3199. this._isCullFaceDirty = true;
  3200. },
  3201. enumerable: true,
  3202. configurable: true
  3203. });
  3204. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3205. get: function () {
  3206. return this._cull;
  3207. },
  3208. set: function (value) {
  3209. if (this._cull === value) {
  3210. return;
  3211. }
  3212. this._cull = value;
  3213. this._isCullDirty = true;
  3214. },
  3215. enumerable: true,
  3216. configurable: true
  3217. });
  3218. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3219. get: function () {
  3220. return this._depthFunc;
  3221. },
  3222. set: function (value) {
  3223. if (this._depthFunc === value) {
  3224. return;
  3225. }
  3226. this._depthFunc = value;
  3227. this._isDepthFuncDirty = true;
  3228. },
  3229. enumerable: true,
  3230. configurable: true
  3231. });
  3232. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3233. get: function () {
  3234. return this._depthMask;
  3235. },
  3236. set: function (value) {
  3237. if (this._depthMask === value) {
  3238. return;
  3239. }
  3240. this._depthMask = value;
  3241. this._isDepthMaskDirty = true;
  3242. },
  3243. enumerable: true,
  3244. configurable: true
  3245. });
  3246. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3247. get: function () {
  3248. return this._depthTest;
  3249. },
  3250. set: function (value) {
  3251. if (this._depthTest === value) {
  3252. return;
  3253. }
  3254. this._depthTest = value;
  3255. this._isDepthTestDirty = true;
  3256. },
  3257. enumerable: true,
  3258. configurable: true
  3259. });
  3260. _DepthCullingState.prototype.reset = function () {
  3261. this._depthMask = true;
  3262. this._depthTest = true;
  3263. this._depthFunc = null;
  3264. this._cull = null;
  3265. this._cullFace = null;
  3266. this._isDepthTestDirty = true;
  3267. this._isDepthMaskDirty = true;
  3268. this._isDepthFuncDirty = false;
  3269. this._isCullFaceDirty = false;
  3270. this._isCullDirty = false;
  3271. };
  3272. _DepthCullingState.prototype.apply = function (gl) {
  3273. if (!this.isDirty) {
  3274. return;
  3275. }
  3276. if (this._isCullDirty) {
  3277. if (this.cull === true) {
  3278. gl.enable(gl.CULL_FACE);
  3279. } else if (this.cull === false) {
  3280. gl.disable(gl.CULL_FACE);
  3281. }
  3282. this._isCullDirty = false;
  3283. }
  3284. if (this._isCullFaceDirty) {
  3285. gl.cullFace(this.cullFace);
  3286. this._isCullFaceDirty = false;
  3287. }
  3288. if (this._isDepthMaskDirty) {
  3289. gl.depthMask(this.depthMask);
  3290. this._isDepthMaskDirty = false;
  3291. }
  3292. if (this._isDepthTestDirty) {
  3293. if (this.depthTest === true) {
  3294. gl.enable(gl.DEPTH_TEST);
  3295. } else if (this.depthTest === false) {
  3296. gl.disable(gl.DEPTH_TEST);
  3297. }
  3298. this._isDepthTestDirty = false;
  3299. }
  3300. if (this._isDepthFuncDirty) {
  3301. gl.depthFunc(this.depthFunc);
  3302. this._isDepthFuncDirty = false;
  3303. }
  3304. };
  3305. return _DepthCullingState;
  3306. })();
  3307. BABYLON._DepthCullingState = _DepthCullingState;
  3308. var _AlphaState = (function () {
  3309. function _AlphaState() {
  3310. this._isAlphaBlendDirty = false;
  3311. this._isBlendFunctionParametersDirty = false;
  3312. this._alphaBlend = false;
  3313. this._blendFunctionParameters = new Array(4);
  3314. }
  3315. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3316. get: function () {
  3317. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3318. },
  3319. enumerable: true,
  3320. configurable: true
  3321. });
  3322. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3323. get: function () {
  3324. return this._alphaBlend;
  3325. },
  3326. set: function (value) {
  3327. if (this._alphaBlend === value) {
  3328. return;
  3329. }
  3330. this._alphaBlend = value;
  3331. this._isAlphaBlendDirty = true;
  3332. },
  3333. enumerable: true,
  3334. configurable: true
  3335. });
  3336. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3337. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3338. return;
  3339. }
  3340. this._blendFunctionParameters[0] = value0;
  3341. this._blendFunctionParameters[1] = value1;
  3342. this._blendFunctionParameters[2] = value2;
  3343. this._blendFunctionParameters[3] = value3;
  3344. this._isBlendFunctionParametersDirty = true;
  3345. };
  3346. _AlphaState.prototype.reset = function () {
  3347. this._alphaBlend = false;
  3348. this._blendFunctionParameters[0] = null;
  3349. this._blendFunctionParameters[1] = null;
  3350. this._blendFunctionParameters[2] = null;
  3351. this._blendFunctionParameters[3] = null;
  3352. this._isAlphaBlendDirty = true;
  3353. this._isBlendFunctionParametersDirty = false;
  3354. };
  3355. _AlphaState.prototype.apply = function (gl) {
  3356. if (!this.isDirty) {
  3357. return;
  3358. }
  3359. if (this._isAlphaBlendDirty) {
  3360. if (this._alphaBlend === true) {
  3361. gl.enable(gl.BLEND);
  3362. } else if (this._alphaBlend === false) {
  3363. gl.disable(gl.BLEND);
  3364. }
  3365. this._isAlphaBlendDirty = false;
  3366. }
  3367. if (this._isBlendFunctionParametersDirty) {
  3368. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3369. this._isBlendFunctionParametersDirty = false;
  3370. }
  3371. };
  3372. return _AlphaState;
  3373. })();
  3374. BABYLON._AlphaState = _AlphaState;
  3375. var compileShader = function (gl, source, type, defines) {
  3376. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3377. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3378. gl.compileShader(shader);
  3379. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3380. throw new Error(gl.getShaderInfoLog(shader));
  3381. }
  3382. return shader;
  3383. };
  3384. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3385. var magFilter = gl.NEAREST;
  3386. var minFilter = gl.NEAREST;
  3387. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3388. magFilter = gl.LINEAR;
  3389. if (generateMipMaps) {
  3390. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3391. } else {
  3392. minFilter = gl.LINEAR;
  3393. }
  3394. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3395. magFilter = gl.LINEAR;
  3396. if (generateMipMaps) {
  3397. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3398. } else {
  3399. minFilter = gl.LINEAR;
  3400. }
  3401. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3402. magFilter = gl.NEAREST;
  3403. if (generateMipMaps) {
  3404. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3405. } else {
  3406. minFilter = gl.NEAREST;
  3407. }
  3408. }
  3409. return {
  3410. min: minFilter,
  3411. mag: magFilter
  3412. };
  3413. };
  3414. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3415. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3416. var engine = scene.getEngine();
  3417. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3418. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3419. gl.bindTexture(gl.TEXTURE_2D, texture);
  3420. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3421. processFunction(potWidth, potHeight);
  3422. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3423. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3424. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3425. if (!noMipmap && !isCompressed) {
  3426. gl.generateMipmap(gl.TEXTURE_2D);
  3427. }
  3428. gl.bindTexture(gl.TEXTURE_2D, null);
  3429. engine._activeTexturesCache = [];
  3430. texture._baseWidth = width;
  3431. texture._baseHeight = height;
  3432. texture._width = potWidth;
  3433. texture._height = potHeight;
  3434. texture.isReady = true;
  3435. scene._removePendingData(texture);
  3436. };
  3437. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3438. var img;
  3439. var onload = function () {
  3440. loadedImages[index] = img;
  3441. loadedImages._internalCount++;
  3442. scene._removePendingData(img);
  3443. if (loadedImages._internalCount == 6) {
  3444. onfinish(loadedImages);
  3445. }
  3446. };
  3447. var onerror = function () {
  3448. scene._removePendingData(img);
  3449. };
  3450. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3451. scene._addPendingData(img);
  3452. };
  3453. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3454. var loadedImages = [];
  3455. loadedImages._internalCount = 0;
  3456. for (var index = 0; index < 6; index++) {
  3457. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3458. }
  3459. };
  3460. var EngineCapabilities = (function () {
  3461. function EngineCapabilities() {
  3462. }
  3463. return EngineCapabilities;
  3464. })();
  3465. BABYLON.EngineCapabilities = EngineCapabilities;
  3466. var Engine = (function () {
  3467. function Engine(canvas, antialias, options) {
  3468. var _this = this;
  3469. this.isFullscreen = false;
  3470. this.isPointerLock = false;
  3471. this.forceWireframe = false;
  3472. this.cullBackFaces = true;
  3473. this.renderEvenInBackground = true;
  3474. this.scenes = new Array();
  3475. this._windowIsBackground = false;
  3476. this._runningLoop = false;
  3477. this._loadingDivBackgroundColor = "black";
  3478. this._depthCullingState = new _DepthCullingState();
  3479. this._alphaState = new _AlphaState();
  3480. this._loadedTexturesCache = new Array();
  3481. this._activeTexturesCache = new Array();
  3482. this._compiledEffects = {};
  3483. this._renderingCanvas = canvas;
  3484. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3485. options = options || {};
  3486. options.antialias = antialias;
  3487. try {
  3488. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3489. } catch (e) {
  3490. throw new Error("WebGL not supported");
  3491. }
  3492. if (!this._gl) {
  3493. throw new Error("WebGL not supported");
  3494. }
  3495. this._onBlur = function () {
  3496. _this._windowIsBackground = true;
  3497. };
  3498. this._onFocus = function () {
  3499. _this._windowIsBackground = false;
  3500. };
  3501. window.addEventListener("blur", this._onBlur);
  3502. window.addEventListener("focus", this._onFocus);
  3503. this._workingCanvas = document.createElement("canvas");
  3504. this._workingContext = this._workingCanvas.getContext("2d");
  3505. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3506. this.resize();
  3507. this._caps = new EngineCapabilities();
  3508. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3509. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3510. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3511. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3512. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3513. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3514. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3515. 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');
  3516. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3517. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3518. this.setDepthBuffer(true);
  3519. this.setDepthFunctionToLessOrEqual();
  3520. this.setDepthWrite(true);
  3521. this._onFullscreenChange = function () {
  3522. if (document.fullscreen !== undefined) {
  3523. _this.isFullscreen = document.fullscreen;
  3524. } else if (document.mozFullScreen !== undefined) {
  3525. _this.isFullscreen = document.mozFullScreen;
  3526. } else if (document.webkitIsFullScreen !== undefined) {
  3527. _this.isFullscreen = document.webkitIsFullScreen;
  3528. } else if (document.msIsFullScreen !== undefined) {
  3529. _this.isFullscreen = document.msIsFullScreen;
  3530. }
  3531. if (_this.isFullscreen && _this._pointerLockRequested) {
  3532. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3533. if (canvas.requestPointerLock) {
  3534. canvas.requestPointerLock();
  3535. }
  3536. }
  3537. };
  3538. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3539. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3540. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3541. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3542. this._onPointerLockChange = function () {
  3543. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3544. };
  3545. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3546. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3547. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3548. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3549. }
  3550. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3551. get: function () {
  3552. return Engine._ALPHA_DISABLE;
  3553. },
  3554. enumerable: true,
  3555. configurable: true
  3556. });
  3557. Object.defineProperty(Engine, "ALPHA_ADD", {
  3558. get: function () {
  3559. return Engine._ALPHA_ADD;
  3560. },
  3561. enumerable: true,
  3562. configurable: true
  3563. });
  3564. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3565. get: function () {
  3566. return Engine._ALPHA_COMBINE;
  3567. },
  3568. enumerable: true,
  3569. configurable: true
  3570. });
  3571. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3572. get: function () {
  3573. return Engine._DELAYLOADSTATE_NONE;
  3574. },
  3575. enumerable: true,
  3576. configurable: true
  3577. });
  3578. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3579. get: function () {
  3580. return Engine._DELAYLOADSTATE_LOADED;
  3581. },
  3582. enumerable: true,
  3583. configurable: true
  3584. });
  3585. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3586. get: function () {
  3587. return Engine._DELAYLOADSTATE_LOADING;
  3588. },
  3589. enumerable: true,
  3590. configurable: true
  3591. });
  3592. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3593. get: function () {
  3594. return Engine._DELAYLOADSTATE_NOTLOADED;
  3595. },
  3596. enumerable: true,
  3597. configurable: true
  3598. });
  3599. Object.defineProperty(Engine, "Version", {
  3600. get: function () {
  3601. return "1.14.0";
  3602. },
  3603. enumerable: true,
  3604. configurable: true
  3605. });
  3606. Engine.prototype.getAspectRatio = function (camera) {
  3607. var viewport = camera.viewport;
  3608. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3609. };
  3610. Engine.prototype.getRenderWidth = function () {
  3611. if (this._currentRenderTarget) {
  3612. return this._currentRenderTarget._width;
  3613. }
  3614. return this._renderingCanvas.width;
  3615. };
  3616. Engine.prototype.getRenderHeight = function () {
  3617. if (this._currentRenderTarget) {
  3618. return this._currentRenderTarget._height;
  3619. }
  3620. return this._renderingCanvas.height;
  3621. };
  3622. Engine.prototype.getRenderingCanvas = function () {
  3623. return this._renderingCanvas;
  3624. };
  3625. Engine.prototype.getRenderingCanvasClientRect = function () {
  3626. return this._renderingCanvas.getBoundingClientRect();
  3627. };
  3628. Engine.prototype.setHardwareScalingLevel = function (level) {
  3629. this._hardwareScalingLevel = level;
  3630. this.resize();
  3631. };
  3632. Engine.prototype.getHardwareScalingLevel = function () {
  3633. return this._hardwareScalingLevel;
  3634. };
  3635. Engine.prototype.getLoadedTexturesCache = function () {
  3636. return this._loadedTexturesCache;
  3637. };
  3638. Engine.prototype.getCaps = function () {
  3639. return this._caps;
  3640. };
  3641. Engine.prototype.setDepthFunctionToGreater = function () {
  3642. this._depthCullingState.depthFunc = this._gl.GREATER;
  3643. };
  3644. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3645. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3646. };
  3647. Engine.prototype.setDepthFunctionToLess = function () {
  3648. this._depthCullingState.depthFunc = this._gl.LESS;
  3649. };
  3650. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3651. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3652. };
  3653. Engine.prototype.stopRenderLoop = function () {
  3654. this._renderFunction = null;
  3655. this._runningLoop = false;
  3656. };
  3657. Engine.prototype._renderLoop = function () {
  3658. var _this = this;
  3659. var shouldRender = true;
  3660. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3661. shouldRender = false;
  3662. }
  3663. if (shouldRender) {
  3664. this.beginFrame();
  3665. if (this._renderFunction) {
  3666. this._renderFunction();
  3667. }
  3668. this.endFrame();
  3669. }
  3670. if (this._runningLoop) {
  3671. BABYLON.Tools.QueueNewFrame(function () {
  3672. _this._renderLoop();
  3673. });
  3674. }
  3675. };
  3676. Engine.prototype.runRenderLoop = function (renderFunction) {
  3677. var _this = this;
  3678. this._runningLoop = true;
  3679. this._renderFunction = renderFunction;
  3680. BABYLON.Tools.QueueNewFrame(function () {
  3681. _this._renderLoop();
  3682. });
  3683. };
  3684. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3685. if (this.isFullscreen) {
  3686. BABYLON.Tools.ExitFullscreen();
  3687. } else {
  3688. this._pointerLockRequested = requestPointerLock;
  3689. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3690. }
  3691. };
  3692. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3693. this.applyStates();
  3694. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3695. if (this._depthCullingState.depthMask) {
  3696. this._gl.clearDepth(1.0);
  3697. }
  3698. var mode = 0;
  3699. if (backBuffer)
  3700. mode |= this._gl.COLOR_BUFFER_BIT;
  3701. if (depthStencil && this._depthCullingState.depthMask)
  3702. mode |= this._gl.DEPTH_BUFFER_BIT;
  3703. this._gl.clear(mode);
  3704. };
  3705. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3706. var width = requiredWidth || this._renderingCanvas.width;
  3707. var height = requiredHeight || this._renderingCanvas.height;
  3708. var x = viewport.x || 0;
  3709. var y = viewport.y || 0;
  3710. this._cachedViewport = viewport;
  3711. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3712. };
  3713. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3714. this._cachedViewport = null;
  3715. this._gl.viewport(x, y, width, height);
  3716. };
  3717. Engine.prototype.beginFrame = function () {
  3718. BABYLON.Tools._MeasureFps();
  3719. };
  3720. Engine.prototype.endFrame = function () {
  3721. this.flushFramebuffer();
  3722. };
  3723. Engine.prototype.resize = function () {
  3724. this._renderingCanvas.width = this._renderingCanvas.clientWidth / this._hardwareScalingLevel;
  3725. this._renderingCanvas.height = this._renderingCanvas.clientHeight / this._hardwareScalingLevel;
  3726. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3727. };
  3728. Engine.prototype.bindFramebuffer = function (texture) {
  3729. this._currentRenderTarget = texture;
  3730. var gl = this._gl;
  3731. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3732. this._gl.viewport(0, 0, texture._width, texture._height);
  3733. this.wipeCaches();
  3734. };
  3735. Engine.prototype.unBindFramebuffer = function (texture) {
  3736. this._currentRenderTarget = null;
  3737. if (texture.generateMipMaps) {
  3738. var gl = this._gl;
  3739. gl.bindTexture(gl.TEXTURE_2D, texture);
  3740. gl.generateMipmap(gl.TEXTURE_2D);
  3741. gl.bindTexture(gl.TEXTURE_2D, null);
  3742. }
  3743. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3744. };
  3745. Engine.prototype.flushFramebuffer = function () {
  3746. this._gl.flush();
  3747. };
  3748. Engine.prototype.restoreDefaultFramebuffer = function () {
  3749. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3750. this.setViewport(this._cachedViewport);
  3751. this.wipeCaches();
  3752. };
  3753. Engine.prototype._resetVertexBufferBinding = function () {
  3754. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3755. this._cachedVertexBuffers = null;
  3756. };
  3757. Engine.prototype.createVertexBuffer = function (vertices) {
  3758. var vbo = this._gl.createBuffer();
  3759. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3760. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3761. this._resetVertexBufferBinding();
  3762. vbo.references = 1;
  3763. return vbo;
  3764. };
  3765. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3766. var vbo = this._gl.createBuffer();
  3767. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3768. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3769. this._resetVertexBufferBinding();
  3770. vbo.references = 1;
  3771. return vbo;
  3772. };
  3773. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  3774. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3775. if (vertices instanceof Float32Array) {
  3776. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  3777. } else {
  3778. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  3779. }
  3780. this._resetVertexBufferBinding();
  3781. };
  3782. Engine.prototype._resetIndexBufferBinding = function () {
  3783. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3784. this._cachedIndexBuffer = null;
  3785. };
  3786. Engine.prototype.createIndexBuffer = function (indices) {
  3787. var vbo = this._gl.createBuffer();
  3788. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3789. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  3790. this._resetIndexBufferBinding();
  3791. vbo.references = 1;
  3792. return vbo;
  3793. };
  3794. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3795. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3796. this._cachedVertexBuffers = vertexBuffer;
  3797. this._cachedEffectForVertexBuffers = effect;
  3798. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3799. var offset = 0;
  3800. for (var index = 0; index < vertexDeclaration.length; index++) {
  3801. var order = effect.getAttributeLocation(index);
  3802. if (order >= 0) {
  3803. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3804. }
  3805. offset += vertexDeclaration[index] * 4;
  3806. }
  3807. }
  3808. if (this._cachedIndexBuffer !== indexBuffer) {
  3809. this._cachedIndexBuffer = indexBuffer;
  3810. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3811. }
  3812. };
  3813. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3814. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3815. this._cachedVertexBuffers = vertexBuffers;
  3816. this._cachedEffectForVertexBuffers = effect;
  3817. var attributes = effect.getAttributesNames();
  3818. for (var index = 0; index < attributes.length; index++) {
  3819. var order = effect.getAttributeLocation(index);
  3820. if (order >= 0) {
  3821. var vertexBuffer = vertexBuffers[attributes[index]];
  3822. if (!vertexBuffer) {
  3823. continue;
  3824. }
  3825. var stride = vertexBuffer.getStrideSize();
  3826. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3827. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3828. }
  3829. }
  3830. }
  3831. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3832. this._cachedIndexBuffer = indexBuffer;
  3833. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3834. }
  3835. };
  3836. Engine.prototype._releaseBuffer = function (buffer) {
  3837. buffer.references--;
  3838. if (buffer.references === 0) {
  3839. this._gl.deleteBuffer(buffer);
  3840. return true;
  3841. }
  3842. return false;
  3843. };
  3844. Engine.prototype.createInstancesBuffer = function (capacity) {
  3845. var buffer = this._gl.createBuffer();
  3846. buffer.capacity = capacity;
  3847. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3848. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3849. return buffer;
  3850. };
  3851. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3852. this._gl.deleteBuffer(buffer);
  3853. };
  3854. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3855. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3856. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3857. for (var index = 0; index < 4; index++) {
  3858. var offsetLocation = offsetLocations[index];
  3859. this._gl.enableVertexAttribArray(offsetLocation);
  3860. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3861. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3862. }
  3863. };
  3864. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3865. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3866. for (var index = 0; index < 4; index++) {
  3867. var offsetLocation = offsetLocations[index];
  3868. this._gl.disableVertexAttribArray(offsetLocation);
  3869. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3870. }
  3871. };
  3872. Engine.prototype.applyStates = function () {
  3873. this._depthCullingState.apply(this._gl);
  3874. this._alphaState.apply(this._gl);
  3875. };
  3876. Engine.prototype.draw = function (drawAs, start, count, instancesCount) {
  3877. this.applyStates();
  3878. switch (drawAs) {
  3879. case this._gl.LINES:
  3880. case this._gl.TRIANGLES:
  3881. {
  3882. if (instancesCount) {
  3883. this._caps.instancedArrays.drawElementsInstancedANGLE(drawAs, count, this._gl.UNSIGNED_SHORT, start * 2, instancesCount);
  3884. } else {
  3885. this._gl.drawElements(drawAs, count, this._gl.UNSIGNED_SHORT, start * 2);
  3886. }
  3887. }
  3888. break;
  3889. case this._gl.POINTS:
  3890. {
  3891. this._gl.drawArrays(drawAs, 0, count);
  3892. }
  3893. break;
  3894. }
  3895. };
  3896. /*
  3897. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  3898. this.applyStates();
  3899. if (instancesCount) {
  3900. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  3901. return;
  3902. }
  3903. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  3904. }*/
  3905. Engine.prototype._releaseEffect = function (effect) {
  3906. if (this._compiledEffects[effect._key]) {
  3907. delete this._compiledEffects[effect._key];
  3908. if (effect.getProgram()) {
  3909. this._gl.deleteProgram(effect.getProgram());
  3910. }
  3911. }
  3912. };
  3913. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3914. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3915. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3916. var name = vertex + "+" + fragment + "@" + defines;
  3917. if (this._compiledEffects[name]) {
  3918. return this._compiledEffects[name];
  3919. }
  3920. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3921. effect._key = name;
  3922. this._compiledEffects[name] = effect;
  3923. return effect;
  3924. };
  3925. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3926. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3927. if (typeof samplers === "undefined") { samplers = []; }
  3928. if (typeof defines === "undefined") { defines = ""; }
  3929. return this.createEffect({
  3930. vertex: "particles",
  3931. fragmentElement: fragmentName
  3932. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3933. };
  3934. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3935. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3936. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3937. var shaderProgram = this._gl.createProgram();
  3938. this._gl.attachShader(shaderProgram, vertexShader);
  3939. this._gl.attachShader(shaderProgram, fragmentShader);
  3940. this._gl.linkProgram(shaderProgram);
  3941. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3942. if (!linked) {
  3943. var error = this._gl.getProgramInfoLog(shaderProgram);
  3944. if (error) {
  3945. throw new Error(error);
  3946. }
  3947. }
  3948. this._gl.deleteShader(vertexShader);
  3949. this._gl.deleteShader(fragmentShader);
  3950. return shaderProgram;
  3951. };
  3952. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3953. var results = [];
  3954. for (var index = 0; index < uniformsNames.length; index++) {
  3955. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3956. }
  3957. return results;
  3958. };
  3959. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3960. var results = [];
  3961. for (var index = 0; index < attributesNames.length; index++) {
  3962. try {
  3963. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3964. } catch (e) {
  3965. results.push(-1);
  3966. }
  3967. }
  3968. return results;
  3969. };
  3970. Engine.prototype.enableEffect = function (effect) {
  3971. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3972. return;
  3973. }
  3974. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3975. this._gl.useProgram(effect.getProgram());
  3976. for (var i in this._vertexAttribArrays) {
  3977. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3978. continue;
  3979. }
  3980. this._vertexAttribArrays[i] = false;
  3981. this._gl.disableVertexAttribArray(i);
  3982. }
  3983. var attributesCount = effect.getAttributesCount();
  3984. for (var index = 0; index < attributesCount; index++) {
  3985. var order = effect.getAttributeLocation(index);
  3986. if (order >= 0) {
  3987. this._vertexAttribArrays[order] = true;
  3988. this._gl.enableVertexAttribArray(order);
  3989. }
  3990. }
  3991. this._currentEffect = effect;
  3992. };
  3993. Engine.prototype.setArray = function (uniform, array) {
  3994. if (!uniform)
  3995. return;
  3996. this._gl.uniform1fv(uniform, array);
  3997. };
  3998. Engine.prototype.setMatrices = function (uniform, matrices) {
  3999. if (!uniform)
  4000. return;
  4001. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4002. };
  4003. Engine.prototype.setMatrix = function (uniform, matrix) {
  4004. if (!uniform)
  4005. return;
  4006. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4007. };
  4008. Engine.prototype.setFloat = function (uniform, value) {
  4009. if (!uniform)
  4010. return;
  4011. this._gl.uniform1f(uniform, value);
  4012. };
  4013. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4014. if (!uniform)
  4015. return;
  4016. this._gl.uniform2f(uniform, x, y);
  4017. };
  4018. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4019. if (!uniform)
  4020. return;
  4021. this._gl.uniform3f(uniform, x, y, z);
  4022. };
  4023. Engine.prototype.setBool = function (uniform, bool) {
  4024. if (!uniform)
  4025. return;
  4026. this._gl.uniform1i(uniform, bool);
  4027. };
  4028. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4029. if (!uniform)
  4030. return;
  4031. this._gl.uniform4f(uniform, x, y, z, w);
  4032. };
  4033. Engine.prototype.setColor3 = function (uniform, color3) {
  4034. if (!uniform)
  4035. return;
  4036. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4037. };
  4038. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4039. if (!uniform)
  4040. return;
  4041. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4042. };
  4043. Engine.prototype.setState = function (culling, force) {
  4044. if (this._depthCullingState.cull !== culling || force) {
  4045. if (culling) {
  4046. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4047. this._depthCullingState.cull = true;
  4048. } else {
  4049. this._depthCullingState.cull = false;
  4050. }
  4051. }
  4052. };
  4053. Engine.prototype.setDepthBuffer = function (enable) {
  4054. this._depthCullingState.depthTest = enable;
  4055. };
  4056. Engine.prototype.getDepthWrite = function () {
  4057. return this._depthCullingState.depthMask;
  4058. };
  4059. Engine.prototype.setDepthWrite = function (enable) {
  4060. this._depthCullingState.depthMask = enable;
  4061. };
  4062. Engine.prototype.setColorWrite = function (enable) {
  4063. this._gl.colorMask(enable, enable, enable, enable);
  4064. };
  4065. Engine.prototype.setAlphaMode = function (mode) {
  4066. switch (mode) {
  4067. case BABYLON.Engine.ALPHA_DISABLE:
  4068. this.setDepthWrite(true);
  4069. this._alphaState.alphaBlend = false;
  4070. break;
  4071. case BABYLON.Engine.ALPHA_COMBINE:
  4072. this.setDepthWrite(false);
  4073. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4074. this._alphaState.alphaBlend = true;
  4075. break;
  4076. case BABYLON.Engine.ALPHA_ADD:
  4077. this.setDepthWrite(false);
  4078. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4079. this._alphaState.alphaBlend = true;
  4080. break;
  4081. }
  4082. };
  4083. Engine.prototype.setAlphaTesting = function (enable) {
  4084. this._alphaTest = enable;
  4085. };
  4086. Engine.prototype.getAlphaTesting = function () {
  4087. return this._alphaTest;
  4088. };
  4089. Engine.prototype.wipeCaches = function () {
  4090. this._activeTexturesCache = [];
  4091. this._currentEffect = null;
  4092. this._depthCullingState.reset();
  4093. this._alphaState.reset();
  4094. this._cachedVertexBuffers = null;
  4095. this._cachedIndexBuffer = null;
  4096. this._cachedEffectForVertexBuffers = null;
  4097. };
  4098. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4099. var gl = this._gl;
  4100. gl.bindTexture(gl.TEXTURE_2D, texture);
  4101. var magFilter = gl.NEAREST;
  4102. var minFilter = gl.NEAREST;
  4103. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4104. magFilter = gl.LINEAR;
  4105. minFilter = gl.LINEAR;
  4106. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4107. magFilter = gl.LINEAR;
  4108. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4109. }
  4110. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4111. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4112. gl.bindTexture(gl.TEXTURE_2D, null);
  4113. };
  4114. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4115. var _this = this;
  4116. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4117. if (typeof onLoad === "undefined") { onLoad = null; }
  4118. if (typeof onError === "undefined") { onError = null; }
  4119. if (typeof buffer === "undefined") { buffer = null; }
  4120. var texture = this._gl.createTexture();
  4121. var extension;
  4122. var fromData = false;
  4123. if (url.substr(0, 5) === "data:") {
  4124. fromData = true;
  4125. }
  4126. if (!fromData)
  4127. extension = url.substr(url.length - 4, 4).toLowerCase();
  4128. else {
  4129. var oldUrl = url;
  4130. fromData = oldUrl.split(':');
  4131. url = oldUrl;
  4132. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4133. }
  4134. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4135. var isTGA = (extension === ".tga");
  4136. scene._addPendingData(texture);
  4137. texture.url = url;
  4138. texture.noMipmap = noMipmap;
  4139. texture.references = 1;
  4140. this._loadedTexturesCache.push(texture);
  4141. var onerror = function () {
  4142. scene._removePendingData(texture);
  4143. if (onError) {
  4144. onError();
  4145. }
  4146. };
  4147. if (isTGA) {
  4148. var callback = function (arrayBuffer) {
  4149. var data = new Uint8Array(arrayBuffer);
  4150. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4151. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4152. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4153. if (onLoad) {
  4154. onLoad();
  4155. }
  4156. }, samplingMode);
  4157. };
  4158. if (!(fromData instanceof Array))
  4159. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4160. callback(arrayBuffer);
  4161. }, onerror, scene.database, true);
  4162. else
  4163. callback(buffer);
  4164. } else if (isDDS) {
  4165. var callback = function (data) {
  4166. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4167. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  4168. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4169. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4170. if (onLoad) {
  4171. onLoad();
  4172. }
  4173. }, samplingMode);
  4174. };
  4175. if (!(fromData instanceof Array))
  4176. BABYLON.Tools.LoadFile(url, function (data) {
  4177. callback(data);
  4178. }, onerror, scene.database, true);
  4179. else
  4180. callback(buffer);
  4181. } else {
  4182. var onload = function (img) {
  4183. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4184. var isPot = (img.width == potWidth && img.height == potHeight);
  4185. if (!isPot) {
  4186. _this._workingCanvas.width = potWidth;
  4187. _this._workingCanvas.height = potHeight;
  4188. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4189. }
  4190. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4191. if (onLoad) {
  4192. onLoad();
  4193. }
  4194. }, samplingMode);
  4195. };
  4196. if (!(fromData instanceof Array))
  4197. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4198. else
  4199. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4200. }
  4201. return texture;
  4202. };
  4203. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4204. var texture = this._gl.createTexture();
  4205. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4206. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4207. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4208. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4209. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4210. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4211. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4212. this._activeTexturesCache = [];
  4213. texture._baseWidth = width;
  4214. texture._baseHeight = height;
  4215. texture._width = width;
  4216. texture._height = height;
  4217. texture.isReady = false;
  4218. texture.generateMipMaps = generateMipMaps;
  4219. texture.references = 1;
  4220. this._loadedTexturesCache.push(texture);
  4221. return texture;
  4222. };
  4223. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4224. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4225. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4226. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4227. if (texture.generateMipMaps) {
  4228. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4229. }
  4230. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4231. this._activeTexturesCache = [];
  4232. texture.isReady = true;
  4233. };
  4234. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4235. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4236. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  4237. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4238. if (!texture._workingCanvas) {
  4239. texture._workingCanvas = document.createElement("canvas");
  4240. texture._workingContext = texture._workingCanvas.getContext("2d");
  4241. texture._workingCanvas.width = texture._width;
  4242. texture._workingCanvas.height = texture._height;
  4243. }
  4244. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4245. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4246. } else {
  4247. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4248. }
  4249. if (texture.generateMipMaps) {
  4250. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4251. }
  4252. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4253. this._activeTexturesCache = [];
  4254. texture.isReady = true;
  4255. };
  4256. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4257. var generateMipMaps = false;
  4258. var generateDepthBuffer = true;
  4259. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4260. if (options !== undefined) {
  4261. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4262. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4263. if (options.samplingMode !== undefined) {
  4264. samplingMode = options.samplingMode;
  4265. }
  4266. }
  4267. var gl = this._gl;
  4268. var texture = gl.createTexture();
  4269. gl.bindTexture(gl.TEXTURE_2D, texture);
  4270. var width = size.width || size;
  4271. var height = size.height || size;
  4272. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4273. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4274. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4275. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4276. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4277. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  4278. var depthBuffer;
  4279. if (generateDepthBuffer) {
  4280. depthBuffer = gl.createRenderbuffer();
  4281. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4282. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4283. }
  4284. var framebuffer = gl.createFramebuffer();
  4285. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4286. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4287. if (generateDepthBuffer) {
  4288. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4289. }
  4290. gl.bindTexture(gl.TEXTURE_2D, null);
  4291. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4292. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4293. texture._framebuffer = framebuffer;
  4294. if (generateDepthBuffer) {
  4295. texture._depthBuffer = depthBuffer;
  4296. }
  4297. texture._width = width;
  4298. texture._height = height;
  4299. texture.isReady = true;
  4300. texture.generateMipMaps = generateMipMaps;
  4301. texture.references = 1;
  4302. this._activeTexturesCache = [];
  4303. this._loadedTexturesCache.push(texture);
  4304. return texture;
  4305. };
  4306. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4307. var _this = this;
  4308. var gl = this._gl;
  4309. var texture = gl.createTexture();
  4310. texture.isCube = true;
  4311. texture.url = rootUrl;
  4312. texture.references = 1;
  4313. this._loadedTexturesCache.push(texture);
  4314. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4315. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4316. if (isDDS) {
  4317. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4318. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4319. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4320. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4321. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4322. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4323. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  4324. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4325. }
  4326. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4327. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4328. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4329. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4330. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4331. _this._activeTexturesCache = [];
  4332. texture._width = info.width;
  4333. texture._height = info.height;
  4334. texture.isReady = true;
  4335. }, null, null, true);
  4336. } else {
  4337. cascadeLoad(rootUrl, scene, function (imgs) {
  4338. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4339. var height = width;
  4340. _this._workingCanvas.width = width;
  4341. _this._workingCanvas.height = height;
  4342. var faces = [
  4343. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4344. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4345. ];
  4346. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4347. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4348. for (var index = 0; index < faces.length; index++) {
  4349. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4350. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4351. }
  4352. if (!noMipmap) {
  4353. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4354. }
  4355. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4356. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4357. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4358. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4359. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4360. _this._activeTexturesCache = [];
  4361. texture._width = width;
  4362. texture._height = height;
  4363. texture.isReady = true;
  4364. }, extensions);
  4365. }
  4366. return texture;
  4367. };
  4368. Engine.prototype._releaseTexture = function (texture) {
  4369. var gl = this._gl;
  4370. if (texture._framebuffer) {
  4371. gl.deleteFramebuffer(texture._framebuffer);
  4372. }
  4373. if (texture._depthBuffer) {
  4374. gl.deleteRenderbuffer(texture._depthBuffer);
  4375. }
  4376. gl.deleteTexture(texture);
  4377. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4378. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4379. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4380. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4381. this._activeTexturesCache[channel] = null;
  4382. }
  4383. var index = this._loadedTexturesCache.indexOf(texture);
  4384. if (index !== -1) {
  4385. this._loadedTexturesCache.splice(index, 1);
  4386. }
  4387. };
  4388. Engine.prototype.bindSamplers = function (effect) {
  4389. this._gl.useProgram(effect.getProgram());
  4390. var samplers = effect.getSamplers();
  4391. for (var index = 0; index < samplers.length; index++) {
  4392. var uniform = effect.getUniform(samplers[index]);
  4393. this._gl.uniform1i(uniform, index);
  4394. }
  4395. this._currentEffect = null;
  4396. };
  4397. Engine.prototype._bindTexture = function (channel, texture) {
  4398. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4399. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4400. this._activeTexturesCache[channel] = null;
  4401. };
  4402. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4403. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4404. };
  4405. Engine.prototype.setTexture = function (channel, texture) {
  4406. if (channel < 0) {
  4407. return;
  4408. }
  4409. if (!texture || !texture.isReady()) {
  4410. if (this._activeTexturesCache[channel] != null) {
  4411. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4412. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4413. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4414. this._activeTexturesCache[channel] = null;
  4415. }
  4416. return;
  4417. }
  4418. if (texture instanceof BABYLON.VideoTexture) {
  4419. if (texture.update()) {
  4420. this._activeTexturesCache[channel] = null;
  4421. }
  4422. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  4423. texture.delayLoad();
  4424. return;
  4425. }
  4426. if (this._activeTexturesCache[channel] == texture) {
  4427. return;
  4428. }
  4429. this._activeTexturesCache[channel] = texture;
  4430. var internalTexture = texture.getInternalTexture();
  4431. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4432. if (internalTexture.isCube) {
  4433. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4434. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4435. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4436. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4437. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4438. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4439. }
  4440. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4441. } else {
  4442. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4443. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4444. internalTexture._cachedWrapU = texture.wrapU;
  4445. switch (texture.wrapU) {
  4446. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4447. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4448. break;
  4449. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4450. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4451. break;
  4452. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4453. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4454. break;
  4455. }
  4456. }
  4457. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4458. internalTexture._cachedWrapV = texture.wrapV;
  4459. switch (texture.wrapV) {
  4460. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4461. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4462. break;
  4463. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4464. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4465. break;
  4466. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4467. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4468. break;
  4469. }
  4470. }
  4471. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4472. }
  4473. };
  4474. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4475. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4476. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4477. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4478. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4479. }
  4480. };
  4481. Engine.prototype.readPixels = function (x, y, width, height) {
  4482. var data = new Uint8Array(height * width * 4);
  4483. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4484. return data;
  4485. };
  4486. Engine.prototype.dispose = function () {
  4487. this.hideLoadingUI();
  4488. this.stopRenderLoop();
  4489. while (this.scenes.length) {
  4490. this.scenes[0].dispose();
  4491. }
  4492. for (var name in this._compiledEffects) {
  4493. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4494. }
  4495. for (var i in this._vertexAttribArrays) {
  4496. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4497. continue;
  4498. }
  4499. this._gl.disableVertexAttribArray(i);
  4500. }
  4501. window.removeEventListener("blur", this._onBlur);
  4502. window.removeEventListener("focus", this._onFocus);
  4503. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4504. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4505. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4506. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4507. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4508. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4509. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4510. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4511. };
  4512. Engine.prototype.displayLoadingUI = function () {
  4513. var _this = this;
  4514. this._loadingDiv = document.createElement("div");
  4515. this._loadingDiv.style.opacity = "0";
  4516. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4517. this._loadingTextDiv = document.createElement("div");
  4518. this._loadingTextDiv.style.position = "absolute";
  4519. this._loadingTextDiv.style.left = "0";
  4520. this._loadingTextDiv.style.top = "50%";
  4521. this._loadingTextDiv.style.marginTop = "80px";
  4522. this._loadingTextDiv.style.width = "100%";
  4523. this._loadingTextDiv.style.height = "20px";
  4524. this._loadingTextDiv.style.fontFamily = "Arial";
  4525. this._loadingTextDiv.style.fontSize = "14px";
  4526. this._loadingTextDiv.style.color = "white";
  4527. this._loadingTextDiv.style.textAlign = "center";
  4528. this._loadingTextDiv.innerHTML = "Loading";
  4529. this._loadingDiv.appendChild(this._loadingTextDiv);
  4530. var imgBack = new Image();
  4531. 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==";
  4532. imgBack.style.position = "absolute";
  4533. imgBack.style.left = "50%";
  4534. imgBack.style.top = "50%";
  4535. imgBack.style.marginLeft = "-50px";
  4536. imgBack.style.marginTop = "-50px";
  4537. imgBack.style.transition = "transform 1.0s ease";
  4538. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4539. var deg = 360;
  4540. var onTransitionEnd = function () {
  4541. deg += 360;
  4542. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4543. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4544. };
  4545. imgBack.addEventListener("transitionend", onTransitionEnd);
  4546. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4547. this._loadingDiv.appendChild(imgBack);
  4548. var imgFront = new Image();
  4549. 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=";
  4550. imgFront.style.position = "absolute";
  4551. imgFront.style.left = "50%";
  4552. imgFront.style.top = "50%";
  4553. imgFront.style.marginLeft = "-50px";
  4554. imgFront.style.marginTop = "-50px";
  4555. this._loadingDiv.appendChild(imgFront);
  4556. this._resizeLoadingUI = function () {
  4557. var canvasRect = _this.getRenderingCanvasClientRect();
  4558. _this._loadingDiv.style.position = "absolute";
  4559. _this._loadingDiv.style.left = canvasRect.left + "px";
  4560. _this._loadingDiv.style.top = canvasRect.top + "px";
  4561. _this._loadingDiv.style.width = canvasRect.width + "px";
  4562. _this._loadingDiv.style.height = canvasRect.height + "px";
  4563. };
  4564. this._resizeLoadingUI();
  4565. window.addEventListener("resize", this._resizeLoadingUI);
  4566. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4567. document.body.appendChild(this._loadingDiv);
  4568. setTimeout(function () {
  4569. _this._loadingDiv.style.opacity = "1";
  4570. imgBack.style.transform = "rotateZ(360deg)";
  4571. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4572. }, 0);
  4573. };
  4574. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4575. set: function (text) {
  4576. if (!this._loadingDiv) {
  4577. return;
  4578. }
  4579. this._loadingTextDiv.innerHTML = text;
  4580. },
  4581. enumerable: true,
  4582. configurable: true
  4583. });
  4584. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4585. get: function () {
  4586. return this._loadingDivBackgroundColor;
  4587. },
  4588. set: function (color) {
  4589. this._loadingDivBackgroundColor = color;
  4590. if (!this._loadingDiv) {
  4591. return;
  4592. }
  4593. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4594. },
  4595. enumerable: true,
  4596. configurable: true
  4597. });
  4598. Engine.prototype.hideLoadingUI = function () {
  4599. var _this = this;
  4600. if (!this._loadingDiv) {
  4601. return;
  4602. }
  4603. var onTransitionEnd = function () {
  4604. if (!_this._loadingDiv) {
  4605. return;
  4606. }
  4607. document.body.removeChild(_this._loadingDiv);
  4608. window.removeEventListener("resize", _this._resizeLoadingUI);
  4609. _this._loadingDiv = null;
  4610. };
  4611. this._loadingDiv.style.opacity = "0";
  4612. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4613. };
  4614. Engine.isSupported = function () {
  4615. try {
  4616. var tempcanvas = document.createElement("canvas");
  4617. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4618. return gl != null && !!window.WebGLRenderingContext;
  4619. } catch (e) {
  4620. return false;
  4621. }
  4622. };
  4623. Engine._ALPHA_DISABLE = 0;
  4624. Engine._ALPHA_ADD = 1;
  4625. Engine._ALPHA_COMBINE = 2;
  4626. Engine._DELAYLOADSTATE_NONE = 0;
  4627. Engine._DELAYLOADSTATE_LOADED = 1;
  4628. Engine._DELAYLOADSTATE_LOADING = 2;
  4629. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4630. Engine.Epsilon = 0.001;
  4631. Engine.CollisionsEpsilon = 0.001;
  4632. Engine.ShadersRepository = "Babylon/Shaders/";
  4633. return Engine;
  4634. })();
  4635. BABYLON.Engine = Engine;
  4636. })(BABYLON || (BABYLON = {}));
  4637. var BABYLON;
  4638. (function (BABYLON) {
  4639. var Node = (function () {
  4640. function Node(name, scene) {
  4641. this.state = "";
  4642. this.animations = new Array();
  4643. this._childrenFlag = -1;
  4644. this._isEnabled = true;
  4645. this._isReady = true;
  4646. this._currentRenderId = -1;
  4647. this.name = name;
  4648. this.id = name;
  4649. this._scene = scene;
  4650. this._initCache();
  4651. }
  4652. Node.prototype.getScene = function () {
  4653. return this._scene;
  4654. };
  4655. Node.prototype.getEngine = function () {
  4656. return this._scene.getEngine();
  4657. };
  4658. Node.prototype.getWorldMatrix = function () {
  4659. return BABYLON.Matrix.Identity();
  4660. };
  4661. Node.prototype._initCache = function () {
  4662. this._cache = {};
  4663. this._cache.parent = undefined;
  4664. };
  4665. Node.prototype.updateCache = function (force) {
  4666. if (!force && this.isSynchronized())
  4667. return;
  4668. this._cache.parent = this.parent;
  4669. this._updateCache();
  4670. };
  4671. Node.prototype._updateCache = function (ignoreParentClass) {
  4672. };
  4673. Node.prototype._isSynchronized = function () {
  4674. return true;
  4675. };
  4676. Node.prototype.isSynchronizedWithParent = function () {
  4677. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4678. };
  4679. Node.prototype.isSynchronized = function (updateCache) {
  4680. var check = this.hasNewParent();
  4681. check = check || !this.isSynchronizedWithParent();
  4682. check = check || !this._isSynchronized();
  4683. if (updateCache)
  4684. this.updateCache(true);
  4685. return !check;
  4686. };
  4687. Node.prototype.hasNewParent = function (update) {
  4688. if (this._cache.parent === this.parent)
  4689. return false;
  4690. if (update)
  4691. this._cache.parent = this.parent;
  4692. return true;
  4693. };
  4694. Node.prototype.isReady = function () {
  4695. return this._isReady;
  4696. };
  4697. Node.prototype.isEnabled = function () {
  4698. if (!this._isEnabled) {
  4699. return false;
  4700. }
  4701. if (this.parent) {
  4702. return this.parent.isEnabled();
  4703. }
  4704. return true;
  4705. };
  4706. Node.prototype.setEnabled = function (value) {
  4707. this._isEnabled = value;
  4708. };
  4709. Node.prototype.isDescendantOf = function (ancestor) {
  4710. if (this.parent) {
  4711. if (this.parent === ancestor) {
  4712. return true;
  4713. }
  4714. return this.parent.isDescendantOf(ancestor);
  4715. }
  4716. return false;
  4717. };
  4718. Node.prototype._getDescendants = function (list, results) {
  4719. for (var index = 0; index < list.length; index++) {
  4720. var item = list[index];
  4721. if (item.isDescendantOf(this)) {
  4722. results.push(item);
  4723. }
  4724. }
  4725. };
  4726. Node.prototype.getDescendants = function () {
  4727. var results = [];
  4728. this._getDescendants(this._scene.meshes, results);
  4729. this._getDescendants(this._scene.lights, results);
  4730. this._getDescendants(this._scene.cameras, results);
  4731. return results;
  4732. };
  4733. Node.prototype._setReady = function (state) {
  4734. if (state == this._isReady) {
  4735. return;
  4736. }
  4737. if (!state) {
  4738. this._isReady = false;
  4739. return;
  4740. }
  4741. this._isReady = true;
  4742. if (this.onReady) {
  4743. this.onReady(this);
  4744. }
  4745. };
  4746. return Node;
  4747. })();
  4748. BABYLON.Node = Node;
  4749. })(BABYLON || (BABYLON = {}));
  4750. var BABYLON;
  4751. (function (BABYLON) {
  4752. var FilesInput = (function () {
  4753. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  4754. this.engine = p_engine;
  4755. this.canvas = p_canvas;
  4756. this.currentScene = p_scene;
  4757. this.sceneLoadedCallback = p_sceneLoadedCallback;
  4758. this.progressCallback = p_progressCallback;
  4759. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  4760. this.textureLoadingCallback = p_textureLoadingCallback;
  4761. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  4762. }
  4763. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  4764. var _this = this;
  4765. if (p_elementToMonitor) {
  4766. this.elementToMonitor = p_elementToMonitor;
  4767. this.elementToMonitor.addEventListener("dragenter", function (e) {
  4768. _this.drag(e);
  4769. }, false);
  4770. this.elementToMonitor.addEventListener("dragover", function (e) {
  4771. _this.drag(e);
  4772. }, false);
  4773. this.elementToMonitor.addEventListener("drop", function (e) {
  4774. _this.drop(e);
  4775. }, false);
  4776. }
  4777. };
  4778. FilesInput.prototype.renderFunction = function () {
  4779. if (this.additionnalRenderLoopLogicCallback) {
  4780. this.additionnalRenderLoopLogicCallback();
  4781. }
  4782. if (this.currentScene) {
  4783. if (this.textureLoadingCallback) {
  4784. var remaining = this.currentScene.getWaitingItemsCount();
  4785. if (remaining > 0) {
  4786. this.textureLoadingCallback(remaining);
  4787. }
  4788. }
  4789. this.currentScene.render();
  4790. }
  4791. };
  4792. FilesInput.prototype.drag = function (e) {
  4793. e.stopPropagation();
  4794. e.preventDefault();
  4795. };
  4796. FilesInput.prototype.drop = function (eventDrop) {
  4797. eventDrop.stopPropagation();
  4798. eventDrop.preventDefault();
  4799. this.loadFiles(eventDrop);
  4800. };
  4801. FilesInput.prototype.loadFiles = function (event) {
  4802. var _this = this;
  4803. var that = this;
  4804. if (this.startingProcessingFilesCallback)
  4805. this.startingProcessingFilesCallback();
  4806. var sceneFileToLoad;
  4807. var filesToLoad;
  4808. if (event && event.dataTransfer && event.dataTransfer.files) {
  4809. filesToLoad = event.dataTransfer.files;
  4810. }
  4811. if (event && event.target && event.target.files) {
  4812. filesToLoad = event.target.files;
  4813. }
  4814. if (filesToLoad && filesToLoad.length > 0) {
  4815. for (var i = 0; i < filesToLoad.length; i++) {
  4816. switch (filesToLoad[i].type) {
  4817. case "image/jpeg":
  4818. case "image/png":
  4819. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  4820. break;
  4821. case "image/targa":
  4822. case "image/vnd.ms-dds":
  4823. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  4824. break;
  4825. default:
  4826. 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) {
  4827. sceneFileToLoad = filesToLoad[i];
  4828. }
  4829. break;
  4830. }
  4831. }
  4832. if (sceneFileToLoad) {
  4833. if (this.currentScene) {
  4834. this.engine.stopRenderLoop();
  4835. this.currentScene.dispose();
  4836. }
  4837. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  4838. that.currentScene = newScene;
  4839. that.currentScene.executeWhenReady(function () {
  4840. if (that.currentScene.activeCamera) {
  4841. that.currentScene.activeCamera.attachControl(that.canvas);
  4842. }
  4843. if (that.sceneLoadedCallback) {
  4844. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  4845. }
  4846. that.engine.runRenderLoop(function () {
  4847. that.renderFunction();
  4848. });
  4849. });
  4850. }, function (progress) {
  4851. if (_this.progressCallback) {
  4852. _this.progressCallback(progress);
  4853. }
  4854. });
  4855. } else {
  4856. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  4857. }
  4858. }
  4859. };
  4860. FilesInput.FilesTextures = new Array();
  4861. FilesInput.FilesToLoad = new Array();
  4862. return FilesInput;
  4863. })();
  4864. BABYLON.FilesInput = FilesInput;
  4865. })(BABYLON || (BABYLON = {}));
  4866. var BABYLON;
  4867. (function (BABYLON) {
  4868. var BoundingSphere = (function () {
  4869. function BoundingSphere(minimum, maximum) {
  4870. this.minimum = minimum;
  4871. this.maximum = maximum;
  4872. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4873. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4874. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4875. this.radius = distance * 0.5;
  4876. this.centerWorld = BABYLON.Vector3.Zero();
  4877. this._update(BABYLON.Matrix.Identity());
  4878. }
  4879. BoundingSphere.prototype._update = function (world) {
  4880. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4881. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4882. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4883. };
  4884. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4885. for (var i = 0; i < 6; i++) {
  4886. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4887. return false;
  4888. }
  4889. return true;
  4890. };
  4891. BoundingSphere.prototype.intersectsPoint = function (point) {
  4892. var x = this.centerWorld.x - point.x;
  4893. var y = this.centerWorld.y - point.y;
  4894. var z = this.centerWorld.z - point.z;
  4895. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4896. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4897. return false;
  4898. return true;
  4899. };
  4900. BoundingSphere.Intersects = function (sphere0, sphere1) {
  4901. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  4902. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  4903. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  4904. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4905. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  4906. return false;
  4907. return true;
  4908. };
  4909. return BoundingSphere;
  4910. })();
  4911. BABYLON.BoundingSphere = BoundingSphere;
  4912. })(BABYLON || (BABYLON = {}));
  4913. var BABYLON;
  4914. (function (BABYLON) {
  4915. var BoundingBox = (function () {
  4916. function BoundingBox(minimum, maximum) {
  4917. this.minimum = minimum;
  4918. this.maximum = maximum;
  4919. this.vectors = new Array();
  4920. this.vectorsWorld = new Array();
  4921. this.vectors.push(this.minimum.clone());
  4922. this.vectors.push(this.maximum.clone());
  4923. this.vectors.push(this.minimum.clone());
  4924. this.vectors[2].x = this.maximum.x;
  4925. this.vectors.push(this.minimum.clone());
  4926. this.vectors[3].y = this.maximum.y;
  4927. this.vectors.push(this.minimum.clone());
  4928. this.vectors[4].z = this.maximum.z;
  4929. this.vectors.push(this.maximum.clone());
  4930. this.vectors[5].z = this.minimum.z;
  4931. this.vectors.push(this.maximum.clone());
  4932. this.vectors[6].x = this.minimum.x;
  4933. this.vectors.push(this.maximum.clone());
  4934. this.vectors[7].y = this.minimum.y;
  4935. this.center = this.maximum.add(this.minimum).scale(0.5);
  4936. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  4937. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  4938. for (var index = 0; index < this.vectors.length; index++) {
  4939. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  4940. }
  4941. this.minimumWorld = BABYLON.Vector3.Zero();
  4942. this.maximumWorld = BABYLON.Vector3.Zero();
  4943. this._update(BABYLON.Matrix.Identity());
  4944. }
  4945. BoundingBox.prototype.getWorldMatrix = function () {
  4946. return this._worldMatrix;
  4947. };
  4948. BoundingBox.prototype._update = function (world) {
  4949. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  4950. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  4951. for (var index = 0; index < this.vectors.length; index++) {
  4952. var v = this.vectorsWorld[index];
  4953. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  4954. if (v.x < this.minimumWorld.x)
  4955. this.minimumWorld.x = v.x;
  4956. if (v.y < this.minimumWorld.y)
  4957. this.minimumWorld.y = v.y;
  4958. if (v.z < this.minimumWorld.z)
  4959. this.minimumWorld.z = v.z;
  4960. if (v.x > this.maximumWorld.x)
  4961. this.maximumWorld.x = v.x;
  4962. if (v.y > this.maximumWorld.y)
  4963. this.maximumWorld.y = v.y;
  4964. if (v.z > this.maximumWorld.z)
  4965. this.maximumWorld.z = v.z;
  4966. }
  4967. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  4968. this.center.scaleInPlace(0.5);
  4969. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  4970. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  4971. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  4972. this._worldMatrix = world;
  4973. };
  4974. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  4975. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  4976. };
  4977. BoundingBox.prototype.intersectsPoint = function (point) {
  4978. var delta = BABYLON.Engine.Epsilon;
  4979. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  4980. return false;
  4981. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  4982. return false;
  4983. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  4984. return false;
  4985. return true;
  4986. };
  4987. BoundingBox.prototype.intersectsSphere = function (sphere) {
  4988. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  4989. };
  4990. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  4991. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  4992. return false;
  4993. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  4994. return false;
  4995. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  4996. return false;
  4997. return true;
  4998. };
  4999. BoundingBox.Intersects = function (box0, box1) {
  5000. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5001. return false;
  5002. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5003. return false;
  5004. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5005. return false;
  5006. return true;
  5007. };
  5008. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5009. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5010. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5011. return (num <= (sphereRadius * sphereRadius));
  5012. };
  5013. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5014. for (var p = 0; p < 6; p++) {
  5015. var inCount = 8;
  5016. for (var i = 0; i < 8; i++) {
  5017. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5018. --inCount;
  5019. } else {
  5020. break;
  5021. }
  5022. }
  5023. if (inCount == 0)
  5024. return false;
  5025. }
  5026. return true;
  5027. };
  5028. return BoundingBox;
  5029. })();
  5030. BABYLON.BoundingBox = BoundingBox;
  5031. })(BABYLON || (BABYLON = {}));
  5032. var BABYLON;
  5033. (function (BABYLON) {
  5034. var computeBoxExtents = function (axis, box) {
  5035. var p = BABYLON.Vector3.Dot(box.center, axis);
  5036. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5037. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5038. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5039. var r = r0 + r1 + r2;
  5040. return {
  5041. min: p - r,
  5042. max: p + r
  5043. };
  5044. };
  5045. var extentsOverlap = function (min0, max0, min1, max1) {
  5046. return !(min0 > max1 || min1 > max0);
  5047. };
  5048. var axisOverlap = function (axis, box0, box1) {
  5049. var result0 = computeBoxExtents(axis, box0);
  5050. var result1 = computeBoxExtents(axis, box1);
  5051. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5052. };
  5053. var BoundingInfo = (function () {
  5054. function BoundingInfo(minimum, maximum) {
  5055. this.minimum = minimum;
  5056. this.maximum = maximum;
  5057. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5058. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5059. }
  5060. BoundingInfo.prototype._update = function (world) {
  5061. this.boundingBox._update(world);
  5062. this.boundingSphere._update(world);
  5063. };
  5064. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5065. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5066. return false;
  5067. return this.boundingBox.isInFrustum(frustumPlanes);
  5068. };
  5069. BoundingInfo.prototype._checkCollision = function (collider) {
  5070. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5071. };
  5072. BoundingInfo.prototype.intersectsPoint = function (point) {
  5073. if (!this.boundingSphere.centerWorld) {
  5074. return false;
  5075. }
  5076. if (!this.boundingSphere.intersectsPoint(point)) {
  5077. return false;
  5078. }
  5079. if (!this.boundingBox.intersectsPoint(point)) {
  5080. return false;
  5081. }
  5082. return true;
  5083. };
  5084. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5085. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5086. return false;
  5087. }
  5088. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5089. return false;
  5090. }
  5091. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5092. return false;
  5093. }
  5094. if (!precise) {
  5095. return true;
  5096. }
  5097. var box0 = this.boundingBox;
  5098. var box1 = boundingInfo.boundingBox;
  5099. if (!axisOverlap(box0.directions[0], box0, box1))
  5100. return false;
  5101. if (!axisOverlap(box0.directions[1], box0, box1))
  5102. return false;
  5103. if (!axisOverlap(box0.directions[2], box0, box1))
  5104. return false;
  5105. if (!axisOverlap(box1.directions[0], box0, box1))
  5106. return false;
  5107. if (!axisOverlap(box1.directions[1], box0, box1))
  5108. return false;
  5109. if (!axisOverlap(box1.directions[2], box0, box1))
  5110. return false;
  5111. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5112. return false;
  5113. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5114. return false;
  5115. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5116. return false;
  5117. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5118. return false;
  5119. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5120. return false;
  5121. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5122. return false;
  5123. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5124. return false;
  5125. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5126. return false;
  5127. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5128. return false;
  5129. return true;
  5130. };
  5131. return BoundingInfo;
  5132. })();
  5133. BABYLON.BoundingInfo = BoundingInfo;
  5134. })(BABYLON || (BABYLON = {}));
  5135. var BABYLON;
  5136. (function (BABYLON) {
  5137. var IntersectionInfo = (function () {
  5138. function IntersectionInfo(bu, bv, distance) {
  5139. this.bu = bu;
  5140. this.bv = bv;
  5141. this.distance = distance;
  5142. this.faceId = 0;
  5143. }
  5144. return IntersectionInfo;
  5145. })();
  5146. BABYLON.IntersectionInfo = IntersectionInfo;
  5147. var PickingInfo = (function () {
  5148. function PickingInfo() {
  5149. this.hit = false;
  5150. this.distance = 0;
  5151. this.pickedPoint = null;
  5152. this.pickedMesh = null;
  5153. this.bu = 0;
  5154. this.bv = 0;
  5155. this.faceId = -1;
  5156. }
  5157. PickingInfo.prototype.getNormal = function () {
  5158. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  5159. return null;
  5160. }
  5161. var indices = this.pickedMesh.getIndices();
  5162. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  5163. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  5164. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  5165. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  5166. normal0 = normal0.scale(this.bu);
  5167. normal1 = normal1.scale(this.bv);
  5168. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  5169. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  5170. };
  5171. PickingInfo.prototype.getTextureCoordinates = function () {
  5172. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5173. return null;
  5174. }
  5175. var indices = this.pickedMesh.getIndices();
  5176. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  5177. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  5178. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  5179. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  5180. uv0 = uv0.scale(this.bu);
  5181. uv1 = uv1.scale(this.bv);
  5182. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  5183. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  5184. };
  5185. return PickingInfo;
  5186. })();
  5187. BABYLON.PickingInfo = PickingInfo;
  5188. })(BABYLON || (BABYLON = {}));
  5189. var __extends = this.__extends || function (d, b) {
  5190. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5191. function __() { this.constructor = d; }
  5192. __.prototype = b.prototype;
  5193. d.prototype = new __();
  5194. };
  5195. var BABYLON;
  5196. (function (BABYLON) {
  5197. var AbstractMesh = (function (_super) {
  5198. __extends(AbstractMesh, _super);
  5199. function AbstractMesh(name, scene) {
  5200. _super.call(this, name, scene);
  5201. this.position = new BABYLON.Vector3(0, 0, 0);
  5202. this.rotation = new BABYLON.Vector3(0, 0, 0);
  5203. this.scaling = new BABYLON.Vector3(1, 1, 1);
  5204. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  5205. this.visibility = 1.0;
  5206. this.infiniteDistance = false;
  5207. this.isVisible = true;
  5208. this.isPickable = true;
  5209. this.showBoundingBox = false;
  5210. this.showSubMeshesBoundingBox = false;
  5211. this.onDispose = null;
  5212. this.checkCollisions = false;
  5213. this.isBlocker = false;
  5214. this.renderingGroupId = 0;
  5215. this.receiveShadows = false;
  5216. this.renderOutline = false;
  5217. this.outlineColor = BABYLON.Color3.Red();
  5218. this.outlineWidth = 0.02;
  5219. this.useOctreeForRenderingSelection = true;
  5220. this.useOctreeForPicking = true;
  5221. this.useOctreeForCollisions = true;
  5222. this.layerMask = 0xFFFFFFFF;
  5223. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  5224. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5225. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  5226. this._collider = new BABYLON.Collider();
  5227. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  5228. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  5229. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  5230. this._localScaling = BABYLON.Matrix.Zero();
  5231. this._localRotation = BABYLON.Matrix.Zero();
  5232. this._localTranslation = BABYLON.Matrix.Zero();
  5233. this._localBillboard = BABYLON.Matrix.Zero();
  5234. this._localPivotScaling = BABYLON.Matrix.Zero();
  5235. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  5236. this._localWorld = BABYLON.Matrix.Zero();
  5237. this._worldMatrix = BABYLON.Matrix.Zero();
  5238. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  5239. this._absolutePosition = BABYLON.Vector3.Zero();
  5240. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  5241. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  5242. this._isDirty = false;
  5243. this._pivotMatrix = BABYLON.Matrix.Identity();
  5244. this._isDisposed = false;
  5245. this._renderId = 0;
  5246. this._intersectionsInProgress = new Array();
  5247. scene.meshes.push(this);
  5248. }
  5249. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  5250. get: function () {
  5251. return AbstractMesh._BILLBOARDMODE_NONE;
  5252. },
  5253. enumerable: true,
  5254. configurable: true
  5255. });
  5256. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  5257. get: function () {
  5258. return AbstractMesh._BILLBOARDMODE_X;
  5259. },
  5260. enumerable: true,
  5261. configurable: true
  5262. });
  5263. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  5264. get: function () {
  5265. return AbstractMesh._BILLBOARDMODE_Y;
  5266. },
  5267. enumerable: true,
  5268. configurable: true
  5269. });
  5270. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  5271. get: function () {
  5272. return AbstractMesh._BILLBOARDMODE_Z;
  5273. },
  5274. enumerable: true,
  5275. configurable: true
  5276. });
  5277. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  5278. get: function () {
  5279. return AbstractMesh._BILLBOARDMODE_ALL;
  5280. },
  5281. enumerable: true,
  5282. configurable: true
  5283. });
  5284. AbstractMesh.prototype.getTotalVertices = function () {
  5285. return 0;
  5286. };
  5287. AbstractMesh.prototype.getIndices = function () {
  5288. return null;
  5289. };
  5290. AbstractMesh.prototype.getVerticesData = function (kind) {
  5291. return null;
  5292. };
  5293. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  5294. return false;
  5295. };
  5296. AbstractMesh.prototype.getBoundingInfo = function () {
  5297. if (!this._boundingInfo) {
  5298. this._updateBoundingInfo();
  5299. }
  5300. return this._boundingInfo;
  5301. };
  5302. AbstractMesh.prototype._preActivate = function () {
  5303. };
  5304. AbstractMesh.prototype._activate = function (renderId) {
  5305. this._renderId = renderId;
  5306. };
  5307. AbstractMesh.prototype.getWorldMatrix = function () {
  5308. if (this._currentRenderId !== this.getScene().getRenderId()) {
  5309. this.computeWorldMatrix();
  5310. }
  5311. return this._worldMatrix;
  5312. };
  5313. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  5314. get: function () {
  5315. return this._worldMatrix;
  5316. },
  5317. enumerable: true,
  5318. configurable: true
  5319. });
  5320. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  5321. get: function () {
  5322. return this._absolutePosition;
  5323. },
  5324. enumerable: true,
  5325. configurable: true
  5326. });
  5327. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  5328. if (!this.rotationQuaternion) {
  5329. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  5330. this.rotation = BABYLON.Vector3.Zero();
  5331. }
  5332. if (!space || space == 0 /* LOCAL */) {
  5333. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  5334. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  5335. } else {
  5336. if (this.parent) {
  5337. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  5338. invertParentWorldMatrix.invert();
  5339. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  5340. }
  5341. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  5342. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  5343. }
  5344. };
  5345. AbstractMesh.prototype.translate = function (axis, distance, space) {
  5346. var displacementVector = axis.scale(distance);
  5347. if (!space || space == 0 /* LOCAL */) {
  5348. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  5349. this.setPositionWithLocalVector(tempV3);
  5350. } else {
  5351. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  5352. }
  5353. };
  5354. AbstractMesh.prototype.getAbsolutePosition = function () {
  5355. this.computeWorldMatrix();
  5356. return this._absolutePosition;
  5357. };
  5358. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  5359. if (!absolutePosition) {
  5360. return;
  5361. }
  5362. var absolutePositionX;
  5363. var absolutePositionY;
  5364. var absolutePositionZ;
  5365. if (absolutePosition.x === undefined) {
  5366. if (arguments.length < 3) {
  5367. return;
  5368. }
  5369. absolutePositionX = arguments[0];
  5370. absolutePositionY = arguments[1];
  5371. absolutePositionZ = arguments[2];
  5372. } else {
  5373. absolutePositionX = absolutePosition.x;
  5374. absolutePositionY = absolutePosition.y;
  5375. absolutePositionZ = absolutePosition.z;
  5376. }
  5377. if (this.parent) {
  5378. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  5379. invertParentWorldMatrix.invert();
  5380. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  5381. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  5382. } else {
  5383. this.position.x = absolutePositionX;
  5384. this.position.y = absolutePositionY;
  5385. this.position.z = absolutePositionZ;
  5386. }
  5387. };
  5388. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  5389. this._pivotMatrix = matrix;
  5390. this._cache.pivotMatrixUpdated = true;
  5391. };
  5392. AbstractMesh.prototype.getPivotMatrix = function () {
  5393. return this._pivotMatrix;
  5394. };
  5395. AbstractMesh.prototype._isSynchronized = function () {
  5396. if (this._isDirty) {
  5397. return false;
  5398. }
  5399. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  5400. return false;
  5401. if (this._cache.pivotMatrixUpdated) {
  5402. return false;
  5403. }
  5404. if (this.infiniteDistance) {
  5405. return false;
  5406. }
  5407. if (!this._cache.position.equals(this.position))
  5408. return false;
  5409. if (this.rotationQuaternion) {
  5410. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  5411. return false;
  5412. } else {
  5413. if (!this._cache.rotation.equals(this.rotation))
  5414. return false;
  5415. }
  5416. if (!this._cache.scaling.equals(this.scaling))
  5417. return false;
  5418. return true;
  5419. };
  5420. AbstractMesh.prototype._initCache = function () {
  5421. _super.prototype._initCache.call(this);
  5422. this._cache.localMatrixUpdated = false;
  5423. this._cache.position = BABYLON.Vector3.Zero();
  5424. this._cache.scaling = BABYLON.Vector3.Zero();
  5425. this._cache.rotation = BABYLON.Vector3.Zero();
  5426. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  5427. };
  5428. AbstractMesh.prototype.markAsDirty = function (property) {
  5429. if (property === "rotation") {
  5430. this.rotationQuaternion = null;
  5431. }
  5432. this._currentRenderId = Number.MAX_VALUE;
  5433. this._isDirty = true;
  5434. };
  5435. AbstractMesh.prototype._updateBoundingInfo = function () {
  5436. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  5437. this._boundingInfo._update(this.worldMatrixFromCache);
  5438. if (!this.subMeshes) {
  5439. return;
  5440. }
  5441. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  5442. var subMesh = this.subMeshes[subIndex];
  5443. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  5444. }
  5445. };
  5446. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  5447. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  5448. return this._worldMatrix;
  5449. }
  5450. this._cache.position.copyFrom(this.position);
  5451. this._cache.scaling.copyFrom(this.scaling);
  5452. this._cache.pivotMatrixUpdated = false;
  5453. this._currentRenderId = this.getScene().getRenderId();
  5454. this._isDirty = false;
  5455. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  5456. if (this.rotationQuaternion) {
  5457. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  5458. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  5459. } else {
  5460. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  5461. this._cache.rotation.copyFrom(this.rotation);
  5462. }
  5463. if (this.infiniteDistance && !this.parent) {
  5464. var camera = this.getScene().activeCamera;
  5465. var cameraWorldMatrix = camera.getWorldMatrix();
  5466. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  5467. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  5468. } else {
  5469. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  5470. }
  5471. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  5472. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  5473. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  5474. var localPosition = this.position.clone();
  5475. var zero = this.getScene().activeCamera.position.clone();
  5476. if (this.parent && this.parent.position) {
  5477. localPosition.addInPlace(this.parent.position);
  5478. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  5479. }
  5480. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  5481. zero = this.getScene().activeCamera.position;
  5482. } else {
  5483. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  5484. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  5485. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  5486. zero.y = localPosition.y + 0.001;
  5487. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  5488. zero.z = localPosition.z + 0.001;
  5489. }
  5490. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  5491. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  5492. this._localBillboard.invert();
  5493. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  5494. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  5495. }
  5496. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  5497. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  5498. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  5499. } else {
  5500. this._worldMatrix.copyFrom(this._localWorld);
  5501. }
  5502. this._updateBoundingInfo();
  5503. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  5504. return this._worldMatrix;
  5505. };
  5506. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  5507. this.computeWorldMatrix();
  5508. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  5509. };
  5510. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  5511. this.computeWorldMatrix();
  5512. var invLocalWorldMatrix = this._localWorld.clone();
  5513. invLocalWorldMatrix.invert();
  5514. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  5515. };
  5516. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  5517. this.computeWorldMatrix();
  5518. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  5519. };
  5520. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  5521. yawCor = yawCor || 0;
  5522. pitchCor = pitchCor || 0;
  5523. rollCor = rollCor || 0;
  5524. var dv = targetPoint.subtract(this.position);
  5525. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  5526. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  5527. var pitch = Math.atan2(dv.y, len);
  5528. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  5529. };
  5530. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  5531. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  5532. return false;
  5533. }
  5534. return true;
  5535. };
  5536. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  5537. if (!this._boundingInfo || !mesh._boundingInfo) {
  5538. return false;
  5539. }
  5540. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  5541. };
  5542. AbstractMesh.prototype.intersectsPoint = function (point) {
  5543. if (!this._boundingInfo) {
  5544. return false;
  5545. }
  5546. return this._boundingInfo.intersectsPoint(point);
  5547. };
  5548. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  5549. var physicsEngine = this.getScene().getPhysicsEngine();
  5550. if (!physicsEngine) {
  5551. return;
  5552. }
  5553. if (impostor.impostor) {
  5554. options = impostor;
  5555. impostor = impostor.impostor;
  5556. }
  5557. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  5558. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  5559. physicsEngine._unregisterMesh(this);
  5560. return;
  5561. }
  5562. options.mass = options.mass || 0;
  5563. options.friction = options.friction || 0.2;
  5564. options.restitution = options.restitution || 0.2;
  5565. this._physicImpostor = impostor;
  5566. this._physicsMass = options.mass;
  5567. this._physicsFriction = options.friction;
  5568. this._physicRestitution = options.restitution;
  5569. physicsEngine._registerMesh(this, impostor, options);
  5570. };
  5571. AbstractMesh.prototype.getPhysicsImpostor = function () {
  5572. if (!this._physicImpostor) {
  5573. return BABYLON.PhysicsEngine.NoImpostor;
  5574. }
  5575. return this._physicImpostor;
  5576. };
  5577. AbstractMesh.prototype.getPhysicsMass = function () {
  5578. if (!this._physicsMass) {
  5579. return 0;
  5580. }
  5581. return this._physicsMass;
  5582. };
  5583. AbstractMesh.prototype.getPhysicsFriction = function () {
  5584. if (!this._physicsFriction) {
  5585. return 0;
  5586. }
  5587. return this._physicsFriction;
  5588. };
  5589. AbstractMesh.prototype.getPhysicsRestitution = function () {
  5590. if (!this._physicRestitution) {
  5591. return 0;
  5592. }
  5593. return this._physicRestitution;
  5594. };
  5595. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  5596. if (!this._physicImpostor) {
  5597. return;
  5598. }
  5599. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  5600. };
  5601. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  5602. if (!this._physicImpostor) {
  5603. return;
  5604. }
  5605. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  5606. };
  5607. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  5608. if (!this._physicImpostor) {
  5609. return;
  5610. }
  5611. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  5612. };
  5613. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  5614. var globalPosition = this.getAbsolutePosition();
  5615. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  5616. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  5617. this._collider.radius = this.ellipsoid;
  5618. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  5619. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  5620. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  5621. this.position.addInPlace(this._diffPositionForCollisions);
  5622. }
  5623. };
  5624. /**
  5625. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  5626. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  5627. */
  5628. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  5629. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  5630. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  5631. if (!this._submeshesOctree) {
  5632. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  5633. }
  5634. this.computeWorldMatrix(true);
  5635. var bbox = this.getBoundingInfo().boundingBox;
  5636. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  5637. return this._submeshesOctree;
  5638. };
  5639. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  5640. this._generatePointsArray();
  5641. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  5642. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  5643. subMesh._lastColliderWorldVertices = [];
  5644. subMesh._trianglePlanes = [];
  5645. var start = subMesh.verticesStart;
  5646. var end = (subMesh.verticesStart + subMesh.verticesCount);
  5647. for (var i = start; i < end; i++) {
  5648. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  5649. }
  5650. }
  5651. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  5652. };
  5653. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  5654. var subMeshes;
  5655. var len;
  5656. if (this._submeshesOctree && this.useOctreeForCollisions) {
  5657. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  5658. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  5659. len = intersections.length;
  5660. subMeshes = intersections.data;
  5661. } else {
  5662. subMeshes = this.subMeshes;
  5663. len = subMeshes.length;
  5664. }
  5665. for (var index = 0; index < len; index++) {
  5666. var subMesh = subMeshes[index];
  5667. if (len > 1 && !subMesh._checkCollision(collider))
  5668. continue;
  5669. this._collideForSubMesh(subMesh, transformMatrix, collider);
  5670. }
  5671. };
  5672. AbstractMesh.prototype._checkCollision = function (collider) {
  5673. if (!this._boundingInfo._checkCollision(collider))
  5674. return;
  5675. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  5676. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  5677. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  5678. };
  5679. AbstractMesh.prototype._generatePointsArray = function () {
  5680. return false;
  5681. };
  5682. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  5683. var pickingInfo = new BABYLON.PickingInfo();
  5684. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  5685. return pickingInfo;
  5686. }
  5687. if (!this._generatePointsArray()) {
  5688. return pickingInfo;
  5689. }
  5690. var intersectInfo = null;
  5691. var subMeshes;
  5692. var len;
  5693. if (this._submeshesOctree && this.useOctreeForPicking) {
  5694. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  5695. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  5696. len = intersections.length;
  5697. subMeshes = intersections.data;
  5698. } else {
  5699. subMeshes = this.subMeshes;
  5700. len = subMeshes.length;
  5701. }
  5702. for (var index = 0; index < len; index++) {
  5703. var subMesh = subMeshes[index];
  5704. if (len > 1 && !subMesh.canIntersects(ray))
  5705. continue;
  5706. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  5707. if (currentIntersectInfo) {
  5708. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  5709. intersectInfo = currentIntersectInfo;
  5710. if (fastCheck) {
  5711. break;
  5712. }
  5713. }
  5714. }
  5715. }
  5716. if (intersectInfo) {
  5717. var world = this.getWorldMatrix();
  5718. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  5719. var direction = ray.direction.clone();
  5720. direction.normalize();
  5721. direction = direction.scale(intersectInfo.distance);
  5722. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  5723. var pickedPoint = worldOrigin.add(worldDirection);
  5724. pickingInfo.hit = true;
  5725. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  5726. pickingInfo.pickedPoint = pickedPoint;
  5727. pickingInfo.pickedMesh = this;
  5728. pickingInfo.bu = intersectInfo.bu;
  5729. pickingInfo.bv = intersectInfo.bv;
  5730. pickingInfo.faceId = intersectInfo.faceId;
  5731. return pickingInfo;
  5732. }
  5733. return pickingInfo;
  5734. };
  5735. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  5736. return null;
  5737. };
  5738. AbstractMesh.prototype.releaseSubMeshes = function () {
  5739. if (this.subMeshes) {
  5740. while (this.subMeshes.length) {
  5741. this.subMeshes[0].dispose();
  5742. }
  5743. } else {
  5744. this.subMeshes = new Array();
  5745. }
  5746. };
  5747. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  5748. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  5749. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  5750. }
  5751. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  5752. var other = this._intersectionsInProgress[index];
  5753. var pos = other._intersectionsInProgress.indexOf(this);
  5754. other._intersectionsInProgress.splice(pos, 1);
  5755. }
  5756. this._intersectionsInProgress = [];
  5757. this.releaseSubMeshes();
  5758. var index = this.getScene().meshes.indexOf(this);
  5759. if (index != -1) {
  5760. this.getScene().meshes.splice(index, 1);
  5761. }
  5762. if (!doNotRecurse) {
  5763. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  5764. if (this.getScene().particleSystems[index].emitter == this) {
  5765. this.getScene().particleSystems[index].dispose();
  5766. index--;
  5767. }
  5768. }
  5769. var objects = this.getScene().meshes.slice(0);
  5770. for (index = 0; index < objects.length; index++) {
  5771. if (objects[index].parent == this) {
  5772. objects[index].dispose();
  5773. }
  5774. }
  5775. } else {
  5776. for (index = 0; index < this.getScene().meshes.length; index++) {
  5777. var obj = this.getScene().meshes[index];
  5778. if (obj.parent === this) {
  5779. obj.parent = null;
  5780. obj.computeWorldMatrix(true);
  5781. }
  5782. }
  5783. }
  5784. this._isDisposed = true;
  5785. if (this.onDispose) {
  5786. this.onDispose();
  5787. }
  5788. };
  5789. AbstractMesh._BILLBOARDMODE_NONE = 0;
  5790. AbstractMesh._BILLBOARDMODE_X = 1;
  5791. AbstractMesh._BILLBOARDMODE_Y = 2;
  5792. AbstractMesh._BILLBOARDMODE_Z = 4;
  5793. AbstractMesh._BILLBOARDMODE_ALL = 7;
  5794. return AbstractMesh;
  5795. })(BABYLON.Node);
  5796. BABYLON.AbstractMesh = AbstractMesh;
  5797. })(BABYLON || (BABYLON = {}));
  5798. var __extends = this.__extends || function (d, b) {
  5799. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5800. function __() { this.constructor = d; }
  5801. __.prototype = b.prototype;
  5802. d.prototype = new __();
  5803. };
  5804. var BABYLON;
  5805. (function (BABYLON) {
  5806. var Light = (function (_super) {
  5807. __extends(Light, _super);
  5808. function Light(name, scene) {
  5809. _super.call(this, name, scene);
  5810. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5811. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5812. this.intensity = 1.0;
  5813. this.range = Number.MAX_VALUE;
  5814. this.includedOnlyMeshes = new Array();
  5815. this.excludedMeshes = new Array();
  5816. this._excludedMeshesIds = new Array();
  5817. this._includedOnlyMeshesIds = new Array();
  5818. scene.lights.push(this);
  5819. }
  5820. Light.prototype.getShadowGenerator = function () {
  5821. return this._shadowGenerator;
  5822. };
  5823. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5824. };
  5825. Light.prototype._getWorldMatrix = function () {
  5826. return BABYLON.Matrix.Identity();
  5827. };
  5828. Light.prototype.canAffectMesh = function (mesh) {
  5829. if (!mesh) {
  5830. return true;
  5831. }
  5832. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5833. return false;
  5834. }
  5835. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5836. return false;
  5837. }
  5838. return true;
  5839. };
  5840. Light.prototype.getWorldMatrix = function () {
  5841. this._currentRenderId = this.getScene().getRenderId();
  5842. var worldMatrix = this._getWorldMatrix();
  5843. if (this.parent && this.parent.getWorldMatrix) {
  5844. if (!this._parentedWorldMatrix) {
  5845. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5846. }
  5847. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5848. return this._parentedWorldMatrix;
  5849. }
  5850. return worldMatrix;
  5851. };
  5852. Light.prototype.dispose = function () {
  5853. if (this._shadowGenerator) {
  5854. this._shadowGenerator.dispose();
  5855. this._shadowGenerator = null;
  5856. }
  5857. var index = this.getScene().lights.indexOf(this);
  5858. this.getScene().lights.splice(index, 1);
  5859. };
  5860. return Light;
  5861. })(BABYLON.Node);
  5862. BABYLON.Light = Light;
  5863. })(BABYLON || (BABYLON = {}));
  5864. var __extends = this.__extends || function (d, b) {
  5865. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5866. function __() { this.constructor = d; }
  5867. __.prototype = b.prototype;
  5868. d.prototype = new __();
  5869. };
  5870. var BABYLON;
  5871. (function (BABYLON) {
  5872. var PointLight = (function (_super) {
  5873. __extends(PointLight, _super);
  5874. function PointLight(name, position, scene) {
  5875. _super.call(this, name, scene);
  5876. this.position = position;
  5877. }
  5878. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5879. if (this.parent && this.parent.getWorldMatrix) {
  5880. if (!this._transformedPosition) {
  5881. this._transformedPosition = BABYLON.Vector3.Zero();
  5882. }
  5883. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5884. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5885. return;
  5886. }
  5887. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5888. };
  5889. PointLight.prototype.getShadowGenerator = function () {
  5890. return null;
  5891. };
  5892. PointLight.prototype._getWorldMatrix = function () {
  5893. if (!this._worldMatrix) {
  5894. this._worldMatrix = BABYLON.Matrix.Identity();
  5895. }
  5896. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5897. return this._worldMatrix;
  5898. };
  5899. return PointLight;
  5900. })(BABYLON.Light);
  5901. BABYLON.PointLight = PointLight;
  5902. })(BABYLON || (BABYLON = {}));
  5903. var __extends = this.__extends || function (d, b) {
  5904. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5905. function __() { this.constructor = d; }
  5906. __.prototype = b.prototype;
  5907. d.prototype = new __();
  5908. };
  5909. var BABYLON;
  5910. (function (BABYLON) {
  5911. var SpotLight = (function (_super) {
  5912. __extends(SpotLight, _super);
  5913. function SpotLight(name, position, direction, angle, exponent, scene) {
  5914. _super.call(this, name, scene);
  5915. this.position = position;
  5916. this.direction = direction;
  5917. this.angle = angle;
  5918. this.exponent = exponent;
  5919. }
  5920. SpotLight.prototype.setDirectionToTarget = function (target) {
  5921. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5922. return this.direction;
  5923. };
  5924. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5925. var normalizeDirection;
  5926. if (this.parent && this.parent.getWorldMatrix) {
  5927. if (!this._transformedDirection) {
  5928. this._transformedDirection = BABYLON.Vector3.Zero();
  5929. }
  5930. if (!this._transformedPosition) {
  5931. this._transformedPosition = BABYLON.Vector3.Zero();
  5932. }
  5933. var parentWorldMatrix = this.parent.getWorldMatrix();
  5934. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  5935. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  5936. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  5937. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5938. } else {
  5939. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5940. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5941. }
  5942. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5943. };
  5944. SpotLight.prototype._getWorldMatrix = function () {
  5945. if (!this._worldMatrix) {
  5946. this._worldMatrix = BABYLON.Matrix.Identity();
  5947. }
  5948. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5949. return this._worldMatrix;
  5950. };
  5951. return SpotLight;
  5952. })(BABYLON.Light);
  5953. BABYLON.SpotLight = SpotLight;
  5954. })(BABYLON || (BABYLON = {}));
  5955. var __extends = this.__extends || function (d, b) {
  5956. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5957. function __() { this.constructor = d; }
  5958. __.prototype = b.prototype;
  5959. d.prototype = new __();
  5960. };
  5961. var BABYLON;
  5962. (function (BABYLON) {
  5963. var HemisphericLight = (function (_super) {
  5964. __extends(HemisphericLight, _super);
  5965. function HemisphericLight(name, direction, scene) {
  5966. _super.call(this, name, scene);
  5967. this.direction = direction;
  5968. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5969. }
  5970. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5971. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5972. return this.direction;
  5973. };
  5974. HemisphericLight.prototype.getShadowGenerator = function () {
  5975. return null;
  5976. };
  5977. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5978. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5979. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5980. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5981. };
  5982. HemisphericLight.prototype._getWorldMatrix = function () {
  5983. if (!this._worldMatrix) {
  5984. this._worldMatrix = BABYLON.Matrix.Identity();
  5985. }
  5986. return this._worldMatrix;
  5987. };
  5988. return HemisphericLight;
  5989. })(BABYLON.Light);
  5990. BABYLON.HemisphericLight = HemisphericLight;
  5991. })(BABYLON || (BABYLON = {}));
  5992. var __extends = this.__extends || function (d, b) {
  5993. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5994. function __() { this.constructor = d; }
  5995. __.prototype = b.prototype;
  5996. d.prototype = new __();
  5997. };
  5998. var BABYLON;
  5999. (function (BABYLON) {
  6000. var DirectionalLight = (function (_super) {
  6001. __extends(DirectionalLight, _super);
  6002. function DirectionalLight(name, direction, scene) {
  6003. _super.call(this, name, scene);
  6004. this.direction = direction;
  6005. this.position = direction.scale(-1);
  6006. }
  6007. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  6008. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6009. return this.direction;
  6010. };
  6011. DirectionalLight.prototype._computeTransformedPosition = function () {
  6012. if (this.parent && this.parent.getWorldMatrix) {
  6013. if (!this._transformedPosition) {
  6014. this._transformedPosition = BABYLON.Vector3.Zero();
  6015. }
  6016. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  6017. return true;
  6018. }
  6019. return false;
  6020. };
  6021. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  6022. if (this.parent && this.parent.getWorldMatrix) {
  6023. if (!this._transformedDirection) {
  6024. this._transformedDirection = BABYLON.Vector3.Zero();
  6025. }
  6026. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6027. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  6028. return;
  6029. }
  6030. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  6031. };
  6032. DirectionalLight.prototype._getWorldMatrix = function () {
  6033. if (!this._worldMatrix) {
  6034. this._worldMatrix = BABYLON.Matrix.Identity();
  6035. }
  6036. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6037. return this._worldMatrix;
  6038. };
  6039. return DirectionalLight;
  6040. })(BABYLON.Light);
  6041. BABYLON.DirectionalLight = DirectionalLight;
  6042. })(BABYLON || (BABYLON = {}));
  6043. var BABYLON;
  6044. (function (BABYLON) {
  6045. var ShadowGenerator = (function () {
  6046. function ShadowGenerator(mapSize, light) {
  6047. var _this = this;
  6048. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  6049. this._darkness = 0;
  6050. this._transparencyShadow = false;
  6051. this._viewMatrix = BABYLON.Matrix.Zero();
  6052. this._projectionMatrix = BABYLON.Matrix.Zero();
  6053. this._transformMatrix = BABYLON.Matrix.Zero();
  6054. this._worldViewProjection = BABYLON.Matrix.Zero();
  6055. this._light = light;
  6056. this._scene = light.getScene();
  6057. light._shadowGenerator = this;
  6058. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  6059. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6060. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6061. this._shadowMap.renderParticles = false;
  6062. var renderSubMesh = function (subMesh) {
  6063. var mesh = subMesh.getRenderingMesh();
  6064. var scene = _this._scene;
  6065. var engine = scene.getEngine();
  6066. engine.setState(subMesh.getMaterial().backFaceCulling);
  6067. var batch = mesh._getInstancesRenderList(subMesh._id);
  6068. if (batch.mustReturn) {
  6069. return;
  6070. }
  6071. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  6072. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  6073. engine.enableEffect(_this._effect);
  6074. mesh._bind(subMesh, _this._effect, WebGLRenderingContext.TRIANGLES);
  6075. var material = subMesh.getMaterial();
  6076. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  6077. if (material && material.needAlphaTesting()) {
  6078. var alphaTexture = material.getAlphaTestTexture();
  6079. _this._effect.setTexture("diffuseSampler", alphaTexture);
  6080. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  6081. }
  6082. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  6083. if (useBones) {
  6084. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  6085. }
  6086. if (hardwareInstancedRendering) {
  6087. mesh._renderWithInstances(subMesh, WebGLRenderingContext.TRIANGLES, batch, _this._effect, engine);
  6088. } else {
  6089. if (batch.renderSelf[subMesh._id]) {
  6090. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  6091. mesh._draw(subMesh, WebGLRenderingContext.TRIANGLES);
  6092. }
  6093. if (batch.visibleInstances[subMesh._id]) {
  6094. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  6095. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  6096. _this._effect.setMatrix("world", instance.getWorldMatrix());
  6097. mesh._draw(subMesh, WebGLRenderingContext.TRIANGLES);
  6098. }
  6099. }
  6100. }
  6101. } else {
  6102. _this._shadowMap.resetRefreshCounter();
  6103. }
  6104. };
  6105. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  6106. var index;
  6107. for (index = 0; index < opaqueSubMeshes.length; index++) {
  6108. renderSubMesh(opaqueSubMeshes.data[index]);
  6109. }
  6110. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  6111. renderSubMesh(alphaTestSubMeshes.data[index]);
  6112. }
  6113. if (_this._transparencyShadow) {
  6114. for (index = 0; index < transparentSubMeshes.length; index++) {
  6115. renderSubMesh(transparentSubMeshes.data[index]);
  6116. }
  6117. }
  6118. };
  6119. }
  6120. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  6121. get: function () {
  6122. return ShadowGenerator._FILTER_NONE;
  6123. },
  6124. enumerable: true,
  6125. configurable: true
  6126. });
  6127. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6128. get: function () {
  6129. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6130. },
  6131. enumerable: true,
  6132. configurable: true
  6133. });
  6134. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6135. get: function () {
  6136. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6137. },
  6138. enumerable: true,
  6139. configurable: true
  6140. });
  6141. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6142. get: function () {
  6143. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  6144. },
  6145. set: function (value) {
  6146. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6147. },
  6148. enumerable: true,
  6149. configurable: true
  6150. });
  6151. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6152. get: function () {
  6153. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  6154. },
  6155. set: function (value) {
  6156. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6157. },
  6158. enumerable: true,
  6159. configurable: true
  6160. });
  6161. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6162. var defines = [];
  6163. if (this.useVarianceShadowMap) {
  6164. defines.push("#define VSM");
  6165. }
  6166. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6167. var mesh = subMesh.getMesh();
  6168. var material = subMesh.getMaterial();
  6169. if (material && material.needAlphaTesting()) {
  6170. defines.push("#define ALPHATEST");
  6171. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6172. attribs.push(BABYLON.VertexBuffer.UVKind);
  6173. defines.push("#define UV1");
  6174. }
  6175. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6176. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6177. defines.push("#define UV2");
  6178. }
  6179. }
  6180. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  6181. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6182. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6183. defines.push("#define BONES");
  6184. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6185. }
  6186. if (useInstances) {
  6187. defines.push("#define INSTANCES");
  6188. attribs.push("world0");
  6189. attribs.push("world1");
  6190. attribs.push("world2");
  6191. attribs.push("world3");
  6192. }
  6193. var join = defines.join("\n");
  6194. if (this._cachedDefines != join) {
  6195. this._cachedDefines = join;
  6196. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6197. }
  6198. return this._effect.isReady();
  6199. };
  6200. ShadowGenerator.prototype.getShadowMap = function () {
  6201. return this._shadowMap;
  6202. };
  6203. ShadowGenerator.prototype.getLight = function () {
  6204. return this._light;
  6205. };
  6206. ShadowGenerator.prototype.getTransformMatrix = function () {
  6207. var lightPosition = this._light.position;
  6208. var lightDirection = this._light.direction;
  6209. if (this._light._computeTransformedPosition()) {
  6210. lightPosition = this._light._transformedPosition;
  6211. }
  6212. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6213. this._cachedPosition = lightPosition.clone();
  6214. this._cachedDirection = lightDirection.clone();
  6215. var activeCamera = this._scene.activeCamera;
  6216. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6217. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  6218. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6219. }
  6220. return this._transformMatrix;
  6221. };
  6222. ShadowGenerator.prototype.getDarkness = function () {
  6223. return this._darkness;
  6224. };
  6225. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6226. if (darkness >= 1.0)
  6227. this._darkness = 1.0;
  6228. else if (darkness <= 0.0)
  6229. this._darkness = 0.0;
  6230. else
  6231. this._darkness = darkness;
  6232. };
  6233. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6234. this._transparencyShadow = hasShadow;
  6235. };
  6236. ShadowGenerator.prototype.dispose = function () {
  6237. this._shadowMap.dispose();
  6238. };
  6239. ShadowGenerator._FILTER_NONE = 0;
  6240. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6241. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6242. return ShadowGenerator;
  6243. })();
  6244. BABYLON.ShadowGenerator = ShadowGenerator;
  6245. })(BABYLON || (BABYLON = {}));
  6246. var BABYLON;
  6247. (function (BABYLON) {
  6248. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6249. if (boxMin.x > sphereCenter.x + sphereRadius)
  6250. return false;
  6251. if (sphereCenter.x - sphereRadius > boxMax.x)
  6252. return false;
  6253. if (boxMin.y > sphereCenter.y + sphereRadius)
  6254. return false;
  6255. if (sphereCenter.y - sphereRadius > boxMax.y)
  6256. return false;
  6257. if (boxMin.z > sphereCenter.z + sphereRadius)
  6258. return false;
  6259. if (sphereCenter.z - sphereRadius > boxMax.z)
  6260. return false;
  6261. return true;
  6262. };
  6263. var getLowestRoot = function (a, b, c, maxR) {
  6264. var determinant = b * b - 4.0 * a * c;
  6265. var result = { root: 0, found: false };
  6266. if (determinant < 0)
  6267. return result;
  6268. var sqrtD = Math.sqrt(determinant);
  6269. var r1 = (-b - sqrtD) / (2.0 * a);
  6270. var r2 = (-b + sqrtD) / (2.0 * a);
  6271. if (r1 > r2) {
  6272. var temp = r2;
  6273. r2 = r1;
  6274. r1 = temp;
  6275. }
  6276. if (r1 > 0 && r1 < maxR) {
  6277. result.root = r1;
  6278. result.found = true;
  6279. return result;
  6280. }
  6281. if (r2 > 0 && r2 < maxR) {
  6282. result.root = r2;
  6283. result.found = true;
  6284. return result;
  6285. }
  6286. return result;
  6287. };
  6288. var Collider = (function () {
  6289. function Collider() {
  6290. this.radius = new BABYLON.Vector3(1, 1, 1);
  6291. this.retry = 0;
  6292. this.basePointWorld = BABYLON.Vector3.Zero();
  6293. this.velocityWorld = BABYLON.Vector3.Zero();
  6294. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6295. this._collisionPoint = BABYLON.Vector3.Zero();
  6296. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6297. this._tempVector = BABYLON.Vector3.Zero();
  6298. this._tempVector2 = BABYLON.Vector3.Zero();
  6299. this._tempVector3 = BABYLON.Vector3.Zero();
  6300. this._tempVector4 = BABYLON.Vector3.Zero();
  6301. this._edge = BABYLON.Vector3.Zero();
  6302. this._baseToVertex = BABYLON.Vector3.Zero();
  6303. this._destinationPoint = BABYLON.Vector3.Zero();
  6304. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6305. this._displacementVector = BABYLON.Vector3.Zero();
  6306. }
  6307. Collider.prototype._initialize = function (source, dir, e) {
  6308. this.velocity = dir;
  6309. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6310. this.basePoint = source;
  6311. source.multiplyToRef(this.radius, this.basePointWorld);
  6312. dir.multiplyToRef(this.radius, this.velocityWorld);
  6313. this.velocityWorldLength = this.velocityWorld.length();
  6314. this.epsilon = e;
  6315. this.collisionFound = false;
  6316. };
  6317. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6318. pa.subtractToRef(point, this._tempVector);
  6319. pb.subtractToRef(point, this._tempVector2);
  6320. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6321. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6322. if (d < 0)
  6323. return false;
  6324. pc.subtractToRef(point, this._tempVector3);
  6325. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6326. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6327. if (d < 0)
  6328. return false;
  6329. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6330. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6331. return d >= 0;
  6332. };
  6333. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6334. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6335. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6336. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6337. return false;
  6338. }
  6339. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6340. return false;
  6341. return true;
  6342. };
  6343. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6344. var t0;
  6345. var embeddedInPlane = false;
  6346. if (!subMesh._trianglePlanes) {
  6347. subMesh._trianglePlanes = [];
  6348. }
  6349. if (!subMesh._trianglePlanes[faceIndex]) {
  6350. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6351. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6352. }
  6353. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6354. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6355. return;
  6356. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6357. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6358. if (normalDotVelocity == 0) {
  6359. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6360. return;
  6361. embeddedInPlane = true;
  6362. t0 = 0;
  6363. } else {
  6364. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6365. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6366. if (t0 > t1) {
  6367. var temp = t1;
  6368. t1 = t0;
  6369. t0 = temp;
  6370. }
  6371. if (t0 > 1.0 || t1 < 0.0)
  6372. return;
  6373. if (t0 < 0)
  6374. t0 = 0;
  6375. if (t0 > 1.0)
  6376. t0 = 1.0;
  6377. }
  6378. this._collisionPoint.copyFromFloats(0, 0, 0);
  6379. var found = false;
  6380. var t = 1.0;
  6381. if (!embeddedInPlane) {
  6382. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6383. this.velocity.scaleToRef(t0, this._tempVector);
  6384. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6385. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6386. found = true;
  6387. t = t0;
  6388. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6389. }
  6390. }
  6391. if (!found) {
  6392. var velocitySquaredLength = this.velocity.lengthSquared();
  6393. var a = velocitySquaredLength;
  6394. this.basePoint.subtractToRef(p1, this._tempVector);
  6395. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6396. var c = this._tempVector.lengthSquared() - 1.0;
  6397. var lowestRoot = getLowestRoot(a, b, c, t);
  6398. if (lowestRoot.found) {
  6399. t = lowestRoot.root;
  6400. found = true;
  6401. this._collisionPoint.copyFrom(p1);
  6402. }
  6403. this.basePoint.subtractToRef(p2, this._tempVector);
  6404. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6405. c = this._tempVector.lengthSquared() - 1.0;
  6406. lowestRoot = getLowestRoot(a, b, c, t);
  6407. if (lowestRoot.found) {
  6408. t = lowestRoot.root;
  6409. found = true;
  6410. this._collisionPoint.copyFrom(p2);
  6411. }
  6412. this.basePoint.subtractToRef(p3, this._tempVector);
  6413. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6414. c = this._tempVector.lengthSquared() - 1.0;
  6415. lowestRoot = getLowestRoot(a, b, c, t);
  6416. if (lowestRoot.found) {
  6417. t = lowestRoot.root;
  6418. found = true;
  6419. this._collisionPoint.copyFrom(p3);
  6420. }
  6421. p2.subtractToRef(p1, this._edge);
  6422. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6423. var edgeSquaredLength = this._edge.lengthSquared();
  6424. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6425. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6426. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6427. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6428. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6429. lowestRoot = getLowestRoot(a, b, c, t);
  6430. if (lowestRoot.found) {
  6431. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6432. if (f >= 0.0 && f <= 1.0) {
  6433. t = lowestRoot.root;
  6434. found = true;
  6435. this._edge.scaleInPlace(f);
  6436. p1.addToRef(this._edge, this._collisionPoint);
  6437. }
  6438. }
  6439. p3.subtractToRef(p2, this._edge);
  6440. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6441. edgeSquaredLength = this._edge.lengthSquared();
  6442. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6443. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6444. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6445. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6446. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6447. lowestRoot = getLowestRoot(a, b, c, t);
  6448. if (lowestRoot.found) {
  6449. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6450. if (f >= 0.0 && f <= 1.0) {
  6451. t = lowestRoot.root;
  6452. found = true;
  6453. this._edge.scaleInPlace(f);
  6454. p2.addToRef(this._edge, this._collisionPoint);
  6455. }
  6456. }
  6457. p1.subtractToRef(p3, this._edge);
  6458. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6459. edgeSquaredLength = this._edge.lengthSquared();
  6460. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6461. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6462. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6463. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6464. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6465. lowestRoot = getLowestRoot(a, b, c, t);
  6466. if (lowestRoot.found) {
  6467. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6468. if (f >= 0.0 && f <= 1.0) {
  6469. t = lowestRoot.root;
  6470. found = true;
  6471. this._edge.scaleInPlace(f);
  6472. p3.addToRef(this._edge, this._collisionPoint);
  6473. }
  6474. }
  6475. }
  6476. if (found) {
  6477. var distToCollision = t * this.velocity.length();
  6478. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6479. if (!this.intersectionPoint) {
  6480. this.intersectionPoint = this._collisionPoint.clone();
  6481. } else {
  6482. this.intersectionPoint.copyFrom(this._collisionPoint);
  6483. }
  6484. this.nearestDistance = distToCollision;
  6485. this.collisionFound = true;
  6486. this.collidedMesh = subMesh.getMesh();
  6487. }
  6488. }
  6489. };
  6490. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6491. for (var i = indexStart; i < indexEnd; i += 3) {
  6492. var p1 = pts[indices[i] - decal];
  6493. var p2 = pts[indices[i + 1] - decal];
  6494. var p3 = pts[indices[i + 2] - decal];
  6495. this._testTriangle(i, subMesh, p3, p2, p1);
  6496. }
  6497. };
  6498. Collider.prototype._getResponse = function (pos, vel) {
  6499. pos.addToRef(vel, this._destinationPoint);
  6500. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6501. this.basePoint.addToRef(vel, pos);
  6502. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6503. this._slidePlaneNormal.normalize();
  6504. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6505. pos.addInPlace(this._displacementVector);
  6506. this.intersectionPoint.addInPlace(this._displacementVector);
  6507. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6508. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6509. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6510. };
  6511. return Collider;
  6512. })();
  6513. BABYLON.Collider = Collider;
  6514. })(BABYLON || (BABYLON = {}));
  6515. var __extends = this.__extends || function (d, b) {
  6516. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  6517. function __() { this.constructor = d; }
  6518. __.prototype = b.prototype;
  6519. d.prototype = new __();
  6520. };
  6521. var BABYLON;
  6522. (function (BABYLON) {
  6523. var Camera = (function (_super) {
  6524. __extends(Camera, _super);
  6525. function Camera(name, position, scene) {
  6526. _super.call(this, name, scene);
  6527. this.position = position;
  6528. this.upVector = BABYLON.Vector3.Up();
  6529. this.orthoLeft = null;
  6530. this.orthoRight = null;
  6531. this.orthoBottom = null;
  6532. this.orthoTop = null;
  6533. this.fov = 0.8;
  6534. this.minZ = 1.0;
  6535. this.maxZ = 10000.0;
  6536. this.inertia = 0.9;
  6537. this.mode = Camera.PERSPECTIVE_CAMERA;
  6538. this.isIntermediate = false;
  6539. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6540. this.subCameras = [];
  6541. this.layerMask = 0xFFFFFFFF;
  6542. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6543. this._projectionMatrix = new BABYLON.Matrix();
  6544. this._postProcesses = new Array();
  6545. this._postProcessesTakenIndices = [];
  6546. scene.cameras.push(this);
  6547. if (!scene.activeCamera) {
  6548. scene.activeCamera = this;
  6549. }
  6550. }
  6551. Camera.prototype._initCache = function () {
  6552. _super.prototype._initCache.call(this);
  6553. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6554. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6555. this._cache.mode = undefined;
  6556. this._cache.minZ = undefined;
  6557. this._cache.maxZ = undefined;
  6558. this._cache.fov = undefined;
  6559. this._cache.aspectRatio = undefined;
  6560. this._cache.orthoLeft = undefined;
  6561. this._cache.orthoRight = undefined;
  6562. this._cache.orthoBottom = undefined;
  6563. this._cache.orthoTop = undefined;
  6564. this._cache.renderWidth = undefined;
  6565. this._cache.renderHeight = undefined;
  6566. };
  6567. Camera.prototype._updateCache = function (ignoreParentClass) {
  6568. if (!ignoreParentClass) {
  6569. _super.prototype._updateCache.call(this);
  6570. }
  6571. var engine = this.getEngine();
  6572. this._cache.position.copyFrom(this.position);
  6573. this._cache.upVector.copyFrom(this.upVector);
  6574. this._cache.mode = this.mode;
  6575. this._cache.minZ = this.minZ;
  6576. this._cache.maxZ = this.maxZ;
  6577. this._cache.fov = this.fov;
  6578. this._cache.aspectRatio = engine.getAspectRatio(this);
  6579. this._cache.orthoLeft = this.orthoLeft;
  6580. this._cache.orthoRight = this.orthoRight;
  6581. this._cache.orthoBottom = this.orthoBottom;
  6582. this._cache.orthoTop = this.orthoTop;
  6583. this._cache.renderWidth = engine.getRenderWidth();
  6584. this._cache.renderHeight = engine.getRenderHeight();
  6585. };
  6586. Camera.prototype._updateFromScene = function () {
  6587. this.updateCache();
  6588. this._update();
  6589. };
  6590. Camera.prototype._isSynchronized = function () {
  6591. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6592. };
  6593. Camera.prototype._isSynchronizedViewMatrix = function () {
  6594. if (!_super.prototype._isSynchronized.call(this))
  6595. return false;
  6596. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6597. };
  6598. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6599. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6600. if (!check) {
  6601. return false;
  6602. }
  6603. var engine = this.getEngine();
  6604. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6605. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6606. } else {
  6607. 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();
  6608. }
  6609. return check;
  6610. };
  6611. Camera.prototype.attachControl = function (element) {
  6612. };
  6613. Camera.prototype.detachControl = function (element) {
  6614. };
  6615. Camera.prototype._update = function () {
  6616. };
  6617. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6618. if (typeof insertAt === "undefined") { insertAt = null; }
  6619. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6620. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6621. return 0;
  6622. }
  6623. if (insertAt == null || insertAt < 0) {
  6624. this._postProcesses.push(postProcess);
  6625. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6626. return this._postProcesses.length - 1;
  6627. }
  6628. var add = 0;
  6629. if (this._postProcesses[insertAt]) {
  6630. var start = this._postProcesses.length - 1;
  6631. for (var i = start; i >= insertAt + 1; --i) {
  6632. this._postProcesses[i + 1] = this._postProcesses[i];
  6633. }
  6634. add = 1;
  6635. }
  6636. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6637. if (this._postProcessesTakenIndices[i] < insertAt) {
  6638. continue;
  6639. }
  6640. start = this._postProcessesTakenIndices.length - 1;
  6641. for (var j = start; j >= i; --j) {
  6642. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6643. }
  6644. this._postProcessesTakenIndices[i] = insertAt;
  6645. break;
  6646. }
  6647. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6648. this._postProcessesTakenIndices.push(insertAt);
  6649. }
  6650. var result = insertAt + add;
  6651. this._postProcesses[result] = postProcess;
  6652. return result;
  6653. };
  6654. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6655. if (typeof atIndices === "undefined") { atIndices = null; }
  6656. var result = [];
  6657. if (!atIndices) {
  6658. var length = this._postProcesses.length;
  6659. for (var i = 0; i < length; i++) {
  6660. if (this._postProcesses[i] !== postProcess) {
  6661. continue;
  6662. }
  6663. delete this._postProcesses[i];
  6664. var index = this._postProcessesTakenIndices.indexOf(i);
  6665. this._postProcessesTakenIndices.splice(index, 1);
  6666. }
  6667. } else {
  6668. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6669. for (i = 0; i < atIndices.length; i++) {
  6670. var foundPostProcess = this._postProcesses[atIndices[i]];
  6671. if (foundPostProcess !== postProcess) {
  6672. result.push(i);
  6673. continue;
  6674. }
  6675. delete this._postProcesses[atIndices[i]];
  6676. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6677. this._postProcessesTakenIndices.splice(index, 1);
  6678. }
  6679. }
  6680. return result;
  6681. };
  6682. Camera.prototype.getWorldMatrix = function () {
  6683. if (!this._worldMatrix) {
  6684. this._worldMatrix = BABYLON.Matrix.Identity();
  6685. }
  6686. var viewMatrix = this.getViewMatrix();
  6687. viewMatrix.invertToRef(this._worldMatrix);
  6688. return this._worldMatrix;
  6689. };
  6690. Camera.prototype._getViewMatrix = function () {
  6691. return BABYLON.Matrix.Identity();
  6692. };
  6693. Camera.prototype.getViewMatrix = function () {
  6694. this._computedViewMatrix = this._computeViewMatrix();
  6695. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6696. return this._computedViewMatrix;
  6697. }
  6698. if (!this._worldMatrix) {
  6699. this._worldMatrix = BABYLON.Matrix.Identity();
  6700. }
  6701. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6702. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6703. this._computedViewMatrix.invert();
  6704. this._currentRenderId = this.getScene().getRenderId();
  6705. return this._computedViewMatrix;
  6706. };
  6707. Camera.prototype._computeViewMatrix = function (force) {
  6708. if (!force && this._isSynchronizedViewMatrix()) {
  6709. return this._computedViewMatrix;
  6710. }
  6711. this._computedViewMatrix = this._getViewMatrix();
  6712. if (!this.parent || !this.parent.getWorldMatrix) {
  6713. this._currentRenderId = this.getScene().getRenderId();
  6714. }
  6715. return this._computedViewMatrix;
  6716. };
  6717. Camera.prototype.getProjectionMatrix = function (force) {
  6718. if (!force && this._isSynchronizedProjectionMatrix()) {
  6719. return this._projectionMatrix;
  6720. }
  6721. var engine = this.getEngine();
  6722. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6723. if (this.minZ <= 0) {
  6724. this.minZ = 0.1;
  6725. }
  6726. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  6727. return this._projectionMatrix;
  6728. }
  6729. var halfWidth = engine.getRenderWidth() / 2.0;
  6730. var halfHeight = engine.getRenderHeight() / 2.0;
  6731. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6732. return this._projectionMatrix;
  6733. };
  6734. Camera.prototype.dispose = function () {
  6735. var index = this.getScene().cameras.indexOf(this);
  6736. this.getScene().cameras.splice(index, 1);
  6737. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6738. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6739. }
  6740. };
  6741. Camera.PERSPECTIVE_CAMERA = 0;
  6742. Camera.ORTHOGRAPHIC_CAMERA = 1;
  6743. return Camera;
  6744. })(BABYLON.Node);
  6745. BABYLON.Camera = Camera;
  6746. })(BABYLON || (BABYLON = {}));
  6747. var __extends = this.__extends || function (d, b) {
  6748. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  6749. function __() { this.constructor = d; }
  6750. __.prototype = b.prototype;
  6751. d.prototype = new __();
  6752. };
  6753. var BABYLON;
  6754. (function (BABYLON) {
  6755. var TargetCamera = (function (_super) {
  6756. __extends(TargetCamera, _super);
  6757. function TargetCamera(name, position, scene) {
  6758. _super.call(this, name, position, scene);
  6759. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6760. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6761. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6762. this.speed = 2.0;
  6763. this.noRotationConstraint = false;
  6764. this.lockedTarget = null;
  6765. this._currentTarget = BABYLON.Vector3.Zero();
  6766. this._viewMatrix = BABYLON.Matrix.Zero();
  6767. this._camMatrix = BABYLON.Matrix.Zero();
  6768. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6769. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6770. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6771. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6772. this._lookAtTemp = BABYLON.Matrix.Zero();
  6773. this._tempMatrix = BABYLON.Matrix.Zero();
  6774. }
  6775. TargetCamera.prototype._getLockedTargetPosition = function () {
  6776. if (!this.lockedTarget) {
  6777. return null;
  6778. }
  6779. return this.lockedTarget.position || this.lockedTarget;
  6780. };
  6781. TargetCamera.prototype._initCache = function () {
  6782. _super.prototype._initCache.call(this);
  6783. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6784. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6785. };
  6786. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6787. if (!ignoreParentClass) {
  6788. _super.prototype._updateCache.call(this);
  6789. }
  6790. var lockedTargetPosition = this._getLockedTargetPosition();
  6791. if (!lockedTargetPosition) {
  6792. this._cache.lockedTarget = null;
  6793. } else {
  6794. if (!this._cache.lockedTarget) {
  6795. this._cache.lockedTarget = lockedTargetPosition.clone();
  6796. } else {
  6797. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6798. }
  6799. }
  6800. this._cache.rotation.copyFrom(this.rotation);
  6801. };
  6802. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6803. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6804. return false;
  6805. }
  6806. var lockedTargetPosition = this._getLockedTargetPosition();
  6807. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6808. };
  6809. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6810. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  6811. };
  6812. TargetCamera.prototype.setTarget = function (target) {
  6813. this.upVector.normalize();
  6814. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6815. this._camMatrix.invert();
  6816. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6817. var vDir = target.subtract(this.position);
  6818. if (vDir.x >= 0.0) {
  6819. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6820. } else {
  6821. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6822. }
  6823. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6824. if (isNaN(this.rotation.x)) {
  6825. this.rotation.x = 0;
  6826. }
  6827. if (isNaN(this.rotation.y)) {
  6828. this.rotation.y = 0;
  6829. }
  6830. if (isNaN(this.rotation.z)) {
  6831. this.rotation.z = 0;
  6832. }
  6833. };
  6834. TargetCamera.prototype.getTarget = function () {
  6835. return this._currentTarget;
  6836. };
  6837. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6838. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6839. };
  6840. TargetCamera.prototype._updatePosition = function () {
  6841. this.position.addInPlace(this.cameraDirection);
  6842. };
  6843. TargetCamera.prototype._update = function () {
  6844. var needToMove = this._decideIfNeedsToMove();
  6845. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6846. if (needToMove) {
  6847. this._updatePosition();
  6848. }
  6849. if (needToRotate) {
  6850. this.rotation.x += this.cameraRotation.x;
  6851. this.rotation.y += this.cameraRotation.y;
  6852. if (!this.noRotationConstraint) {
  6853. var limit = (Math.PI / 2) * 0.95;
  6854. if (this.rotation.x > limit)
  6855. this.rotation.x = limit;
  6856. if (this.rotation.x < -limit)
  6857. this.rotation.x = -limit;
  6858. }
  6859. }
  6860. if (needToMove) {
  6861. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6862. this.cameraDirection.x = 0;
  6863. }
  6864. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6865. this.cameraDirection.y = 0;
  6866. }
  6867. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6868. this.cameraDirection.z = 0;
  6869. }
  6870. this.cameraDirection.scaleInPlace(this.inertia);
  6871. }
  6872. if (needToRotate) {
  6873. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6874. this.cameraRotation.x = 0;
  6875. }
  6876. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6877. this.cameraRotation.y = 0;
  6878. }
  6879. this.cameraRotation.scaleInPlace(this.inertia);
  6880. }
  6881. };
  6882. TargetCamera.prototype._getViewMatrix = function () {
  6883. if (!this.lockedTarget) {
  6884. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6885. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6886. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6887. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6888. this._lookAtTemp.invert();
  6889. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6890. } else {
  6891. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6892. }
  6893. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6894. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6895. } else {
  6896. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6897. }
  6898. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6899. return this._viewMatrix;
  6900. };
  6901. return TargetCamera;
  6902. })(BABYLON.Camera);
  6903. BABYLON.TargetCamera = TargetCamera;
  6904. })(BABYLON || (BABYLON = {}));
  6905. var __extends = this.__extends || function (d, b) {
  6906. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  6907. function __() { this.constructor = d; }
  6908. __.prototype = b.prototype;
  6909. d.prototype = new __();
  6910. };
  6911. var BABYLON;
  6912. (function (BABYLON) {
  6913. var FollowCamera = (function (_super) {
  6914. __extends(FollowCamera, _super);
  6915. function FollowCamera(name, position, scene) {
  6916. _super.call(this, name, position, scene);
  6917. this.radius = 12;
  6918. this.rotationOffset = 0;
  6919. this.heightOffset = 4;
  6920. this.cameraAcceleration = 0.05;
  6921. this.maxCameraSpeed = 20;
  6922. }
  6923. FollowCamera.prototype.getRadians = function (degrees) {
  6924. return degrees * Math.PI / 180;
  6925. };
  6926. FollowCamera.prototype.follow = function (cameraTarget) {
  6927. if (!cameraTarget)
  6928. return;
  6929. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6930. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6931. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6932. var dx = targetX - this.position.x;
  6933. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6934. var dz = (targetZ) - this.position.z;
  6935. var vx = dx * this.cameraAcceleration * 2;
  6936. var vy = dy * this.cameraAcceleration;
  6937. var vz = dz * this.cameraAcceleration * 2;
  6938. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6939. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6940. }
  6941. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6942. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6943. }
  6944. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6945. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6946. }
  6947. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6948. this.setTarget(cameraTarget.position);
  6949. };
  6950. FollowCamera.prototype._update = function () {
  6951. _super.prototype._update.call(this);
  6952. this.follow(this.target);
  6953. };
  6954. return FollowCamera;
  6955. })(BABYLON.TargetCamera);
  6956. BABYLON.FollowCamera = FollowCamera;
  6957. })(BABYLON || (BABYLON = {}));
  6958. var __extends = this.__extends || function (d, b) {
  6959. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  6960. function __() { this.constructor = d; }
  6961. __.prototype = b.prototype;
  6962. d.prototype = new __();
  6963. };
  6964. var BABYLON;
  6965. (function (BABYLON) {
  6966. var FreeCamera = (function (_super) {
  6967. __extends(FreeCamera, _super);
  6968. function FreeCamera(name, position, scene) {
  6969. _super.call(this, name, position, scene);
  6970. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6971. this.keysUp = [38];
  6972. this.keysDown = [40];
  6973. this.keysLeft = [37];
  6974. this.keysRight = [39];
  6975. this.checkCollisions = false;
  6976. this.applyGravity = false;
  6977. this.angularSensibility = 2000.0;
  6978. this._keys = [];
  6979. this._collider = new BABYLON.Collider();
  6980. this._needMoveForGravity = true;
  6981. this._oldPosition = BABYLON.Vector3.Zero();
  6982. this._diffPosition = BABYLON.Vector3.Zero();
  6983. this._newPosition = BABYLON.Vector3.Zero();
  6984. }
  6985. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6986. var _this = this;
  6987. var previousPosition;
  6988. var engine = this.getEngine();
  6989. if (this._attachedElement) {
  6990. return;
  6991. }
  6992. this._attachedElement = element;
  6993. if (this._onMouseDown === undefined) {
  6994. this._onMouseDown = function (evt) {
  6995. previousPosition = {
  6996. x: evt.clientX,
  6997. y: evt.clientY
  6998. };
  6999. if (!noPreventDefault) {
  7000. evt.preventDefault();
  7001. }
  7002. };
  7003. this._onMouseUp = function (evt) {
  7004. previousPosition = null;
  7005. if (!noPreventDefault) {
  7006. evt.preventDefault();
  7007. }
  7008. };
  7009. this._onMouseOut = function (evt) {
  7010. previousPosition = null;
  7011. _this._keys = [];
  7012. if (!noPreventDefault) {
  7013. evt.preventDefault();
  7014. }
  7015. };
  7016. this._onMouseMove = function (evt) {
  7017. if (!previousPosition && !engine.isPointerLock) {
  7018. return;
  7019. }
  7020. var offsetX;
  7021. var offsetY;
  7022. if (!engine.isPointerLock) {
  7023. offsetX = evt.clientX - previousPosition.x;
  7024. offsetY = evt.clientY - previousPosition.y;
  7025. } else {
  7026. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7027. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7028. }
  7029. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7030. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7031. previousPosition = {
  7032. x: evt.clientX,
  7033. y: evt.clientY
  7034. };
  7035. if (!noPreventDefault) {
  7036. evt.preventDefault();
  7037. }
  7038. };
  7039. this._onKeyDown = function (evt) {
  7040. 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) {
  7041. var index = _this._keys.indexOf(evt.keyCode);
  7042. if (index === -1) {
  7043. _this._keys.push(evt.keyCode);
  7044. }
  7045. if (!noPreventDefault) {
  7046. evt.preventDefault();
  7047. }
  7048. }
  7049. };
  7050. this._onKeyUp = function (evt) {
  7051. 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) {
  7052. var index = _this._keys.indexOf(evt.keyCode);
  7053. if (index >= 0) {
  7054. _this._keys.splice(index, 1);
  7055. }
  7056. if (!noPreventDefault) {
  7057. evt.preventDefault();
  7058. }
  7059. }
  7060. };
  7061. this._onLostFocus = function () {
  7062. _this._keys = [];
  7063. };
  7064. this._reset = function () {
  7065. _this._keys = [];
  7066. previousPosition = null;
  7067. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7068. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7069. };
  7070. }
  7071. element.addEventListener("mousedown", this._onMouseDown, false);
  7072. element.addEventListener("mouseup", this._onMouseUp, false);
  7073. element.addEventListener("mouseout", this._onMouseOut, false);
  7074. element.addEventListener("mousemove", this._onMouseMove, false);
  7075. BABYLON.Tools.RegisterTopRootEvents([
  7076. { name: "keydown", handler: this._onKeyDown },
  7077. { name: "keyup", handler: this._onKeyUp },
  7078. { name: "blur", handler: this._onLostFocus }
  7079. ]);
  7080. };
  7081. FreeCamera.prototype.detachControl = function (element) {
  7082. if (this._attachedElement != element) {
  7083. return;
  7084. }
  7085. element.removeEventListener("mousedown", this._onMouseDown);
  7086. element.removeEventListener("mouseup", this._onMouseUp);
  7087. element.removeEventListener("mouseout", this._onMouseOut);
  7088. element.removeEventListener("mousemove", this._onMouseMove);
  7089. BABYLON.Tools.UnregisterTopRootEvents([
  7090. { name: "keydown", handler: this._onKeyDown },
  7091. { name: "keyup", handler: this._onKeyUp },
  7092. { name: "blur", handler: this._onLostFocus }
  7093. ]);
  7094. this._attachedElement = null;
  7095. if (this._reset) {
  7096. this._reset();
  7097. }
  7098. };
  7099. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7100. var globalPosition;
  7101. if (this.parent) {
  7102. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7103. } else {
  7104. globalPosition = this.position;
  7105. }
  7106. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7107. this._collider.radius = this.ellipsoid;
  7108. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7109. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7110. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7111. this.position.addInPlace(this._diffPosition);
  7112. if (this.onCollide) {
  7113. this.onCollide(this._collider.collidedMesh);
  7114. }
  7115. }
  7116. };
  7117. FreeCamera.prototype._checkInputs = function () {
  7118. if (!this._localDirection) {
  7119. this._localDirection = BABYLON.Vector3.Zero();
  7120. this._transformedDirection = BABYLON.Vector3.Zero();
  7121. }
  7122. for (var index = 0; index < this._keys.length; index++) {
  7123. var keyCode = this._keys[index];
  7124. var speed = this._computeLocalCameraSpeed();
  7125. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7126. this._localDirection.copyFromFloats(-speed, 0, 0);
  7127. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  7128. this._localDirection.copyFromFloats(0, 0, speed);
  7129. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  7130. this._localDirection.copyFromFloats(speed, 0, 0);
  7131. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  7132. this._localDirection.copyFromFloats(0, 0, -speed);
  7133. }
  7134. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7135. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7136. this.cameraDirection.addInPlace(this._transformedDirection);
  7137. }
  7138. };
  7139. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7140. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7141. };
  7142. FreeCamera.prototype._updatePosition = function () {
  7143. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7144. this._collideWithWorld(this.cameraDirection);
  7145. if (this.applyGravity) {
  7146. var oldPosition = this.position;
  7147. this._collideWithWorld(this.getScene().gravity);
  7148. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7149. }
  7150. } else {
  7151. this.position.addInPlace(this.cameraDirection);
  7152. }
  7153. };
  7154. FreeCamera.prototype._update = function () {
  7155. this._checkInputs();
  7156. _super.prototype._update.call(this);
  7157. };
  7158. return FreeCamera;
  7159. })(BABYLON.TargetCamera);
  7160. BABYLON.FreeCamera = FreeCamera;
  7161. })(BABYLON || (BABYLON = {}));
  7162. var __extends = this.__extends || function (d, b) {
  7163. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7164. function __() { this.constructor = d; }
  7165. __.prototype = b.prototype;
  7166. d.prototype = new __();
  7167. };
  7168. var BABYLON;
  7169. (function (BABYLON) {
  7170. var TouchCamera = (function (_super) {
  7171. __extends(TouchCamera, _super);
  7172. function TouchCamera(name, position, scene) {
  7173. _super.call(this, name, position, scene);
  7174. this._offsetX = null;
  7175. this._offsetY = null;
  7176. this._pointerCount = 0;
  7177. this._pointerPressed = [];
  7178. this.angularSensibility = 200000.0;
  7179. this.moveSensibility = 500.0;
  7180. }
  7181. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7182. var _this = this;
  7183. var previousPosition;
  7184. if (this._attachedCanvas) {
  7185. return;
  7186. }
  7187. this._attachedCanvas = canvas;
  7188. if (this._onPointerDown === undefined) {
  7189. this._onPointerDown = function (evt) {
  7190. if (!noPreventDefault) {
  7191. evt.preventDefault();
  7192. }
  7193. _this._pointerPressed.push(evt.pointerId);
  7194. if (_this._pointerPressed.length !== 1) {
  7195. return;
  7196. }
  7197. previousPosition = {
  7198. x: evt.clientX,
  7199. y: evt.clientY
  7200. };
  7201. };
  7202. this._onPointerUp = function (evt) {
  7203. if (!noPreventDefault) {
  7204. evt.preventDefault();
  7205. }
  7206. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7207. if (index === -1) {
  7208. return;
  7209. }
  7210. _this._pointerPressed.splice(index, 1);
  7211. if (index != 0) {
  7212. return;
  7213. }
  7214. previousPosition = null;
  7215. _this._offsetX = null;
  7216. _this._offsetY = null;
  7217. };
  7218. this._onPointerMove = function (evt) {
  7219. if (!noPreventDefault) {
  7220. evt.preventDefault();
  7221. }
  7222. if (!previousPosition) {
  7223. return;
  7224. }
  7225. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7226. if (index != 0) {
  7227. return;
  7228. }
  7229. _this._offsetX = evt.clientX - previousPosition.x;
  7230. _this._offsetY = -(evt.clientY - previousPosition.y);
  7231. };
  7232. this._onLostFocus = function () {
  7233. _this._offsetX = null;
  7234. _this._offsetY = null;
  7235. };
  7236. }
  7237. canvas.addEventListener("pointerdown", this._onPointerDown);
  7238. canvas.addEventListener("pointerup", this._onPointerUp);
  7239. canvas.addEventListener("pointerout", this._onPointerUp);
  7240. canvas.addEventListener("pointermove", this._onPointerMove);
  7241. BABYLON.Tools.RegisterTopRootEvents([
  7242. { name: "blur", handler: this._onLostFocus }
  7243. ]);
  7244. };
  7245. TouchCamera.prototype.detachControl = function (canvas) {
  7246. if (this._attachedCanvas != canvas) {
  7247. return;
  7248. }
  7249. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7250. canvas.removeEventListener("pointerup", this._onPointerUp);
  7251. canvas.removeEventListener("pointerout", this._onPointerUp);
  7252. canvas.removeEventListener("pointermove", this._onPointerMove);
  7253. BABYLON.Tools.UnregisterTopRootEvents([
  7254. { name: "blur", handler: this._onLostFocus }
  7255. ]);
  7256. this._attachedCanvas = null;
  7257. };
  7258. TouchCamera.prototype._checkInputs = function () {
  7259. if (!this._offsetX) {
  7260. return;
  7261. }
  7262. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7263. if (this._pointerPressed.length > 1) {
  7264. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7265. } else {
  7266. var speed = this._computeLocalCameraSpeed();
  7267. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7268. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7269. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7270. }
  7271. };
  7272. return TouchCamera;
  7273. })(BABYLON.FreeCamera);
  7274. BABYLON.TouchCamera = TouchCamera;
  7275. })(BABYLON || (BABYLON = {}));
  7276. var __extends = this.__extends || function (d, b) {
  7277. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7278. function __() { this.constructor = d; }
  7279. __.prototype = b.prototype;
  7280. d.prototype = new __();
  7281. };
  7282. var BABYLON;
  7283. (function (BABYLON) {
  7284. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7285. var ArcRotateCamera = (function (_super) {
  7286. __extends(ArcRotateCamera, _super);
  7287. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7288. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7289. this.alpha = alpha;
  7290. this.beta = beta;
  7291. this.radius = radius;
  7292. this.target = target;
  7293. this.inertialAlphaOffset = 0;
  7294. this.inertialBetaOffset = 0;
  7295. this.inertialRadiusOffset = 0;
  7296. this.lowerAlphaLimit = null;
  7297. this.upperAlphaLimit = null;
  7298. this.lowerBetaLimit = 0.01;
  7299. this.upperBetaLimit = Math.PI;
  7300. this.lowerRadiusLimit = null;
  7301. this.upperRadiusLimit = null;
  7302. this.angularSensibility = 1000.0;
  7303. this.wheelPrecision = 3.0;
  7304. this.keysUp = [38];
  7305. this.keysDown = [40];
  7306. this.keysLeft = [37];
  7307. this.keysRight = [39];
  7308. this.zoomOnFactor = 1;
  7309. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7310. this._keys = [];
  7311. this._viewMatrix = new BABYLON.Matrix();
  7312. this.checkCollisions = false;
  7313. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7314. this._collider = new BABYLON.Collider();
  7315. this._previousPosition = BABYLON.Vector3.Zero();
  7316. this._collisionVelocity = BABYLON.Vector3.Zero();
  7317. this._newPosition = BABYLON.Vector3.Zero();
  7318. this.pinchPrecision = 20;
  7319. this.getViewMatrix();
  7320. }
  7321. ArcRotateCamera.prototype._getTargetPosition = function () {
  7322. return this.target.position || this.target;
  7323. };
  7324. ArcRotateCamera.prototype._initCache = function () {
  7325. _super.prototype._initCache.call(this);
  7326. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7327. this._cache.alpha = undefined;
  7328. this._cache.beta = undefined;
  7329. this._cache.radius = undefined;
  7330. this._cache.targetScreenOffset = undefined;
  7331. };
  7332. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7333. if (!ignoreParentClass) {
  7334. _super.prototype._updateCache.call(this);
  7335. }
  7336. this._cache.target.copyFrom(this._getTargetPosition());
  7337. this._cache.alpha = this.alpha;
  7338. this._cache.beta = this.beta;
  7339. this._cache.radius = this.radius;
  7340. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7341. };
  7342. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7343. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7344. return false;
  7345. 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);
  7346. };
  7347. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7348. var _this = this;
  7349. var previousPosition;
  7350. var pointerId;
  7351. var pinchStarted = false;
  7352. var pinchPointX1, pinchPointX2;
  7353. if (this._attachedElement) {
  7354. return;
  7355. }
  7356. this._attachedElement = element;
  7357. var engine = this.getEngine();
  7358. if (this._onPointerDown === undefined) {
  7359. this._onPointerDown = function (evt) {
  7360. if (pointerId) {
  7361. return;
  7362. }
  7363. pointerId = evt.pointerId;
  7364. previousPosition = {
  7365. x: evt.clientX,
  7366. y: evt.clientY
  7367. };
  7368. if (!noPreventDefault) {
  7369. evt.preventDefault();
  7370. }
  7371. };
  7372. this._onPointerUp = function (evt) {
  7373. previousPosition = null;
  7374. pointerId = null;
  7375. if (!noPreventDefault) {
  7376. evt.preventDefault();
  7377. }
  7378. };
  7379. this._onPointerMove = function (evt) {
  7380. if (!previousPosition) {
  7381. return;
  7382. }
  7383. if (pointerId !== evt.pointerId) {
  7384. return;
  7385. }
  7386. if (pinchStarted) {
  7387. return;
  7388. }
  7389. var offsetX = evt.clientX - previousPosition.x;
  7390. var offsetY = evt.clientY - previousPosition.y;
  7391. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7392. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7393. previousPosition = {
  7394. x: evt.clientX,
  7395. y: evt.clientY
  7396. };
  7397. if (!noPreventDefault) {
  7398. evt.preventDefault();
  7399. }
  7400. };
  7401. this._onMouseMove = function (evt) {
  7402. if (!engine.isPointerLock) {
  7403. return;
  7404. }
  7405. if (pinchStarted) {
  7406. return;
  7407. }
  7408. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7409. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7410. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7411. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7412. if (!noPreventDefault) {
  7413. evt.preventDefault();
  7414. }
  7415. };
  7416. this._wheel = function (event) {
  7417. var delta = 0;
  7418. if (event.wheelDelta) {
  7419. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7420. } else if (event.detail) {
  7421. delta = -event.detail / _this.wheelPrecision;
  7422. }
  7423. if (delta)
  7424. _this.inertialRadiusOffset += delta;
  7425. if (event.preventDefault) {
  7426. if (!noPreventDefault) {
  7427. event.preventDefault();
  7428. }
  7429. }
  7430. };
  7431. this._onKeyDown = function (evt) {
  7432. 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) {
  7433. var index = _this._keys.indexOf(evt.keyCode);
  7434. if (index === -1) {
  7435. _this._keys.push(evt.keyCode);
  7436. }
  7437. if (evt.preventDefault) {
  7438. if (!noPreventDefault) {
  7439. evt.preventDefault();
  7440. }
  7441. }
  7442. }
  7443. };
  7444. this._onKeyUp = function (evt) {
  7445. 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) {
  7446. var index = _this._keys.indexOf(evt.keyCode);
  7447. if (index >= 0) {
  7448. _this._keys.splice(index, 1);
  7449. }
  7450. if (evt.preventDefault) {
  7451. if (!noPreventDefault) {
  7452. evt.preventDefault();
  7453. }
  7454. }
  7455. }
  7456. };
  7457. this._onLostFocus = function () {
  7458. _this._keys = [];
  7459. pointerId = null;
  7460. };
  7461. this._onGestureStart = function (e) {
  7462. if (window.MSGesture === undefined) {
  7463. return;
  7464. }
  7465. if (!_this._MSGestureHandler) {
  7466. _this._MSGestureHandler = new MSGesture();
  7467. _this._MSGestureHandler.target = element;
  7468. }
  7469. _this._MSGestureHandler.addPointer(e.pointerId);
  7470. };
  7471. this._onGesture = function (e) {
  7472. _this.radius *= e.scale;
  7473. if (e.preventDefault) {
  7474. if (!noPreventDefault) {
  7475. e.stopPropagation();
  7476. e.preventDefault();
  7477. }
  7478. }
  7479. };
  7480. this._reset = function () {
  7481. _this._keys = [];
  7482. _this.inertialAlphaOffset = 0;
  7483. _this.inertialBetaOffset = 0;
  7484. _this.inertialRadiusOffset = 0;
  7485. previousPosition = null;
  7486. pointerId = null;
  7487. };
  7488. this._touchStart = function (event) {
  7489. if (event.touches.length == 2) {
  7490. pinchStarted = true;
  7491. _this._pinchStart(event);
  7492. }
  7493. };
  7494. this._touchMove = function (event) {
  7495. if (pinchStarted) {
  7496. _this._pinchMove(event);
  7497. }
  7498. };
  7499. this._touchEnd = function (event) {
  7500. if (pinchStarted) {
  7501. _this._pinchEnd(event);
  7502. }
  7503. };
  7504. this._pinchStart = function (event) {
  7505. pinchPointX1 = event.touches[0].clientX;
  7506. pinchPointX2 = event.touches[1].clientX;
  7507. pinchStarted = true;
  7508. };
  7509. this._pinchMove = function (event) {
  7510. var delta = 0;
  7511. var direction = 1;
  7512. var distanceXOrigine, distanceXNow;
  7513. if (event.touches.length != 2)
  7514. return;
  7515. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7516. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7517. if (distanceXNow < distanceXOrigine) {
  7518. direction = -1;
  7519. }
  7520. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7521. _this.inertialRadiusOffset += delta;
  7522. pinchPointX1 = event.touches[0].clientX;
  7523. pinchPointX2 = event.touches[1].clientX;
  7524. };
  7525. this._pinchEnd = function (event) {
  7526. pinchStarted = false;
  7527. };
  7528. }
  7529. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7530. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7531. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7532. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7533. element.addEventListener("mousemove", this._onMouseMove, false);
  7534. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7535. element.addEventListener("MSGestureChange", this._onGesture, false);
  7536. element.addEventListener('mousewheel', this._wheel, false);
  7537. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7538. element.addEventListener('touchstart', this._touchStart, false);
  7539. element.addEventListener('touchmove', this._touchMove, false);
  7540. element.addEventListener('touchend', this._touchEnd, false);
  7541. BABYLON.Tools.RegisterTopRootEvents([
  7542. { name: "keydown", handler: this._onKeyDown },
  7543. { name: "keyup", handler: this._onKeyUp },
  7544. { name: "blur", handler: this._onLostFocus }
  7545. ]);
  7546. };
  7547. ArcRotateCamera.prototype.detachControl = function (element) {
  7548. if (this._attachedElement != element) {
  7549. return;
  7550. }
  7551. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7552. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7553. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7554. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7555. element.removeEventListener("mousemove", this._onMouseMove);
  7556. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7557. element.removeEventListener("MSGestureChange", this._onGesture);
  7558. element.removeEventListener('mousewheel', this._wheel);
  7559. element.removeEventListener('DOMMouseScroll', this._wheel);
  7560. element.removeEventListener('touchstart', this._touchStart);
  7561. element.removeEventListener('touchmove', this._touchMove);
  7562. element.removeEventListener('touchend', this._touchEnd);
  7563. BABYLON.Tools.UnregisterTopRootEvents([
  7564. { name: "keydown", handler: this._onKeyDown },
  7565. { name: "keyup", handler: this._onKeyUp },
  7566. { name: "blur", handler: this._onLostFocus }
  7567. ]);
  7568. this._MSGestureHandler = null;
  7569. this._attachedElement = null;
  7570. if (this._reset) {
  7571. this._reset();
  7572. }
  7573. };
  7574. ArcRotateCamera.prototype._update = function () {
  7575. for (var index = 0; index < this._keys.length; index++) {
  7576. var keyCode = this._keys[index];
  7577. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7578. this.inertialAlphaOffset -= 0.01;
  7579. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  7580. this.inertialBetaOffset -= 0.01;
  7581. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  7582. this.inertialAlphaOffset += 0.01;
  7583. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  7584. this.inertialBetaOffset += 0.01;
  7585. }
  7586. }
  7587. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7588. this.alpha += this.inertialAlphaOffset;
  7589. this.beta += this.inertialBetaOffset;
  7590. this.radius -= this.inertialRadiusOffset;
  7591. this.inertialAlphaOffset *= this.inertia;
  7592. this.inertialBetaOffset *= this.inertia;
  7593. this.inertialRadiusOffset *= this.inertia;
  7594. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7595. this.inertialAlphaOffset = 0;
  7596. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7597. this.inertialBetaOffset = 0;
  7598. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7599. this.inertialRadiusOffset = 0;
  7600. }
  7601. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7602. this.alpha = this.lowerAlphaLimit;
  7603. }
  7604. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7605. this.alpha = this.upperAlphaLimit;
  7606. }
  7607. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7608. this.beta = this.lowerBetaLimit;
  7609. }
  7610. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7611. this.beta = this.upperBetaLimit;
  7612. }
  7613. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7614. this.radius = this.lowerRadiusLimit;
  7615. }
  7616. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7617. this.radius = this.upperRadiusLimit;
  7618. }
  7619. };
  7620. ArcRotateCamera.prototype.setPosition = function (position) {
  7621. var radiusv3 = position.subtract(this._getTargetPosition());
  7622. this.radius = radiusv3.length();
  7623. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7624. if (radiusv3.z < 0) {
  7625. this.alpha = 2 * Math.PI - this.alpha;
  7626. }
  7627. this.beta = Math.acos(radiusv3.y / this.radius);
  7628. };
  7629. ArcRotateCamera.prototype._getViewMatrix = function () {
  7630. var cosa = Math.cos(this.alpha);
  7631. var sina = Math.sin(this.alpha);
  7632. var cosb = Math.cos(this.beta);
  7633. var sinb = Math.sin(this.beta);
  7634. var target = this._getTargetPosition();
  7635. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7636. if (this.checkCollisions) {
  7637. this._collider.radius = this.collisionRadius;
  7638. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7639. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7640. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7641. this.position.copyFrom(this._previousPosition);
  7642. this.alpha = this._previousAlpha;
  7643. this.beta = this._previousBeta;
  7644. this.radius = this._previousRadius;
  7645. if (this.onCollide) {
  7646. this.onCollide(this._collider.collidedMesh);
  7647. }
  7648. }
  7649. }
  7650. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7651. this._previousAlpha = this.alpha;
  7652. this._previousBeta = this.beta;
  7653. this._previousRadius = this.radius;
  7654. this._previousPosition.copyFrom(this.position);
  7655. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7656. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7657. return this._viewMatrix;
  7658. };
  7659. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7660. meshes = meshes || this.getScene().meshes;
  7661. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7662. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7663. this.radius = distance * this.zoomOnFactor;
  7664. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7665. };
  7666. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7667. var meshesOrMinMaxVector;
  7668. var distance;
  7669. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7670. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7671. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7672. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7673. } else {
  7674. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7675. distance = meshesOrMinMaxVectorAndDistance.distance;
  7676. }
  7677. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7678. this.maxZ = distance * 2;
  7679. };
  7680. return ArcRotateCamera;
  7681. })(BABYLON.Camera);
  7682. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7683. })(BABYLON || (BABYLON = {}));
  7684. var __extends = this.__extends || function (d, b) {
  7685. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7686. function __() { this.constructor = d; }
  7687. __.prototype = b.prototype;
  7688. d.prototype = new __();
  7689. };
  7690. var BABYLON;
  7691. (function (BABYLON) {
  7692. var DeviceOrientationCamera = (function (_super) {
  7693. __extends(DeviceOrientationCamera, _super);
  7694. function DeviceOrientationCamera(name, position, scene) {
  7695. var _this = this;
  7696. _super.call(this, name, position, scene);
  7697. this._offsetX = null;
  7698. this._offsetY = null;
  7699. this._orientationGamma = 0;
  7700. this._orientationBeta = 0;
  7701. this._initialOrientationGamma = 0;
  7702. this._initialOrientationBeta = 0;
  7703. this.angularSensibility = 10000.0;
  7704. this.moveSensibility = 50.0;
  7705. window.addEventListener("resize", function () {
  7706. _this._initialOrientationGamma = null;
  7707. }, false);
  7708. }
  7709. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7710. var _this = this;
  7711. if (this._attachedCanvas) {
  7712. return;
  7713. }
  7714. this._attachedCanvas = canvas;
  7715. if (!this._orientationChanged) {
  7716. this._orientationChanged = function (evt) {
  7717. if (!_this._initialOrientationGamma) {
  7718. _this._initialOrientationGamma = evt.gamma;
  7719. _this._initialOrientationBeta = evt.beta;
  7720. }
  7721. _this._orientationGamma = evt.gamma;
  7722. _this._orientationBeta = evt.beta;
  7723. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7724. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7725. };
  7726. }
  7727. window.addEventListener("deviceorientation", this._orientationChanged);
  7728. };
  7729. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7730. if (this._attachedCanvas != canvas) {
  7731. return;
  7732. }
  7733. window.removeEventListener("deviceorientation", this._orientationChanged);
  7734. this._attachedCanvas = null;
  7735. this._orientationGamma = 0;
  7736. this._orientationBeta = 0;
  7737. this._initialOrientationGamma = 0;
  7738. this._initialOrientationBeta = 0;
  7739. };
  7740. DeviceOrientationCamera.prototype._checkInputs = function () {
  7741. if (!this._offsetX) {
  7742. return;
  7743. }
  7744. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7745. var speed = this._computeLocalCameraSpeed();
  7746. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7747. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7748. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7749. };
  7750. return DeviceOrientationCamera;
  7751. })(BABYLON.FreeCamera);
  7752. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7753. })(BABYLON || (BABYLON = {}));
  7754. var BABYLON;
  7755. (function (BABYLON) {
  7756. var RenderingManager = (function () {
  7757. function RenderingManager(scene) {
  7758. this._renderingGroups = new Array();
  7759. this._scene = scene;
  7760. }
  7761. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  7762. if (this._scene._activeParticleSystems.length === 0) {
  7763. return;
  7764. }
  7765. var beforeParticlesDate = new Date().getTime();
  7766. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  7767. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  7768. if (particleSystem.renderingGroupId !== index) {
  7769. continue;
  7770. }
  7771. this._clearDepthBuffer();
  7772. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  7773. this._scene._activeParticles += particleSystem.render();
  7774. }
  7775. }
  7776. this._scene._particlesDuration += new Date().getTime() - beforeParticlesDate;
  7777. };
  7778. RenderingManager.prototype._renderSprites = function (index) {
  7779. if (this._scene.spriteManagers.length === 0) {
  7780. return;
  7781. }
  7782. var beforeSpritessDate = new Date().getTime();
  7783. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  7784. var spriteManager = this._scene.spriteManagers[id];
  7785. if (spriteManager.renderingGroupId === index) {
  7786. this._clearDepthBuffer();
  7787. spriteManager.render();
  7788. }
  7789. }
  7790. this._scene._spritesDuration += new Date().getTime() - beforeSpritessDate;
  7791. };
  7792. RenderingManager.prototype._clearDepthBuffer = function () {
  7793. if (this._depthBufferAlreadyCleaned) {
  7794. return;
  7795. }
  7796. this._scene.getEngine().clear(0, false, true);
  7797. this._depthBufferAlreadyCleaned = true;
  7798. };
  7799. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  7800. var _this = this;
  7801. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  7802. this._depthBufferAlreadyCleaned = false;
  7803. var renderingGroup = this._renderingGroups[index];
  7804. if (renderingGroup) {
  7805. this._clearDepthBuffer();
  7806. if (!renderingGroup.render(customRenderFunction, function () {
  7807. if (renderSprites) {
  7808. _this._renderSprites(index);
  7809. }
  7810. })) {
  7811. this._renderingGroups.splice(index, 1);
  7812. }
  7813. } else if (renderSprites) {
  7814. this._renderSprites(index);
  7815. }
  7816. if (renderParticles) {
  7817. this._renderParticles(index, activeMeshes);
  7818. }
  7819. }
  7820. };
  7821. RenderingManager.prototype.reset = function () {
  7822. for (var index in this._renderingGroups) {
  7823. var renderingGroup = this._renderingGroups[index];
  7824. renderingGroup.prepare();
  7825. }
  7826. };
  7827. RenderingManager.prototype.dispatch = function (subMesh) {
  7828. var mesh = subMesh.getMesh();
  7829. var renderingGroupId = mesh.renderingGroupId || 0;
  7830. if (!this._renderingGroups[renderingGroupId]) {
  7831. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  7832. }
  7833. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  7834. };
  7835. RenderingManager.MAX_RENDERINGGROUPS = 4;
  7836. return RenderingManager;
  7837. })();
  7838. BABYLON.RenderingManager = RenderingManager;
  7839. })(BABYLON || (BABYLON = {}));
  7840. var BABYLON;
  7841. (function (BABYLON) {
  7842. var RenderingGroup = (function () {
  7843. function RenderingGroup(index, scene) {
  7844. this.index = index;
  7845. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  7846. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  7847. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  7848. this._scene = scene;
  7849. }
  7850. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  7851. if (customRenderFunction) {
  7852. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  7853. return true;
  7854. }
  7855. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  7856. return false;
  7857. }
  7858. var engine = this._scene.getEngine();
  7859. var subIndex;
  7860. var submesh;
  7861. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  7862. submesh = this._opaqueSubMeshes.data[subIndex];
  7863. this._activeVertices += submesh.verticesCount;
  7864. submesh.render();
  7865. }
  7866. engine.setAlphaTesting(true);
  7867. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  7868. submesh = this._alphaTestSubMeshes.data[subIndex];
  7869. this._activeVertices += submesh.verticesCount;
  7870. submesh.render();
  7871. }
  7872. engine.setAlphaTesting(false);
  7873. if (beforeTransparents) {
  7874. beforeTransparents();
  7875. }
  7876. if (this._transparentSubMeshes.length) {
  7877. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  7878. submesh = this._transparentSubMeshes.data[subIndex];
  7879. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  7880. }
  7881. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  7882. sortedArray.sort(function (a, b) {
  7883. if (a._distanceToCamera < b._distanceToCamera) {
  7884. return 1;
  7885. }
  7886. if (a._distanceToCamera > b._distanceToCamera) {
  7887. return -1;
  7888. }
  7889. return 0;
  7890. });
  7891. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  7892. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  7893. submesh = sortedArray[subIndex];
  7894. this._activeVertices += submesh.verticesCount;
  7895. submesh.render();
  7896. }
  7897. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  7898. }
  7899. return true;
  7900. };
  7901. RenderingGroup.prototype.prepare = function () {
  7902. this._opaqueSubMeshes.reset();
  7903. this._transparentSubMeshes.reset();
  7904. this._alphaTestSubMeshes.reset();
  7905. };
  7906. RenderingGroup.prototype.dispatch = function (subMesh) {
  7907. var material = subMesh.getMaterial();
  7908. var mesh = subMesh.getMesh();
  7909. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  7910. if (material.alpha > 0 || mesh.visibility < 1.0) {
  7911. this._transparentSubMeshes.push(subMesh);
  7912. }
  7913. } else if (material.needAlphaTesting()) {
  7914. this._alphaTestSubMeshes.push(subMesh);
  7915. } else {
  7916. this._opaqueSubMeshes.push(subMesh);
  7917. }
  7918. };
  7919. return RenderingGroup;
  7920. })();
  7921. BABYLON.RenderingGroup = RenderingGroup;
  7922. })(BABYLON || (BABYLON = {}));
  7923. var BABYLON;
  7924. (function (BABYLON) {
  7925. var Scene = (function () {
  7926. function Scene(engine) {
  7927. this.autoClear = true;
  7928. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7929. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7930. this.forceWireframe = false;
  7931. this.cameraToUseForPointers = null;
  7932. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  7933. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7934. this.fogDensity = 0.1;
  7935. this.fogStart = 0;
  7936. this.fogEnd = 1000.0;
  7937. this.lightsEnabled = true;
  7938. this.lights = new Array();
  7939. this.cameras = new Array();
  7940. this.activeCameras = new Array();
  7941. this.meshes = new Array();
  7942. this._geometries = new Array();
  7943. this.materials = new Array();
  7944. this.multiMaterials = new Array();
  7945. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7946. this.texturesEnabled = true;
  7947. this.textures = new Array();
  7948. this.particlesEnabled = true;
  7949. this.particleSystems = new Array();
  7950. this.spriteManagers = new Array();
  7951. this.layers = new Array();
  7952. this.skeletons = new Array();
  7953. this.lensFlareSystems = new Array();
  7954. this.collisionsEnabled = true;
  7955. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7956. this.postProcessesEnabled = true;
  7957. this.renderTargetsEnabled = true;
  7958. this.customRenderTargets = new Array();
  7959. this.importedMeshesFiles = new Array();
  7960. this._actionManagers = new Array();
  7961. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7962. this.proceduralTexturesEnabled = true;
  7963. this._proceduralTextures = new Array();
  7964. this._totalVertices = 0;
  7965. this._activeVertices = 0;
  7966. this._activeParticles = 0;
  7967. this._lastFrameDuration = 0;
  7968. this._evaluateActiveMeshesDuration = 0;
  7969. this._renderTargetsDuration = 0;
  7970. this._particlesDuration = 0;
  7971. this._renderDuration = 0;
  7972. this._spritesDuration = 0;
  7973. this._animationRatio = 0;
  7974. this._renderId = 0;
  7975. this._executeWhenReadyTimeoutId = -1;
  7976. this._toBeDisposed = new BABYLON.SmartArray(256);
  7977. this._onReadyCallbacks = new Array();
  7978. this._pendingData = [];
  7979. this._onBeforeRenderCallbacks = new Array();
  7980. this._activeMeshes = new BABYLON.SmartArray(256);
  7981. this._processedMaterials = new BABYLON.SmartArray(256);
  7982. this._renderTargets = new BABYLON.SmartArray(256);
  7983. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7984. this._activeSkeletons = new BABYLON.SmartArray(32);
  7985. this._activeAnimatables = new Array();
  7986. this._transformMatrix = BABYLON.Matrix.Zero();
  7987. this._scaledPosition = BABYLON.Vector3.Zero();
  7988. this._scaledVelocity = BABYLON.Vector3.Zero();
  7989. this._engine = engine;
  7990. engine.scenes.push(this);
  7991. this._renderingManager = new BABYLON.RenderingManager(this);
  7992. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7993. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7994. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7995. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7996. this.attachControl();
  7997. }
  7998. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7999. get: function () {
  8000. return this._meshUnderPointer;
  8001. },
  8002. enumerable: true,
  8003. configurable: true
  8004. });
  8005. Object.defineProperty(Scene.prototype, "pointerX", {
  8006. get: function () {
  8007. return this._pointerX;
  8008. },
  8009. enumerable: true,
  8010. configurable: true
  8011. });
  8012. Object.defineProperty(Scene.prototype, "pointerY", {
  8013. get: function () {
  8014. return this._pointerY;
  8015. },
  8016. enumerable: true,
  8017. configurable: true
  8018. });
  8019. Scene.prototype.getBoundingBoxRenderer = function () {
  8020. return this._boundingBoxRenderer;
  8021. };
  8022. Scene.prototype.getOutlineRenderer = function () {
  8023. return this._outlineRenderer;
  8024. };
  8025. Scene.prototype.getEngine = function () {
  8026. return this._engine;
  8027. };
  8028. Scene.prototype.getTotalVertices = function () {
  8029. return this._totalVertices;
  8030. };
  8031. Scene.prototype.getActiveVertices = function () {
  8032. return this._activeVertices;
  8033. };
  8034. Scene.prototype.getActiveParticles = function () {
  8035. return this._activeParticles;
  8036. };
  8037. Scene.prototype.getLastFrameDuration = function () {
  8038. return this._lastFrameDuration;
  8039. };
  8040. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8041. return this._evaluateActiveMeshesDuration;
  8042. };
  8043. Scene.prototype.getActiveMeshes = function () {
  8044. return this._activeMeshes;
  8045. };
  8046. Scene.prototype.getRenderTargetsDuration = function () {
  8047. return this._renderTargetsDuration;
  8048. };
  8049. Scene.prototype.getRenderDuration = function () {
  8050. return this._renderDuration;
  8051. };
  8052. Scene.prototype.getParticlesDuration = function () {
  8053. return this._particlesDuration;
  8054. };
  8055. Scene.prototype.getSpritesDuration = function () {
  8056. return this._spritesDuration;
  8057. };
  8058. Scene.prototype.getAnimationRatio = function () {
  8059. return this._animationRatio;
  8060. };
  8061. Scene.prototype.getRenderId = function () {
  8062. return this._renderId;
  8063. };
  8064. Scene.prototype._updatePointerPosition = function (evt) {
  8065. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8066. this._pointerX = evt.clientX - canvasRect.left;
  8067. this._pointerY = evt.clientY - canvasRect.top;
  8068. if (this.cameraToUseForPointers) {
  8069. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8070. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8071. }
  8072. };
  8073. Scene.prototype.attachControl = function () {
  8074. var _this = this;
  8075. this._onPointerMove = function (evt) {
  8076. var canvas = _this._engine.getRenderingCanvas();
  8077. _this._updatePointerPosition(evt);
  8078. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  8079. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  8080. }, false, _this.cameraToUseForPointers);
  8081. if (pickResult.hit) {
  8082. _this._meshUnderPointer = pickResult.pickedMesh;
  8083. _this.setPointerOverMesh(pickResult.pickedMesh);
  8084. canvas.style.cursor = "pointer";
  8085. } else {
  8086. _this.setPointerOverMesh(null);
  8087. canvas.style.cursor = "";
  8088. _this._meshUnderPointer = null;
  8089. }
  8090. };
  8091. this._onPointerDown = function (evt) {
  8092. var predicate = null;
  8093. if (!_this.onPointerDown) {
  8094. predicate = function (mesh) {
  8095. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8096. };
  8097. }
  8098. _this._updatePointerPosition(evt);
  8099. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8100. if (pickResult.hit) {
  8101. if (pickResult.pickedMesh.actionManager) {
  8102. switch (evt.button) {
  8103. case 0:
  8104. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  8105. break;
  8106. case 1:
  8107. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  8108. break;
  8109. case 2:
  8110. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  8111. break;
  8112. }
  8113. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  8114. }
  8115. }
  8116. if (_this.onPointerDown) {
  8117. _this.onPointerDown(evt, pickResult);
  8118. }
  8119. };
  8120. this._onKeyDown = function (evt) {
  8121. if (_this.actionManager) {
  8122. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8123. }
  8124. };
  8125. this._onKeyUp = function (evt) {
  8126. if (_this.actionManager) {
  8127. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8128. }
  8129. };
  8130. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8131. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8132. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8133. window.addEventListener("keydown", this._onKeyDown, false);
  8134. window.addEventListener("keyup", this._onKeyUp, false);
  8135. };
  8136. Scene.prototype.detachControl = function () {
  8137. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8138. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8139. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8140. window.removeEventListener("keydown", this._onKeyDown);
  8141. window.removeEventListener("keyup", this._onKeyUp);
  8142. };
  8143. Scene.prototype.isReady = function () {
  8144. if (this._pendingData.length > 0) {
  8145. return false;
  8146. }
  8147. for (var index = 0; index < this._geometries.length; index++) {
  8148. var geometry = this._geometries[index];
  8149. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8150. return false;
  8151. }
  8152. }
  8153. for (index = 0; index < this.meshes.length; index++) {
  8154. var mesh = this.meshes[index];
  8155. if (!mesh.isReady()) {
  8156. return false;
  8157. }
  8158. var mat = mesh.material;
  8159. if (mat) {
  8160. if (!mat.isReady(mesh)) {
  8161. return false;
  8162. }
  8163. }
  8164. }
  8165. return true;
  8166. };
  8167. Scene.prototype.registerBeforeRender = function (func) {
  8168. this._onBeforeRenderCallbacks.push(func);
  8169. };
  8170. Scene.prototype.unregisterBeforeRender = function (func) {
  8171. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8172. if (index > -1) {
  8173. this._onBeforeRenderCallbacks.splice(index, 1);
  8174. }
  8175. };
  8176. Scene.prototype._addPendingData = function (data) {
  8177. this._pendingData.push(data);
  8178. };
  8179. Scene.prototype._removePendingData = function (data) {
  8180. var index = this._pendingData.indexOf(data);
  8181. if (index !== -1) {
  8182. this._pendingData.splice(index, 1);
  8183. }
  8184. };
  8185. Scene.prototype.getWaitingItemsCount = function () {
  8186. return this._pendingData.length;
  8187. };
  8188. Scene.prototype.executeWhenReady = function (func) {
  8189. var _this = this;
  8190. this._onReadyCallbacks.push(func);
  8191. if (this._executeWhenReadyTimeoutId !== -1) {
  8192. return;
  8193. }
  8194. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8195. _this._checkIsReady();
  8196. }, 150);
  8197. };
  8198. Scene.prototype._checkIsReady = function () {
  8199. var _this = this;
  8200. if (this.isReady()) {
  8201. this._onReadyCallbacks.forEach(function (func) {
  8202. func();
  8203. });
  8204. this._onReadyCallbacks = [];
  8205. this._executeWhenReadyTimeoutId = -1;
  8206. return;
  8207. }
  8208. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8209. _this._checkIsReady();
  8210. }, 150);
  8211. };
  8212. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8213. if (speedRatio === undefined) {
  8214. speedRatio = 1.0;
  8215. }
  8216. this.stopAnimation(target);
  8217. if (!animatable) {
  8218. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8219. }
  8220. if (target.animations) {
  8221. animatable.appendAnimations(target, target.animations);
  8222. }
  8223. if (target.getAnimatables) {
  8224. var animatables = target.getAnimatables();
  8225. for (var index = 0; index < animatables.length; index++) {
  8226. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8227. }
  8228. }
  8229. return animatable;
  8230. };
  8231. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8232. if (speedRatio === undefined) {
  8233. speedRatio = 1.0;
  8234. }
  8235. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8236. return animatable;
  8237. };
  8238. Scene.prototype.getAnimatableByTarget = function (target) {
  8239. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8240. if (this._activeAnimatables[index].target === target) {
  8241. return this._activeAnimatables[index];
  8242. }
  8243. }
  8244. return null;
  8245. };
  8246. Scene.prototype.stopAnimation = function (target) {
  8247. var animatable = this.getAnimatableByTarget(target);
  8248. if (animatable) {
  8249. animatable.stop();
  8250. }
  8251. };
  8252. Scene.prototype._animate = function () {
  8253. if (!this._animationStartDate) {
  8254. this._animationStartDate = new Date().getTime();
  8255. }
  8256. var now = new Date().getTime();
  8257. var delay = now - this._animationStartDate;
  8258. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8259. if (!this._activeAnimatables[index]._animate(delay)) {
  8260. this._activeAnimatables.splice(index, 1);
  8261. index--;
  8262. }
  8263. }
  8264. };
  8265. Scene.prototype.getViewMatrix = function () {
  8266. return this._viewMatrix;
  8267. };
  8268. Scene.prototype.getProjectionMatrix = function () {
  8269. return this._projectionMatrix;
  8270. };
  8271. Scene.prototype.getTransformMatrix = function () {
  8272. return this._transformMatrix;
  8273. };
  8274. Scene.prototype.setTransformMatrix = function (view, projection) {
  8275. this._viewMatrix = view;
  8276. this._projectionMatrix = projection;
  8277. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8278. };
  8279. Scene.prototype.setActiveCameraByID = function (id) {
  8280. var camera = this.getCameraByID(id);
  8281. if (camera) {
  8282. this.activeCamera = camera;
  8283. return camera;
  8284. }
  8285. return null;
  8286. };
  8287. Scene.prototype.setActiveCameraByName = function (name) {
  8288. var camera = this.getCameraByName(name);
  8289. if (camera) {
  8290. this.activeCamera = camera;
  8291. return camera;
  8292. }
  8293. return null;
  8294. };
  8295. Scene.prototype.getMaterialByID = function (id) {
  8296. for (var index = 0; index < this.materials.length; index++) {
  8297. if (this.materials[index].id === id) {
  8298. return this.materials[index];
  8299. }
  8300. }
  8301. return null;
  8302. };
  8303. Scene.prototype.getMaterialByName = function (name) {
  8304. for (var index = 0; index < this.materials.length; index++) {
  8305. if (this.materials[index].name === name) {
  8306. return this.materials[index];
  8307. }
  8308. }
  8309. return null;
  8310. };
  8311. Scene.prototype.getCameraByID = function (id) {
  8312. for (var index = 0; index < this.cameras.length; index++) {
  8313. if (this.cameras[index].id === id) {
  8314. return this.cameras[index];
  8315. }
  8316. }
  8317. return null;
  8318. };
  8319. Scene.prototype.getCameraByName = function (name) {
  8320. for (var index = 0; index < this.cameras.length; index++) {
  8321. if (this.cameras[index].name === name) {
  8322. return this.cameras[index];
  8323. }
  8324. }
  8325. return null;
  8326. };
  8327. Scene.prototype.getLightByName = function (name) {
  8328. for (var index = 0; index < this.lights.length; index++) {
  8329. if (this.lights[index].name === name) {
  8330. return this.lights[index];
  8331. }
  8332. }
  8333. return null;
  8334. };
  8335. Scene.prototype.getLightByID = function (id) {
  8336. for (var index = 0; index < this.lights.length; index++) {
  8337. if (this.lights[index].id === id) {
  8338. return this.lights[index];
  8339. }
  8340. }
  8341. return null;
  8342. };
  8343. Scene.prototype.getGeometryByID = function (id) {
  8344. for (var index = 0; index < this._geometries.length; index++) {
  8345. if (this._geometries[index].id === id) {
  8346. return this._geometries[index];
  8347. }
  8348. }
  8349. return null;
  8350. };
  8351. Scene.prototype.pushGeometry = function (geometry, force) {
  8352. if (!force && this.getGeometryByID(geometry.id)) {
  8353. return false;
  8354. }
  8355. this._geometries.push(geometry);
  8356. return true;
  8357. };
  8358. Scene.prototype.getGeometries = function () {
  8359. return this._geometries;
  8360. };
  8361. Scene.prototype.getMeshByID = function (id) {
  8362. for (var index = 0; index < this.meshes.length; index++) {
  8363. if (this.meshes[index].id === id) {
  8364. return this.meshes[index];
  8365. }
  8366. }
  8367. return null;
  8368. };
  8369. Scene.prototype.getLastMeshByID = function (id) {
  8370. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8371. if (this.meshes[index].id === id) {
  8372. return this.meshes[index];
  8373. }
  8374. }
  8375. return null;
  8376. };
  8377. Scene.prototype.getLastEntryByID = function (id) {
  8378. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8379. if (this.meshes[index].id === id) {
  8380. return this.meshes[index];
  8381. }
  8382. }
  8383. for (index = this.cameras.length - 1; index >= 0; index--) {
  8384. if (this.cameras[index].id === id) {
  8385. return this.cameras[index];
  8386. }
  8387. }
  8388. for (index = this.lights.length - 1; index >= 0; index--) {
  8389. if (this.lights[index].id === id) {
  8390. return this.lights[index];
  8391. }
  8392. }
  8393. return null;
  8394. };
  8395. Scene.prototype.getMeshByName = function (name) {
  8396. for (var index = 0; index < this.meshes.length; index++) {
  8397. if (this.meshes[index].name === name) {
  8398. return this.meshes[index];
  8399. }
  8400. }
  8401. return null;
  8402. };
  8403. Scene.prototype.getLastSkeletonByID = function (id) {
  8404. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8405. if (this.skeletons[index].id === id) {
  8406. return this.skeletons[index];
  8407. }
  8408. }
  8409. return null;
  8410. };
  8411. Scene.prototype.getSkeletonById = function (id) {
  8412. for (var index = 0; index < this.skeletons.length; index++) {
  8413. if (this.skeletons[index].id === id) {
  8414. return this.skeletons[index];
  8415. }
  8416. }
  8417. return null;
  8418. };
  8419. Scene.prototype.getSkeletonByName = function (name) {
  8420. for (var index = 0; index < this.skeletons.length; index++) {
  8421. if (this.skeletons[index].name === name) {
  8422. return this.skeletons[index];
  8423. }
  8424. }
  8425. return null;
  8426. };
  8427. Scene.prototype.isActiveMesh = function (mesh) {
  8428. return (this._activeMeshes.indexOf(mesh) !== -1);
  8429. };
  8430. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8431. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8432. var material = subMesh.getMaterial();
  8433. if (mesh.showSubMeshesBoundingBox) {
  8434. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8435. }
  8436. if (material) {
  8437. if (material.getRenderTargetTextures) {
  8438. if (this._processedMaterials.indexOf(material) === -1) {
  8439. this._processedMaterials.push(material);
  8440. this._renderTargets.concat(material.getRenderTargetTextures());
  8441. }
  8442. }
  8443. this._activeVertices += subMesh.verticesCount;
  8444. this._renderingManager.dispatch(subMesh);
  8445. }
  8446. }
  8447. };
  8448. Scene.prototype._evaluateActiveMeshes = function () {
  8449. this._activeMeshes.reset();
  8450. this._renderingManager.reset();
  8451. this._processedMaterials.reset();
  8452. this._activeParticleSystems.reset();
  8453. this._activeSkeletons.reset();
  8454. this._boundingBoxRenderer.reset();
  8455. if (!this._frustumPlanes) {
  8456. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8457. } else {
  8458. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8459. }
  8460. var meshes;
  8461. var len;
  8462. if (this._selectionOctree) {
  8463. var selection = this._selectionOctree.select(this._frustumPlanes);
  8464. meshes = selection.data;
  8465. len = selection.length;
  8466. } else {
  8467. len = this.meshes.length;
  8468. meshes = this.meshes;
  8469. }
  8470. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8471. var mesh = meshes[meshIndex];
  8472. this._totalVertices += mesh.getTotalVertices();
  8473. if (!mesh.isReady()) {
  8474. continue;
  8475. }
  8476. mesh.computeWorldMatrix();
  8477. mesh._preActivate();
  8478. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8479. this._meshesForIntersections.pushNoDuplicate(mesh);
  8480. }
  8481. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8482. this._activeMeshes.push(mesh);
  8483. mesh._activate(this._renderId);
  8484. this._activeMesh(mesh);
  8485. }
  8486. }
  8487. var beforeParticlesDate = new Date().getTime();
  8488. if (this.particlesEnabled) {
  8489. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8490. var particleSystem = this.particleSystems[particleIndex];
  8491. if (!particleSystem.isStarted()) {
  8492. continue;
  8493. }
  8494. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8495. this._activeParticleSystems.push(particleSystem);
  8496. particleSystem.animate();
  8497. }
  8498. }
  8499. }
  8500. this._particlesDuration += new Date().getTime() - beforeParticlesDate;
  8501. };
  8502. Scene.prototype._activeMesh = function (mesh) {
  8503. if (mesh.skeleton) {
  8504. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8505. }
  8506. if (mesh.showBoundingBox) {
  8507. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8508. }
  8509. if (mesh.subMeshes) {
  8510. var len;
  8511. var subMeshes;
  8512. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8513. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8514. len = intersections.length;
  8515. subMeshes = intersections.data;
  8516. } else {
  8517. subMeshes = mesh.subMeshes;
  8518. len = subMeshes.length;
  8519. }
  8520. for (var subIndex = 0; subIndex < len; subIndex++) {
  8521. var subMesh = subMeshes[subIndex];
  8522. this._evaluateSubMesh(subMesh, mesh);
  8523. }
  8524. }
  8525. };
  8526. Scene.prototype.updateTransformMatrix = function (force) {
  8527. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8528. };
  8529. Scene.prototype._renderForCamera = function (camera) {
  8530. var engine = this._engine;
  8531. this.activeCamera = camera;
  8532. if (!this.activeCamera)
  8533. throw new Error("Active camera not set");
  8534. engine.setViewport(this.activeCamera.viewport);
  8535. this._renderId++;
  8536. this.updateTransformMatrix();
  8537. if (this.beforeCameraRender) {
  8538. this.beforeCameraRender(this.activeCamera);
  8539. }
  8540. var beforeEvaluateActiveMeshesDate = new Date().getTime();
  8541. this._evaluateActiveMeshes();
  8542. this._evaluateActiveMeshesDuration += new Date().getTime() - beforeEvaluateActiveMeshesDate;
  8543. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8544. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8545. skeleton.prepare();
  8546. }
  8547. var beforeRenderTargetDate = new Date().getTime();
  8548. if (this.renderTargetsEnabled) {
  8549. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8550. var renderTarget = this._renderTargets.data[renderIndex];
  8551. if (renderTarget._shouldRender()) {
  8552. this._renderId++;
  8553. renderTarget.render();
  8554. }
  8555. }
  8556. this._renderId++;
  8557. }
  8558. if (this._renderTargets.length > 0) {
  8559. engine.restoreDefaultFramebuffer();
  8560. }
  8561. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  8562. this.postProcessManager._prepareFrame();
  8563. var beforeRenderDate = new Date().getTime();
  8564. if (this.layers.length) {
  8565. engine.setDepthBuffer(false);
  8566. var layerIndex;
  8567. var layer;
  8568. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8569. layer = this.layers[layerIndex];
  8570. if (layer.isBackground) {
  8571. layer.render();
  8572. }
  8573. }
  8574. engine.setDepthBuffer(true);
  8575. }
  8576. this._renderingManager.render(null, null, true, true);
  8577. this._boundingBoxRenderer.render();
  8578. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8579. this.lensFlareSystems[lensFlareSystemIndex].render();
  8580. }
  8581. if (this.layers.length) {
  8582. engine.setDepthBuffer(false);
  8583. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8584. layer = this.layers[layerIndex];
  8585. if (!layer.isBackground) {
  8586. layer.render();
  8587. }
  8588. }
  8589. engine.setDepthBuffer(true);
  8590. }
  8591. this._renderDuration += new Date().getTime() - beforeRenderDate;
  8592. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8593. this.activeCamera._updateFromScene();
  8594. this._renderTargets.reset();
  8595. if (this.afterCameraRender) {
  8596. this.afterCameraRender(this.activeCamera);
  8597. }
  8598. };
  8599. Scene.prototype._processSubCameras = function (camera) {
  8600. if (camera.subCameras.length == 0) {
  8601. this._renderForCamera(camera);
  8602. return;
  8603. }
  8604. for (var index = 0; index < camera.subCameras.length; index++) {
  8605. this._renderForCamera(camera.subCameras[index]);
  8606. }
  8607. this.activeCamera = camera;
  8608. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8609. this.activeCamera._updateFromScene();
  8610. };
  8611. Scene.prototype._checkIntersections = function () {
  8612. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8613. var sourceMesh = this._meshesForIntersections.data[index];
  8614. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8615. var action = sourceMesh.actionManager.actions[actionIndex];
  8616. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8617. var otherMesh = action.getTriggerParameter();
  8618. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  8619. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8620. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8621. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  8622. sourceMesh._intersectionsInProgress.push(otherMesh);
  8623. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8624. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  8625. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8626. if (indexOfOther > -1) {
  8627. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8628. }
  8629. }
  8630. }
  8631. }
  8632. }
  8633. };
  8634. Scene.prototype.render = function () {
  8635. var startDate = new Date().getTime();
  8636. this._particlesDuration = 0;
  8637. this._spritesDuration = 0;
  8638. this._activeParticles = 0;
  8639. this._renderDuration = 0;
  8640. this._evaluateActiveMeshesDuration = 0;
  8641. this._totalVertices = 0;
  8642. this._activeVertices = 0;
  8643. this._meshesForIntersections.reset();
  8644. if (this.actionManager) {
  8645. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8646. }
  8647. if (this.beforeRender) {
  8648. this.beforeRender();
  8649. }
  8650. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8651. this._onBeforeRenderCallbacks[callbackIndex]();
  8652. }
  8653. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  8654. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8655. this._animate();
  8656. if (this._physicsEngine) {
  8657. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8658. }
  8659. var beforeRenderTargetDate = new Date().getTime();
  8660. var engine = this.getEngine();
  8661. if (this.renderTargetsEnabled) {
  8662. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8663. var renderTarget = this.customRenderTargets[customIndex];
  8664. if (renderTarget._shouldRender()) {
  8665. this._renderId++;
  8666. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8667. if (!this.activeCamera)
  8668. throw new Error("Active camera not set");
  8669. engine.setViewport(this.activeCamera.viewport);
  8670. this.updateTransformMatrix();
  8671. renderTarget.render();
  8672. }
  8673. }
  8674. this._renderId++;
  8675. }
  8676. if (this.customRenderTargets.length > 0) {
  8677. engine.restoreDefaultFramebuffer();
  8678. }
  8679. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  8680. if (this.proceduralTexturesEnabled) {
  8681. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8682. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8683. if (proceduralTexture._shouldRender()) {
  8684. proceduralTexture.render();
  8685. }
  8686. }
  8687. }
  8688. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  8689. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8690. var light = this.lights[lightIndex];
  8691. var shadowGenerator = light.getShadowGenerator();
  8692. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8693. this._renderTargets.push(shadowGenerator.getShadowMap());
  8694. }
  8695. }
  8696. this.postProcessRenderPipelineManager.update();
  8697. if (this.activeCameras.length > 0) {
  8698. var currentRenderId = this._renderId;
  8699. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8700. this._renderId = currentRenderId;
  8701. this._processSubCameras(this.activeCameras[cameraIndex]);
  8702. }
  8703. } else {
  8704. if (!this.activeCamera) {
  8705. throw new Error("No camera defined");
  8706. }
  8707. this._processSubCameras(this.activeCamera);
  8708. }
  8709. this._checkIntersections();
  8710. if (this.afterRender) {
  8711. this.afterRender();
  8712. }
  8713. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8714. this._toBeDisposed.data[index].dispose();
  8715. this._toBeDisposed[index] = null;
  8716. }
  8717. this._toBeDisposed.reset();
  8718. this._lastFrameDuration = new Date().getTime() - startDate;
  8719. };
  8720. Scene.prototype.dispose = function () {
  8721. this.beforeRender = null;
  8722. this.afterRender = null;
  8723. this.skeletons = [];
  8724. this._boundingBoxRenderer.dispose();
  8725. if (this.onDispose) {
  8726. this.onDispose();
  8727. }
  8728. this.detachControl();
  8729. var canvas = this._engine.getRenderingCanvas();
  8730. var index;
  8731. for (index = 0; index < this.cameras.length; index++) {
  8732. this.cameras[index].detachControl(canvas);
  8733. }
  8734. while (this.lights.length) {
  8735. this.lights[0].dispose();
  8736. }
  8737. while (this.meshes.length) {
  8738. this.meshes[0].dispose(true);
  8739. }
  8740. while (this.cameras.length) {
  8741. this.cameras[0].dispose();
  8742. }
  8743. while (this.materials.length) {
  8744. this.materials[0].dispose();
  8745. }
  8746. while (this.particleSystems.length) {
  8747. this.particleSystems[0].dispose();
  8748. }
  8749. while (this.spriteManagers.length) {
  8750. this.spriteManagers[0].dispose();
  8751. }
  8752. while (this.layers.length) {
  8753. this.layers[0].dispose();
  8754. }
  8755. while (this.textures.length) {
  8756. this.textures[0].dispose();
  8757. }
  8758. this.postProcessManager.dispose();
  8759. if (this._physicsEngine) {
  8760. this.disablePhysicsEngine();
  8761. }
  8762. index = this._engine.scenes.indexOf(this);
  8763. if (index > -1) {
  8764. this._engine.scenes.splice(index, 1);
  8765. }
  8766. this._engine.wipeCaches();
  8767. };
  8768. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8769. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8770. position.divideToRef(collider.radius, this._scaledPosition);
  8771. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8772. collider.retry = 0;
  8773. collider.initialVelocity = this._scaledVelocity;
  8774. collider.initialPosition = this._scaledPosition;
  8775. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8776. finalPosition.multiplyInPlace(collider.radius);
  8777. };
  8778. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8779. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8780. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8781. if (collider.retry >= maximumRetry) {
  8782. finalPosition.copyFrom(position);
  8783. return;
  8784. }
  8785. collider._initialize(position, velocity, closeDistance);
  8786. for (var index = 0; index < this.meshes.length; index++) {
  8787. var mesh = this.meshes[index];
  8788. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8789. mesh._checkCollision(collider);
  8790. }
  8791. }
  8792. if (!collider.collisionFound) {
  8793. position.addToRef(velocity, finalPosition);
  8794. return;
  8795. }
  8796. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  8797. collider._getResponse(position, velocity);
  8798. }
  8799. if (velocity.length() <= closeDistance) {
  8800. finalPosition.copyFrom(position);
  8801. return;
  8802. }
  8803. collider.retry++;
  8804. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8805. };
  8806. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8807. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8808. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8809. if (!this._selectionOctree) {
  8810. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8811. }
  8812. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8813. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8814. for (var index = 0; index < this.meshes.length; index++) {
  8815. var mesh = this.meshes[index];
  8816. mesh.computeWorldMatrix(true);
  8817. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8818. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8819. BABYLON.Tools.CheckExtends(minBox, min, max);
  8820. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8821. }
  8822. this._selectionOctree.update(min, max, this.meshes);
  8823. return this._selectionOctree;
  8824. };
  8825. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8826. var engine = this._engine;
  8827. if (!camera) {
  8828. if (!this.activeCamera)
  8829. throw new Error("Active camera not set");
  8830. camera = this.activeCamera;
  8831. }
  8832. var cameraViewport = camera.viewport;
  8833. var viewport = cameraViewport.toGlobal(engine);
  8834. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8835. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8836. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8837. };
  8838. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8839. var pickingInfo = null;
  8840. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8841. var mesh = this.meshes[meshIndex];
  8842. if (predicate) {
  8843. if (!predicate(mesh)) {
  8844. continue;
  8845. }
  8846. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8847. continue;
  8848. }
  8849. var world = mesh.getWorldMatrix();
  8850. var ray = rayFunction(world);
  8851. var result = mesh.intersects(ray, fastCheck);
  8852. if (!result || !result.hit)
  8853. continue;
  8854. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8855. continue;
  8856. pickingInfo = result;
  8857. if (fastCheck) {
  8858. break;
  8859. }
  8860. }
  8861. return pickingInfo || new BABYLON.PickingInfo();
  8862. };
  8863. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8864. var _this = this;
  8865. return this._internalPick(function (world) {
  8866. return _this.createPickingRay(x, y, world, camera);
  8867. }, predicate, fastCheck);
  8868. };
  8869. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8870. var _this = this;
  8871. return this._internalPick(function (world) {
  8872. if (!_this._pickWithRayInverseMatrix) {
  8873. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8874. }
  8875. world.invertToRef(_this._pickWithRayInverseMatrix);
  8876. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8877. }, predicate, fastCheck);
  8878. };
  8879. Scene.prototype.setPointerOverMesh = function (mesh) {
  8880. if (this._pointerOverMesh === mesh) {
  8881. return;
  8882. }
  8883. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8884. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8885. }
  8886. this._pointerOverMesh = mesh;
  8887. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8888. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8889. }
  8890. };
  8891. Scene.prototype.getPointerOverMesh = function () {
  8892. return this._pointerOverMesh;
  8893. };
  8894. Scene.prototype.getPhysicsEngine = function () {
  8895. return this._physicsEngine;
  8896. };
  8897. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8898. if (this._physicsEngine) {
  8899. return true;
  8900. }
  8901. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8902. if (!this._physicsEngine.isSupported()) {
  8903. this._physicsEngine = null;
  8904. return false;
  8905. }
  8906. this._physicsEngine._initialize(gravity);
  8907. return true;
  8908. };
  8909. Scene.prototype.disablePhysicsEngine = function () {
  8910. if (!this._physicsEngine) {
  8911. return;
  8912. }
  8913. this._physicsEngine.dispose();
  8914. this._physicsEngine = undefined;
  8915. };
  8916. Scene.prototype.isPhysicsEnabled = function () {
  8917. return this._physicsEngine !== undefined;
  8918. };
  8919. Scene.prototype.setGravity = function (gravity) {
  8920. if (!this._physicsEngine) {
  8921. return;
  8922. }
  8923. this._physicsEngine._setGravity(gravity);
  8924. };
  8925. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8926. if (parts.parts) {
  8927. options = parts;
  8928. parts = parts.parts;
  8929. }
  8930. if (!this._physicsEngine) {
  8931. return null;
  8932. }
  8933. for (var index = 0; index < parts.length; index++) {
  8934. var mesh = parts[index].mesh;
  8935. mesh._physicImpostor = parts[index].impostor;
  8936. mesh._physicsMass = options.mass / parts.length;
  8937. mesh._physicsFriction = options.friction;
  8938. mesh._physicRestitution = options.restitution;
  8939. }
  8940. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8941. };
  8942. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8943. for (var index = 0; index < compound.parts.length; index++) {
  8944. var mesh = compound.parts[index].mesh;
  8945. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8946. this._physicsEngine._unregisterMesh(mesh);
  8947. }
  8948. };
  8949. Scene.prototype._getByTags = function (list, tagsQuery) {
  8950. if (tagsQuery === undefined) {
  8951. return list;
  8952. }
  8953. var listByTags = [];
  8954. for (var i in list) {
  8955. var item = list[i];
  8956. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8957. listByTags.push(item);
  8958. }
  8959. }
  8960. return listByTags;
  8961. };
  8962. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  8963. return this._getByTags(this.meshes, tagsQuery);
  8964. };
  8965. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  8966. return this._getByTags(this.cameras, tagsQuery);
  8967. };
  8968. Scene.prototype.getLightsByTags = function (tagsQuery) {
  8969. return this._getByTags(this.lights, tagsQuery);
  8970. };
  8971. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  8972. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  8973. };
  8974. Scene.FOGMODE_NONE = 0;
  8975. Scene.FOGMODE_EXP = 1;
  8976. Scene.FOGMODE_EXP2 = 2;
  8977. Scene.FOGMODE_LINEAR = 3;
  8978. Scene.MinDeltaTime = 1.0;
  8979. Scene.MaxDeltaTime = 1000.0;
  8980. return Scene;
  8981. })();
  8982. BABYLON.Scene = Scene;
  8983. })(BABYLON || (BABYLON = {}));
  8984. var BABYLON;
  8985. (function (BABYLON) {
  8986. var VertexBuffer = (function () {
  8987. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation) {
  8988. if (engine instanceof BABYLON.Mesh) {
  8989. this._engine = engine.getScene().getEngine();
  8990. } else {
  8991. this._engine = engine;
  8992. }
  8993. this._updatable = updatable;
  8994. this._data = data;
  8995. if (!postponeInternalCreation) {
  8996. this.create();
  8997. }
  8998. this._kind = kind;
  8999. switch (kind) {
  9000. case VertexBuffer.PositionKind:
  9001. this._strideSize = 3;
  9002. break;
  9003. case VertexBuffer.NormalKind:
  9004. this._strideSize = 3;
  9005. break;
  9006. case VertexBuffer.UVKind:
  9007. this._strideSize = 2;
  9008. break;
  9009. case VertexBuffer.UV2Kind:
  9010. this._strideSize = 2;
  9011. break;
  9012. case VertexBuffer.ColorKind:
  9013. this._strideSize = 3;
  9014. break;
  9015. case VertexBuffer.MatricesIndicesKind:
  9016. this._strideSize = 4;
  9017. break;
  9018. case VertexBuffer.MatricesWeightsKind:
  9019. this._strideSize = 4;
  9020. break;
  9021. }
  9022. }
  9023. VertexBuffer.prototype.isUpdatable = function () {
  9024. return this._updatable;
  9025. };
  9026. VertexBuffer.prototype.getData = function () {
  9027. return this._data;
  9028. };
  9029. VertexBuffer.prototype.getBuffer = function () {
  9030. return this._buffer;
  9031. };
  9032. VertexBuffer.prototype.getStrideSize = function () {
  9033. return this._strideSize;
  9034. };
  9035. VertexBuffer.prototype.create = function (data) {
  9036. if (!data && this._buffer) {
  9037. return;
  9038. }
  9039. data = data || this._data;
  9040. if (!this._buffer) {
  9041. if (this._updatable) {
  9042. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9043. } else {
  9044. this._buffer = this._engine.createVertexBuffer(data);
  9045. }
  9046. }
  9047. if (this._updatable) {
  9048. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9049. this._data = data;
  9050. }
  9051. };
  9052. VertexBuffer.prototype.update = function (data) {
  9053. this.create(data);
  9054. };
  9055. VertexBuffer.prototype.updateDirectly = function (data) {
  9056. if (!this._buffer) {
  9057. return;
  9058. }
  9059. if (this._updatable) {
  9060. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9061. this._data = null;
  9062. }
  9063. };
  9064. VertexBuffer.prototype.dispose = function () {
  9065. if (!this._buffer) {
  9066. return;
  9067. }
  9068. if (this._engine._releaseBuffer(this._buffer)) {
  9069. this._buffer = null;
  9070. }
  9071. };
  9072. Object.defineProperty(VertexBuffer, "PositionKind", {
  9073. get: function () {
  9074. return VertexBuffer._PositionKind;
  9075. },
  9076. enumerable: true,
  9077. configurable: true
  9078. });
  9079. Object.defineProperty(VertexBuffer, "NormalKind", {
  9080. get: function () {
  9081. return VertexBuffer._NormalKind;
  9082. },
  9083. enumerable: true,
  9084. configurable: true
  9085. });
  9086. Object.defineProperty(VertexBuffer, "UVKind", {
  9087. get: function () {
  9088. return VertexBuffer._UVKind;
  9089. },
  9090. enumerable: true,
  9091. configurable: true
  9092. });
  9093. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9094. get: function () {
  9095. return VertexBuffer._UV2Kind;
  9096. },
  9097. enumerable: true,
  9098. configurable: true
  9099. });
  9100. Object.defineProperty(VertexBuffer, "ColorKind", {
  9101. get: function () {
  9102. return VertexBuffer._ColorKind;
  9103. },
  9104. enumerable: true,
  9105. configurable: true
  9106. });
  9107. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9108. get: function () {
  9109. return VertexBuffer._MatricesIndicesKind;
  9110. },
  9111. enumerable: true,
  9112. configurable: true
  9113. });
  9114. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9115. get: function () {
  9116. return VertexBuffer._MatricesWeightsKind;
  9117. },
  9118. enumerable: true,
  9119. configurable: true
  9120. });
  9121. VertexBuffer._PositionKind = "position";
  9122. VertexBuffer._NormalKind = "normal";
  9123. VertexBuffer._UVKind = "uv";
  9124. VertexBuffer._UV2Kind = "uv2";
  9125. VertexBuffer._ColorKind = "color";
  9126. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9127. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9128. return VertexBuffer;
  9129. })();
  9130. BABYLON.VertexBuffer = VertexBuffer;
  9131. })(BABYLON || (BABYLON = {}));
  9132. var __extends = this.__extends || function (d, b) {
  9133. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9134. function __() { this.constructor = d; }
  9135. __.prototype = b.prototype;
  9136. d.prototype = new __();
  9137. };
  9138. var BABYLON;
  9139. (function (BABYLON) {
  9140. var InstancedMesh = (function (_super) {
  9141. __extends(InstancedMesh, _super);
  9142. function InstancedMesh(name, source) {
  9143. _super.call(this, name, source.getScene());
  9144. source.instances.push(this);
  9145. this._sourceMesh = source;
  9146. this.position.copyFrom(source.position);
  9147. this.rotation.copyFrom(source.rotation);
  9148. this.scaling.copyFrom(source.scaling);
  9149. if (source.rotationQuaternion) {
  9150. this.rotationQuaternion = source.rotationQuaternion.clone();
  9151. }
  9152. this.infiniteDistance = source.infiniteDistance;
  9153. this.setPivotMatrix(source.getPivotMatrix());
  9154. this.refreshBoundingInfo();
  9155. this._syncSubMeshes();
  9156. }
  9157. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  9158. get: function () {
  9159. return this._sourceMesh.receiveShadows;
  9160. },
  9161. enumerable: true,
  9162. configurable: true
  9163. });
  9164. Object.defineProperty(InstancedMesh.prototype, "material", {
  9165. get: function () {
  9166. return this._sourceMesh.material;
  9167. },
  9168. enumerable: true,
  9169. configurable: true
  9170. });
  9171. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  9172. get: function () {
  9173. return this._sourceMesh.visibility;
  9174. },
  9175. enumerable: true,
  9176. configurable: true
  9177. });
  9178. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  9179. get: function () {
  9180. return this._sourceMesh.skeleton;
  9181. },
  9182. enumerable: true,
  9183. configurable: true
  9184. });
  9185. InstancedMesh.prototype.getTotalVertices = function () {
  9186. return this._sourceMesh.getTotalVertices();
  9187. };
  9188. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  9189. get: function () {
  9190. return this._sourceMesh;
  9191. },
  9192. enumerable: true,
  9193. configurable: true
  9194. });
  9195. InstancedMesh.prototype.getVerticesData = function (kind) {
  9196. return this._sourceMesh.getVerticesData(kind);
  9197. };
  9198. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  9199. return this._sourceMesh.isVerticesDataPresent(kind);
  9200. };
  9201. InstancedMesh.prototype.getIndices = function () {
  9202. return this._sourceMesh.getIndices();
  9203. };
  9204. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  9205. get: function () {
  9206. return this._sourceMesh._positions;
  9207. },
  9208. enumerable: true,
  9209. configurable: true
  9210. });
  9211. InstancedMesh.prototype.refreshBoundingInfo = function () {
  9212. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9213. if (data) {
  9214. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  9215. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9216. }
  9217. this._updateBoundingInfo();
  9218. };
  9219. InstancedMesh.prototype._preActivate = function () {
  9220. this.sourceMesh._preActivate();
  9221. };
  9222. InstancedMesh.prototype._activate = function (renderId) {
  9223. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  9224. };
  9225. InstancedMesh.prototype._syncSubMeshes = function () {
  9226. this.releaseSubMeshes();
  9227. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  9228. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  9229. }
  9230. };
  9231. InstancedMesh.prototype._generatePointsArray = function () {
  9232. return this._sourceMesh._generatePointsArray();
  9233. };
  9234. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9235. var result = this._sourceMesh.createInstance(name);
  9236. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  9237. this.refreshBoundingInfo();
  9238. if (newParent) {
  9239. result.parent = newParent;
  9240. }
  9241. if (!doNotCloneChildren) {
  9242. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9243. var mesh = this.getScene().meshes[index];
  9244. if (mesh.parent == this) {
  9245. mesh.clone(mesh.name, result);
  9246. }
  9247. }
  9248. }
  9249. result.computeWorldMatrix(true);
  9250. return result;
  9251. };
  9252. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  9253. var index = this._sourceMesh.instances.indexOf(this);
  9254. this._sourceMesh.instances.splice(index, 1);
  9255. _super.prototype.dispose.call(this, doNotRecurse);
  9256. };
  9257. return InstancedMesh;
  9258. })(BABYLON.AbstractMesh);
  9259. BABYLON.InstancedMesh = InstancedMesh;
  9260. })(BABYLON || (BABYLON = {}));
  9261. var __extends = this.__extends || function (d, b) {
  9262. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9263. function __() { this.constructor = d; }
  9264. __.prototype = b.prototype;
  9265. d.prototype = new __();
  9266. };
  9267. var BABYLON;
  9268. (function (BABYLON) {
  9269. var _InstancesBatch = (function () {
  9270. function _InstancesBatch() {
  9271. this.mustReturn = false;
  9272. this.visibleInstances = new Array();
  9273. this.renderSelf = new Array();
  9274. }
  9275. return _InstancesBatch;
  9276. })();
  9277. BABYLON._InstancesBatch = _InstancesBatch;
  9278. var Mesh = (function (_super) {
  9279. __extends(Mesh, _super);
  9280. function Mesh(name, scene) {
  9281. _super.call(this, name, scene);
  9282. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9283. this.instances = new Array();
  9284. this._onBeforeRenderCallbacks = new Array();
  9285. this._onAfterRenderCallbacks = new Array();
  9286. this._visibleInstances = {};
  9287. this._renderIdForInstances = new Array();
  9288. this._batchCache = new _InstancesBatch();
  9289. this._instancesBufferSize = 32 * 16 * 4;
  9290. }
  9291. Mesh.prototype.getTotalVertices = function () {
  9292. if (!this._geometry) {
  9293. return 0;
  9294. }
  9295. return this._geometry.getTotalVertices();
  9296. };
  9297. Mesh.prototype.getVerticesData = function (kind) {
  9298. if (!this._geometry) {
  9299. return null;
  9300. }
  9301. return this._geometry.getVerticesData(kind);
  9302. };
  9303. Mesh.prototype.getVertexBuffer = function (kind) {
  9304. if (!this._geometry) {
  9305. return undefined;
  9306. }
  9307. return this._geometry.getVertexBuffer(kind);
  9308. };
  9309. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9310. if (!this._geometry) {
  9311. if (this._delayInfo) {
  9312. return this._delayInfo.indexOf(kind) !== -1;
  9313. }
  9314. return false;
  9315. }
  9316. return this._geometry.isVerticesDataPresent(kind);
  9317. };
  9318. Mesh.prototype.getVerticesDataKinds = function () {
  9319. if (!this._geometry) {
  9320. var result = [];
  9321. if (this._delayInfo) {
  9322. for (var kind in this._delayInfo) {
  9323. result.push(kind);
  9324. }
  9325. }
  9326. return result;
  9327. }
  9328. return this._geometry.getVerticesDataKinds();
  9329. };
  9330. Mesh.prototype.getTotalIndices = function () {
  9331. if (!this._geometry) {
  9332. return 0;
  9333. }
  9334. return this._geometry.getTotalIndices();
  9335. };
  9336. Mesh.prototype.getIndices = function () {
  9337. if (!this._geometry) {
  9338. return [];
  9339. }
  9340. return this._geometry.getIndices();
  9341. };
  9342. Mesh.prototype.isReady = function () {
  9343. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9344. return false;
  9345. }
  9346. return _super.prototype.isReady.call(this);
  9347. };
  9348. Mesh.prototype.isDisposed = function () {
  9349. return this._isDisposed;
  9350. };
  9351. Mesh.prototype._preActivate = function () {
  9352. var sceneRenderId = this.getScene().getRenderId();
  9353. if (this._preActivateId == sceneRenderId) {
  9354. return;
  9355. }
  9356. this._preActivateId = sceneRenderId;
  9357. this._visibleInstances = null;
  9358. };
  9359. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  9360. if (!this._visibleInstances) {
  9361. this._visibleInstances = {};
  9362. this._visibleInstances.defaultRenderId = renderId;
  9363. this._visibleInstances.selfDefaultRenderId = this._renderId;
  9364. }
  9365. if (!this._visibleInstances[renderId]) {
  9366. this._visibleInstances[renderId] = new Array();
  9367. }
  9368. this._visibleInstances[renderId].push(instance);
  9369. };
  9370. Mesh.prototype.refreshBoundingInfo = function () {
  9371. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9372. if (data) {
  9373. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  9374. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9375. }
  9376. if (this.subMeshes) {
  9377. for (var index = 0; index < this.subMeshes.length; index++) {
  9378. this.subMeshes[index].refreshBoundingInfo();
  9379. }
  9380. }
  9381. this._updateBoundingInfo();
  9382. };
  9383. Mesh.prototype._createGlobalSubMesh = function () {
  9384. var totalVertices = this.getTotalVertices();
  9385. if (!totalVertices || !this.getIndices()) {
  9386. return null;
  9387. }
  9388. this.releaseSubMeshes();
  9389. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  9390. };
  9391. Mesh.prototype.subdivide = function (count) {
  9392. if (count < 1) {
  9393. return;
  9394. }
  9395. var totalIndices = this.getTotalIndices();
  9396. var subdivisionSize = (totalIndices / count) | 0;
  9397. var offset = 0;
  9398. while (subdivisionSize % 3 != 0) {
  9399. subdivisionSize++;
  9400. }
  9401. this.releaseSubMeshes();
  9402. for (var index = 0; index < count; index++) {
  9403. if (offset >= totalIndices) {
  9404. break;
  9405. }
  9406. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  9407. offset += subdivisionSize;
  9408. }
  9409. this.synchronizeInstances();
  9410. };
  9411. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  9412. if (kind instanceof Array) {
  9413. var temp = data;
  9414. data = kind;
  9415. kind = temp;
  9416. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  9417. }
  9418. if (!this._geometry) {
  9419. var vertexData = new BABYLON.VertexData();
  9420. vertexData.set(data, kind);
  9421. var scene = this.getScene();
  9422. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  9423. } else {
  9424. this._geometry.setVerticesData(kind, data, updatable);
  9425. }
  9426. };
  9427. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  9428. if (!this._geometry) {
  9429. return;
  9430. }
  9431. if (!makeItUnique) {
  9432. this._geometry.updateVerticesData(kind, data, updateExtends);
  9433. } else {
  9434. this.makeGeometryUnique();
  9435. this.updateVerticesData(kind, data, updateExtends, false);
  9436. }
  9437. };
  9438. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, makeItUnique) {
  9439. if (!this._geometry) {
  9440. return;
  9441. }
  9442. if (!makeItUnique) {
  9443. this._geometry.updateVerticesDataDirectly(kind, data);
  9444. } else {
  9445. this.makeGeometryUnique();
  9446. this.updateVerticesDataDirectly(kind, data, false);
  9447. }
  9448. };
  9449. Mesh.prototype.makeGeometryUnique = function () {
  9450. if (!this._geometry) {
  9451. return;
  9452. }
  9453. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  9454. geometry.applyToMesh(this);
  9455. };
  9456. Mesh.prototype.setIndices = function (indices) {
  9457. if (!this._geometry) {
  9458. var vertexData = new BABYLON.VertexData();
  9459. vertexData.indices = indices;
  9460. var scene = this.getScene();
  9461. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  9462. } else {
  9463. this._geometry.setIndices(indices);
  9464. }
  9465. };
  9466. Mesh.prototype._bind = function (subMesh, effect, drawAs) {
  9467. var engine = this.getScene().getEngine();
  9468. var indexToBind = undefined;
  9469. switch (drawAs) {
  9470. case WebGLRenderingContext.LINES:
  9471. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  9472. break;
  9473. case WebGLRenderingContext.POINTS:
  9474. indexToBind = null;
  9475. break;
  9476. case WebGLRenderingContext.TRIANGLES:
  9477. default:
  9478. indexToBind = this._geometry.getIndexBuffer();
  9479. break;
  9480. }
  9481. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  9482. };
  9483. Mesh.prototype._getStartIndexOfMesh = function (subMesh, drawAs) {
  9484. var start = 0;
  9485. switch (drawAs) {
  9486. case WebGLRenderingContext.LINES:
  9487. start = 0;
  9488. break;
  9489. case WebGLRenderingContext.POINTS:
  9490. start = 0;
  9491. break;
  9492. case WebGLRenderingContext.TRIANGLES:
  9493. default:
  9494. start = subMesh.indexStart;
  9495. break;
  9496. }
  9497. return start;
  9498. };
  9499. Mesh.prototype._getCountOfMesh = function (subMesh, drawAs) {
  9500. var count = 0;
  9501. switch (drawAs) {
  9502. case WebGLRenderingContext.LINES:
  9503. count = subMesh.linesIndexCount;
  9504. break;
  9505. case WebGLRenderingContext.POINTS:
  9506. count = subMesh.verticesCount;
  9507. break;
  9508. case WebGLRenderingContext.TRIANGLES:
  9509. default:
  9510. count = subMesh.indexCount;
  9511. break;
  9512. }
  9513. return count;
  9514. };
  9515. Mesh.prototype._draw = function (subMesh, drawAs, instancesCount) {
  9516. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9517. return;
  9518. }
  9519. var engine = this.getScene().getEngine();
  9520. var start = this._getStartIndexOfMesh(subMesh, drawAs);
  9521. var count = this._getCountOfMesh(subMesh, drawAs);
  9522. engine.draw(drawAs, start, count, instancesCount);
  9523. };
  9524. Mesh.prototype._fullDraw = function (subMesh, drawAs, instancesCount) {
  9525. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9526. return;
  9527. }
  9528. var engine = this.getScene().getEngine();
  9529. var start = this._getStartIndexOfMesh(subMesh, drawAs);
  9530. var count = this._getCountOfMesh(subMesh, drawAs);
  9531. engine.draw(drawAs, start, count, instancesCount);
  9532. };
  9533. Mesh.prototype.registerBeforeRender = function (func) {
  9534. this._onBeforeRenderCallbacks.push(func);
  9535. };
  9536. Mesh.prototype.unregisterBeforeRender = function (func) {
  9537. var index = this._onBeforeRenderCallbacks.indexOf(func);
  9538. if (index > -1) {
  9539. this._onBeforeRenderCallbacks.splice(index, 1);
  9540. }
  9541. };
  9542. Mesh.prototype.registerAfterRender = function (func) {
  9543. this._onAfterRenderCallbacks.push(func);
  9544. };
  9545. Mesh.prototype.unregisterAfterRender = function (func) {
  9546. var index = this._onAfterRenderCallbacks.indexOf(func);
  9547. if (index > -1) {
  9548. this._onAfterRenderCallbacks.splice(index, 1);
  9549. }
  9550. };
  9551. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  9552. var scene = this.getScene();
  9553. this._batchCache.mustReturn = false;
  9554. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  9555. this._batchCache.visibleInstances[subMeshId] = null;
  9556. if (this._visibleInstances) {
  9557. var currentRenderId = scene.getRenderId();
  9558. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  9559. var selfRenderId = this._renderId;
  9560. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  9561. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  9562. currentRenderId = this._visibleInstances.defaultRenderId;
  9563. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  9564. }
  9565. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  9566. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  9567. this._batchCache.mustReturn = true;
  9568. return this._batchCache;
  9569. }
  9570. if (currentRenderId !== selfRenderId) {
  9571. this._batchCache.renderSelf[subMeshId] = false;
  9572. }
  9573. }
  9574. this._renderIdForInstances[subMeshId] = currentRenderId;
  9575. }
  9576. return this._batchCache;
  9577. };
  9578. Mesh.prototype._renderWithInstances = function (subMesh, drawAs, batch, effect, engine) {
  9579. var matricesCount = this.instances.length + 1;
  9580. var bufferSize = matricesCount * 16 * 4;
  9581. while (this._instancesBufferSize < bufferSize) {
  9582. this._instancesBufferSize *= 2;
  9583. }
  9584. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  9585. if (this._worldMatricesInstancesBuffer) {
  9586. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9587. }
  9588. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  9589. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  9590. }
  9591. var offset = 0;
  9592. var instancesCount = 0;
  9593. var world = this.getWorldMatrix();
  9594. if (batch.renderSelf[subMesh._id]) {
  9595. world.copyToArray(this._worldMatricesInstancesArray, offset);
  9596. offset += 16;
  9597. instancesCount++;
  9598. }
  9599. var visibleInstances = batch.visibleInstances[subMesh._id];
  9600. if (visibleInstances) {
  9601. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  9602. var instance = visibleInstances[instanceIndex];
  9603. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  9604. offset += 16;
  9605. instancesCount++;
  9606. }
  9607. }
  9608. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  9609. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  9610. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  9611. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  9612. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  9613. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  9614. this._draw(subMesh, drawAs, instancesCount);
  9615. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  9616. };
  9617. Mesh.prototype.render = function (subMesh) {
  9618. var scene = this.getScene();
  9619. var batch = this._getInstancesRenderList(subMesh._id);
  9620. if (batch.mustReturn) {
  9621. return;
  9622. }
  9623. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9624. return;
  9625. }
  9626. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9627. this._onBeforeRenderCallbacks[callbackIndex]();
  9628. }
  9629. var engine = scene.getEngine();
  9630. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  9631. var effectiveMaterial = subMesh.getMaterial();
  9632. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  9633. return;
  9634. }
  9635. var savedDepthWrite = engine.getDepthWrite();
  9636. if (this.renderOutline) {
  9637. engine.setDepthWrite(false);
  9638. scene.getOutlineRenderer().render(subMesh, batch);
  9639. }
  9640. effectiveMaterial._preBind();
  9641. var effect = effectiveMaterial.getEffect();
  9642. var drawAs = engine.forceWireframe ? WebGLRenderingContext.LINES : effectiveMaterial.drawAs;
  9643. this._bind(subMesh, effect, drawAs);
  9644. var world = this.getWorldMatrix();
  9645. effectiveMaterial.bind(world, this);
  9646. if (hardwareInstancedRendering) {
  9647. this._renderWithInstances(subMesh, drawAs, batch, effect, engine);
  9648. } else {
  9649. if (batch.renderSelf[subMesh._id]) {
  9650. this._draw(subMesh, drawAs);
  9651. }
  9652. if (batch.visibleInstances[subMesh._id]) {
  9653. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  9654. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  9655. world = instance.getWorldMatrix();
  9656. effectiveMaterial.bindOnlyWorldMatrix(world);
  9657. this._draw(subMesh, drawAs);
  9658. }
  9659. }
  9660. }
  9661. effectiveMaterial.unbind();
  9662. if (this.renderOutline && savedDepthWrite) {
  9663. engine.setDepthWrite(true);
  9664. engine.setColorWrite(false);
  9665. scene.getOutlineRenderer().render(subMesh, batch);
  9666. engine.setColorWrite(true);
  9667. }
  9668. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9669. this._onAfterRenderCallbacks[callbackIndex]();
  9670. }
  9671. };
  9672. Mesh.prototype.getEmittedParticleSystems = function () {
  9673. var results = new Array();
  9674. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9675. var particleSystem = this.getScene().particleSystems[index];
  9676. if (particleSystem.emitter === this) {
  9677. results.push(particleSystem);
  9678. }
  9679. }
  9680. return results;
  9681. };
  9682. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  9683. var results = new Array();
  9684. var descendants = this.getDescendants();
  9685. descendants.push(this);
  9686. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9687. var particleSystem = this.getScene().particleSystems[index];
  9688. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  9689. results.push(particleSystem);
  9690. }
  9691. }
  9692. return results;
  9693. };
  9694. Mesh.prototype.getChildren = function () {
  9695. var results = [];
  9696. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9697. var mesh = this.getScene().meshes[index];
  9698. if (mesh.parent == this) {
  9699. results.push(mesh);
  9700. }
  9701. }
  9702. return results;
  9703. };
  9704. Mesh.prototype._checkDelayState = function () {
  9705. var _this = this;
  9706. var that = this;
  9707. var scene = this.getScene();
  9708. if (this._geometry) {
  9709. this._geometry.load(scene);
  9710. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9711. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  9712. scene._addPendingData(that);
  9713. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  9714. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  9715. if (data instanceof ArrayBuffer) {
  9716. _this._delayLoadingFunction(data, _this);
  9717. } else {
  9718. _this._delayLoadingFunction(JSON.parse(data), _this);
  9719. }
  9720. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9721. scene._removePendingData(_this);
  9722. }, function () {
  9723. }, scene.database, getBinaryData);
  9724. }
  9725. };
  9726. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  9727. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9728. return false;
  9729. }
  9730. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  9731. return false;
  9732. }
  9733. this._checkDelayState();
  9734. return true;
  9735. };
  9736. Mesh.prototype.setMaterialByID = function (id) {
  9737. var materials = this.getScene().materials;
  9738. for (var index = 0; index < materials.length; index++) {
  9739. if (materials[index].id == id) {
  9740. this.material = materials[index];
  9741. return;
  9742. }
  9743. }
  9744. var multiMaterials = this.getScene().multiMaterials;
  9745. for (index = 0; index < multiMaterials.length; index++) {
  9746. if (multiMaterials[index].id == id) {
  9747. this.material = multiMaterials[index];
  9748. return;
  9749. }
  9750. }
  9751. };
  9752. Mesh.prototype.getAnimatables = function () {
  9753. var results = [];
  9754. if (this.material) {
  9755. results.push(this.material);
  9756. }
  9757. if (this.skeleton) {
  9758. results.push(this.skeleton);
  9759. }
  9760. return results;
  9761. };
  9762. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  9763. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  9764. return;
  9765. }
  9766. this._resetPointsArrayCache();
  9767. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9768. var temp = [];
  9769. for (var index = 0; index < data.length; index += 3) {
  9770. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9771. }
  9772. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  9773. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9774. return;
  9775. }
  9776. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9777. for (index = 0; index < data.length; index += 3) {
  9778. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9779. }
  9780. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  9781. };
  9782. Mesh.prototype._resetPointsArrayCache = function () {
  9783. this._positions = null;
  9784. };
  9785. Mesh.prototype._generatePointsArray = function () {
  9786. if (this._positions)
  9787. return true;
  9788. this._positions = [];
  9789. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9790. if (!data) {
  9791. return false;
  9792. }
  9793. for (var index = 0; index < data.length; index += 3) {
  9794. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  9795. }
  9796. return true;
  9797. };
  9798. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9799. var result = new BABYLON.Mesh(name, this.getScene());
  9800. this._geometry.applyToMesh(result);
  9801. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  9802. result.material = this.material;
  9803. if (newParent) {
  9804. result.parent = newParent;
  9805. }
  9806. if (!doNotCloneChildren) {
  9807. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9808. var mesh = this.getScene().meshes[index];
  9809. if (mesh.parent == this) {
  9810. mesh.clone(mesh.name, result);
  9811. }
  9812. }
  9813. }
  9814. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9815. var system = this.getScene().particleSystems[index];
  9816. if (system.emitter == this) {
  9817. system.clone(system.name, result);
  9818. }
  9819. }
  9820. result.computeWorldMatrix(true);
  9821. return result;
  9822. };
  9823. Mesh.prototype.dispose = function (doNotRecurse) {
  9824. if (this._geometry) {
  9825. this._geometry.releaseForMesh(this, true);
  9826. }
  9827. if (this._worldMatricesInstancesBuffer) {
  9828. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9829. this._worldMatricesInstancesBuffer = null;
  9830. }
  9831. while (this.instances.length) {
  9832. this.instances[0].dispose();
  9833. }
  9834. _super.prototype.dispose.call(this, doNotRecurse);
  9835. };
  9836. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  9837. var _this = this;
  9838. var scene = this.getScene();
  9839. var onload = function (img) {
  9840. var canvas = document.createElement("canvas");
  9841. var context = canvas.getContext("2d");
  9842. var heightMapWidth = img.width;
  9843. var heightMapHeight = img.height;
  9844. canvas.width = heightMapWidth;
  9845. canvas.height = heightMapHeight;
  9846. context.drawImage(img, 0, 0);
  9847. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9848. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  9849. };
  9850. BABYLON.Tools.LoadImage(url, onload, function () {
  9851. }, scene.database);
  9852. };
  9853. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  9854. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9855. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  9856. return;
  9857. }
  9858. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9859. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9860. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9861. var position = BABYLON.Vector3.Zero();
  9862. var normal = BABYLON.Vector3.Zero();
  9863. var uv = BABYLON.Vector2.Zero();
  9864. for (var index = 0; index < positions.length; index += 3) {
  9865. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  9866. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  9867. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  9868. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  9869. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  9870. var pos = (u + v * heightMapWidth) * 4;
  9871. var r = buffer[pos] / 255.0;
  9872. var g = buffer[pos + 1] / 255.0;
  9873. var b = buffer[pos + 2] / 255.0;
  9874. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  9875. normal.normalize();
  9876. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  9877. position = position.add(normal);
  9878. position.toArray(positions, index);
  9879. }
  9880. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  9881. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  9882. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  9883. };
  9884. Mesh.prototype.convertToFlatShadedMesh = function () {
  9885. var kinds = this.getVerticesDataKinds();
  9886. var vbs = [];
  9887. var data = [];
  9888. var newdata = [];
  9889. var updatableNormals = false;
  9890. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9891. var kind = kinds[kindIndex];
  9892. var vertexBuffer = this.getVertexBuffer(kind);
  9893. if (kind === BABYLON.VertexBuffer.NormalKind) {
  9894. updatableNormals = vertexBuffer.isUpdatable();
  9895. kinds.splice(kindIndex, 1);
  9896. kindIndex--;
  9897. continue;
  9898. }
  9899. vbs[kind] = vertexBuffer;
  9900. data[kind] = vbs[kind].getData();
  9901. newdata[kind] = [];
  9902. }
  9903. var previousSubmeshes = this.subMeshes.slice(0);
  9904. var indices = this.getIndices();
  9905. var totalIndices = this.getTotalIndices();
  9906. for (index = 0; index < totalIndices; index++) {
  9907. var vertexIndex = indices[index];
  9908. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9909. kind = kinds[kindIndex];
  9910. var stride = vbs[kind].getStrideSize();
  9911. for (var offset = 0; offset < stride; offset++) {
  9912. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  9913. }
  9914. }
  9915. }
  9916. var normals = [];
  9917. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  9918. for (var index = 0; index < totalIndices; index += 3) {
  9919. indices[index] = index;
  9920. indices[index + 1] = index + 1;
  9921. indices[index + 2] = index + 2;
  9922. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  9923. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  9924. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  9925. var p1p2 = p1.subtract(p2);
  9926. var p3p2 = p3.subtract(p2);
  9927. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  9928. for (var localIndex = 0; localIndex < 3; localIndex++) {
  9929. normals.push(normal.x);
  9930. normals.push(normal.y);
  9931. normals.push(normal.z);
  9932. }
  9933. }
  9934. this.setIndices(indices);
  9935. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  9936. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9937. kind = kinds[kindIndex];
  9938. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  9939. }
  9940. this.releaseSubMeshes();
  9941. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  9942. var previousOne = previousSubmeshes[submeshIndex];
  9943. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  9944. }
  9945. this.synchronizeInstances();
  9946. };
  9947. Mesh.prototype.createInstance = function (name) {
  9948. return new BABYLON.InstancedMesh(name, this);
  9949. };
  9950. Mesh.prototype.synchronizeInstances = function () {
  9951. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  9952. var instance = this.instances[instanceIndex];
  9953. instance._syncSubMeshes();
  9954. }
  9955. };
  9956. Mesh.CreateBox = function (name, size, scene, updatable) {
  9957. var box = new BABYLON.Mesh(name, scene);
  9958. var vertexData = BABYLON.VertexData.CreateBox(size);
  9959. vertexData.applyToMesh(box, updatable);
  9960. return box;
  9961. };
  9962. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  9963. var sphere = new BABYLON.Mesh(name, scene);
  9964. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  9965. vertexData.applyToMesh(sphere, updatable);
  9966. return sphere;
  9967. };
  9968. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  9969. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  9970. if (scene !== undefined) {
  9971. updatable = scene;
  9972. }
  9973. scene = subdivisions;
  9974. subdivisions = 1;
  9975. }
  9976. var cylinder = new BABYLON.Mesh(name, scene);
  9977. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  9978. vertexData.applyToMesh(cylinder, updatable);
  9979. return cylinder;
  9980. };
  9981. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  9982. var torus = new BABYLON.Mesh(name, scene);
  9983. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  9984. vertexData.applyToMesh(torus, updatable);
  9985. return torus;
  9986. };
  9987. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  9988. var torusKnot = new BABYLON.Mesh(name, scene);
  9989. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  9990. vertexData.applyToMesh(torusKnot, updatable);
  9991. return torusKnot;
  9992. };
  9993. Mesh.CreateLines = function (name, points, scene, updatable) {
  9994. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  9995. var vertexData = BABYLON.VertexData.CreateLines(points);
  9996. vertexData.applyToMesh(lines, updatable);
  9997. return lines;
  9998. };
  9999. Mesh.CreatePlane = function (name, size, scene, updatable) {
  10000. var plane = new BABYLON.Mesh(name, scene);
  10001. var vertexData = BABYLON.VertexData.CreatePlane(size);
  10002. vertexData.applyToMesh(plane, updatable);
  10003. return plane;
  10004. };
  10005. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10006. var ground = new BABYLON.GroundMesh(name, scene);
  10007. ground._setReady(false);
  10008. ground._subdivisions = subdivisions;
  10009. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10010. vertexData.applyToMesh(ground, updatable);
  10011. ground._setReady(true);
  10012. return ground;
  10013. };
  10014. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10015. var tiledGround = new BABYLON.Mesh(name, scene);
  10016. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10017. vertexData.applyToMesh(tiledGround, updatable);
  10018. return tiledGround;
  10019. };
  10020. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  10021. var ground = new BABYLON.GroundMesh(name, scene);
  10022. ground._subdivisions = subdivisions;
  10023. ground._setReady(false);
  10024. var onload = function (img) {
  10025. var canvas = document.createElement("canvas");
  10026. var context = canvas.getContext("2d");
  10027. var heightMapWidth = img.width;
  10028. var heightMapHeight = img.height;
  10029. canvas.width = heightMapWidth;
  10030. canvas.height = heightMapHeight;
  10031. context.drawImage(img, 0, 0);
  10032. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10033. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10034. vertexData.applyToMesh(ground, updatable);
  10035. ground._setReady(true);
  10036. };
  10037. BABYLON.Tools.LoadImage(url, onload, function () {
  10038. }, scene.database);
  10039. return ground;
  10040. };
  10041. Mesh.MinMax = function (meshes) {
  10042. var minVector = null;
  10043. var maxVector = null;
  10044. for (var i in meshes) {
  10045. var mesh = meshes[i];
  10046. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10047. if (!minVector) {
  10048. minVector = boundingBox.minimumWorld;
  10049. maxVector = boundingBox.maximumWorld;
  10050. continue;
  10051. }
  10052. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10053. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10054. }
  10055. return {
  10056. min: minVector,
  10057. max: maxVector
  10058. };
  10059. };
  10060. Mesh.Center = function (meshesOrMinMaxVector) {
  10061. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  10062. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10063. };
  10064. return Mesh;
  10065. })(BABYLON.AbstractMesh);
  10066. BABYLON.Mesh = Mesh;
  10067. })(BABYLON || (BABYLON = {}));
  10068. var BABYLON;
  10069. (function (BABYLON) {
  10070. var SubMesh = (function () {
  10071. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  10072. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  10073. this.materialIndex = materialIndex;
  10074. this.verticesStart = verticesStart;
  10075. this.verticesCount = verticesCount;
  10076. this.indexStart = indexStart;
  10077. this.indexCount = indexCount;
  10078. this._renderId = 0;
  10079. this._mesh = mesh;
  10080. this._renderingMesh = renderingMesh || mesh;
  10081. mesh.subMeshes.push(this);
  10082. this._id = mesh.subMeshes.length - 1;
  10083. if (createBoundingBox) {
  10084. this.refreshBoundingInfo();
  10085. }
  10086. }
  10087. SubMesh.prototype.getBoundingInfo = function () {
  10088. return this._boundingInfo;
  10089. };
  10090. SubMesh.prototype.getMesh = function () {
  10091. return this._mesh;
  10092. };
  10093. SubMesh.prototype.getRenderingMesh = function () {
  10094. return this._renderingMesh;
  10095. };
  10096. SubMesh.prototype.getMaterial = function () {
  10097. var rootMaterial = this._renderingMesh.material;
  10098. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  10099. var multiMaterial = rootMaterial;
  10100. return multiMaterial.getSubMaterial(this.materialIndex);
  10101. }
  10102. if (!rootMaterial) {
  10103. return this._mesh.getScene().defaultMaterial;
  10104. }
  10105. return rootMaterial;
  10106. };
  10107. SubMesh.prototype.refreshBoundingInfo = function () {
  10108. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10109. if (!data) {
  10110. this._boundingInfo = this._mesh._boundingInfo;
  10111. return;
  10112. }
  10113. var indices = this._renderingMesh.getIndices();
  10114. var extend;
  10115. if (this.indexStart === 0 && this.indexCount === indices.length) {
  10116. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  10117. } else {
  10118. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  10119. }
  10120. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10121. };
  10122. SubMesh.prototype._checkCollision = function (collider) {
  10123. return this._boundingInfo._checkCollision(collider);
  10124. };
  10125. SubMesh.prototype.updateBoundingInfo = function (world) {
  10126. if (!this._boundingInfo) {
  10127. this.refreshBoundingInfo();
  10128. }
  10129. this._boundingInfo._update(world);
  10130. };
  10131. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  10132. return this._boundingInfo.isInFrustum(frustumPlanes);
  10133. };
  10134. SubMesh.prototype.render = function () {
  10135. this._renderingMesh.render(this);
  10136. };
  10137. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  10138. if (!this._linesIndexBuffer) {
  10139. var linesIndices = [];
  10140. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10141. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  10142. }
  10143. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  10144. this.linesIndexCount = linesIndices.length;
  10145. }
  10146. return this._linesIndexBuffer;
  10147. };
  10148. SubMesh.prototype.canIntersects = function (ray) {
  10149. return ray.intersectsBox(this._boundingInfo.boundingBox);
  10150. };
  10151. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  10152. var intersectInfo = null;
  10153. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10154. var p0 = positions[indices[index]];
  10155. var p1 = positions[indices[index + 1]];
  10156. var p2 = positions[indices[index + 2]];
  10157. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  10158. if (currentIntersectInfo) {
  10159. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10160. intersectInfo = currentIntersectInfo;
  10161. intersectInfo.faceId = index / 3;
  10162. if (fastCheck) {
  10163. break;
  10164. }
  10165. }
  10166. }
  10167. }
  10168. return intersectInfo;
  10169. };
  10170. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  10171. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  10172. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  10173. return result;
  10174. };
  10175. SubMesh.prototype.dispose = function () {
  10176. if (this._linesIndexBuffer) {
  10177. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  10178. this._linesIndexBuffer = null;
  10179. }
  10180. var index = this._mesh.subMeshes.indexOf(this);
  10181. this._mesh.subMeshes.splice(index, 1);
  10182. };
  10183. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  10184. var minVertexIndex = Number.MAX_VALUE;
  10185. var maxVertexIndex = -Number.MAX_VALUE;
  10186. renderingMesh = renderingMesh || mesh;
  10187. var indices = renderingMesh.getIndices();
  10188. for (var index = startIndex; index < startIndex + indexCount; index++) {
  10189. var vertexIndex = indices[index];
  10190. if (vertexIndex < minVertexIndex)
  10191. minVertexIndex = vertexIndex;
  10192. if (vertexIndex > maxVertexIndex)
  10193. maxVertexIndex = vertexIndex;
  10194. }
  10195. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  10196. };
  10197. return SubMesh;
  10198. })();
  10199. BABYLON.SubMesh = SubMesh;
  10200. })(BABYLON || (BABYLON = {}));
  10201. var BABYLON;
  10202. (function (BABYLON) {
  10203. var BaseTexture = (function () {
  10204. function BaseTexture(scene) {
  10205. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10206. this.hasAlpha = false;
  10207. this.getAlphaFromRGB = false;
  10208. this.level = 1;
  10209. this.isCube = false;
  10210. this.isRenderTarget = false;
  10211. this.animations = new Array();
  10212. this.coordinatesIndex = 0;
  10213. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  10214. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10215. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10216. this.anisotropicFilteringLevel = 4;
  10217. this._scene = scene;
  10218. this._scene.textures.push(this);
  10219. }
  10220. BaseTexture.prototype.getScene = function () {
  10221. return this._scene;
  10222. };
  10223. BaseTexture.prototype.getTextureMatrix = function () {
  10224. return null;
  10225. };
  10226. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  10227. return null;
  10228. };
  10229. BaseTexture.prototype.getInternalTexture = function () {
  10230. return this._texture;
  10231. };
  10232. BaseTexture.prototype.isReady = function () {
  10233. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10234. return true;
  10235. }
  10236. if (this._texture) {
  10237. return this._texture.isReady;
  10238. }
  10239. return false;
  10240. };
  10241. BaseTexture.prototype.getSize = function () {
  10242. if (this._texture._width) {
  10243. return { width: this._texture._width, height: this._texture._height };
  10244. }
  10245. if (this._texture._size) {
  10246. return { width: this._texture._size, height: this._texture._size };
  10247. }
  10248. return { width: 0, height: 0 };
  10249. };
  10250. BaseTexture.prototype.getBaseSize = function () {
  10251. if (!this.isReady())
  10252. return { width: 0, height: 0 };
  10253. if (this._texture._size) {
  10254. return { width: this._texture._size, height: this._texture._size };
  10255. }
  10256. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  10257. };
  10258. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  10259. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10260. for (var index = 0; index < texturesCache.length; index++) {
  10261. var texturesCacheEntry = texturesCache[index];
  10262. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10263. texturesCacheEntry.references++;
  10264. return texturesCacheEntry;
  10265. }
  10266. }
  10267. return null;
  10268. };
  10269. BaseTexture.prototype.delayLoad = function () {
  10270. };
  10271. BaseTexture.prototype.releaseInternalTexture = function () {
  10272. if (!this._texture) {
  10273. return;
  10274. }
  10275. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10276. this._texture.references--;
  10277. if (this._texture.references == 0) {
  10278. var index = texturesCache.indexOf(this._texture);
  10279. texturesCache.splice(index, 1);
  10280. this._scene.getEngine()._releaseTexture(this._texture);
  10281. delete this._texture;
  10282. }
  10283. };
  10284. BaseTexture.prototype.clone = function () {
  10285. return null;
  10286. };
  10287. BaseTexture.prototype.dispose = function () {
  10288. var index = this._scene.textures.indexOf(this);
  10289. if (index >= 0) {
  10290. this._scene.textures.splice(index, 1);
  10291. }
  10292. if (this._texture === undefined) {
  10293. return;
  10294. }
  10295. this.releaseInternalTexture();
  10296. if (this.onDispose) {
  10297. this.onDispose();
  10298. }
  10299. };
  10300. return BaseTexture;
  10301. })();
  10302. BABYLON.BaseTexture = BaseTexture;
  10303. })(BABYLON || (BABYLON = {}));
  10304. var __extends = this.__extends || function (d, b) {
  10305. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10306. function __() { this.constructor = d; }
  10307. __.prototype = b.prototype;
  10308. d.prototype = new __();
  10309. };
  10310. var BABYLON;
  10311. (function (BABYLON) {
  10312. var Texture = (function (_super) {
  10313. __extends(Texture, _super);
  10314. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  10315. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10316. if (typeof onLoad === "undefined") { onLoad = null; }
  10317. if (typeof onError === "undefined") { onError = null; }
  10318. if (typeof buffer === "undefined") { buffer = null; }
  10319. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  10320. _super.call(this, scene);
  10321. this.uOffset = 0;
  10322. this.vOffset = 0;
  10323. this.uScale = 1.0;
  10324. this.vScale = 1.0;
  10325. this.uAng = 0;
  10326. this.vAng = 0;
  10327. this.wAng = 0;
  10328. this.name = url;
  10329. this.url = url;
  10330. this._noMipmap = noMipmap;
  10331. this._invertY = invertY;
  10332. this._samplingMode = samplingMode;
  10333. this._buffer = buffer;
  10334. this._deleteBuffer = deleteBuffer;
  10335. if (!url) {
  10336. return;
  10337. }
  10338. this._texture = this._getFromCache(url, noMipmap);
  10339. if (!this._texture) {
  10340. if (!scene.useDelayedTextureLoading) {
  10341. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  10342. if (deleteBuffer) {
  10343. delete this._buffer;
  10344. }
  10345. } else {
  10346. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10347. }
  10348. }
  10349. }
  10350. Texture.prototype.delayLoad = function () {
  10351. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10352. return;
  10353. }
  10354. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10355. this._texture = this._getFromCache(this.url, this._noMipmap);
  10356. if (!this._texture) {
  10357. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  10358. if (this._deleteBuffer) {
  10359. delete this._buffer;
  10360. }
  10361. }
  10362. };
  10363. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  10364. x -= this.uOffset + 0.5;
  10365. y -= this.vOffset + 0.5;
  10366. z -= 0.5;
  10367. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  10368. t.x *= this.uScale;
  10369. t.y *= this.vScale;
  10370. t.x += 0.5;
  10371. t.y += 0.5;
  10372. t.z += 0.5;
  10373. };
  10374. Texture.prototype.getTextureMatrix = function () {
  10375. 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) {
  10376. return this._cachedTextureMatrix;
  10377. }
  10378. this._cachedUOffset = this.uOffset;
  10379. this._cachedVOffset = this.vOffset;
  10380. this._cachedUScale = this.uScale;
  10381. this._cachedVScale = this.vScale;
  10382. this._cachedUAng = this.uAng;
  10383. this._cachedVAng = this.vAng;
  10384. this._cachedWAng = this.wAng;
  10385. if (!this._cachedTextureMatrix) {
  10386. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10387. this._rowGenerationMatrix = new BABYLON.Matrix();
  10388. this._t0 = BABYLON.Vector3.Zero();
  10389. this._t1 = BABYLON.Vector3.Zero();
  10390. this._t2 = BABYLON.Vector3.Zero();
  10391. }
  10392. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  10393. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  10394. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  10395. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  10396. this._t1.subtractInPlace(this._t0);
  10397. this._t2.subtractInPlace(this._t0);
  10398. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10399. this._cachedTextureMatrix.m[0] = this._t1.x;
  10400. this._cachedTextureMatrix.m[1] = this._t1.y;
  10401. this._cachedTextureMatrix.m[2] = this._t1.z;
  10402. this._cachedTextureMatrix.m[4] = this._t2.x;
  10403. this._cachedTextureMatrix.m[5] = this._t2.y;
  10404. this._cachedTextureMatrix.m[6] = this._t2.z;
  10405. this._cachedTextureMatrix.m[8] = this._t0.x;
  10406. this._cachedTextureMatrix.m[9] = this._t0.y;
  10407. this._cachedTextureMatrix.m[10] = this._t0.z;
  10408. return this._cachedTextureMatrix;
  10409. };
  10410. Texture.prototype.getReflectionTextureMatrix = function () {
  10411. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  10412. return this._cachedTextureMatrix;
  10413. }
  10414. if (!this._cachedTextureMatrix) {
  10415. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10416. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  10417. }
  10418. switch (this.coordinatesMode) {
  10419. case BABYLON.Texture.SPHERICAL_MODE:
  10420. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10421. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  10422. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  10423. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  10424. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  10425. break;
  10426. case BABYLON.Texture.PLANAR_MODE:
  10427. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10428. this._cachedTextureMatrix[0] = this.uScale;
  10429. this._cachedTextureMatrix[5] = this.vScale;
  10430. this._cachedTextureMatrix[12] = this.uOffset;
  10431. this._cachedTextureMatrix[13] = this.vOffset;
  10432. break;
  10433. case BABYLON.Texture.PROJECTION_MODE:
  10434. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  10435. this._projectionModeMatrix.m[0] = 0.5;
  10436. this._projectionModeMatrix.m[5] = -0.5;
  10437. this._projectionModeMatrix.m[10] = 0.0;
  10438. this._projectionModeMatrix.m[12] = 0.5;
  10439. this._projectionModeMatrix.m[13] = 0.5;
  10440. this._projectionModeMatrix.m[14] = 1.0;
  10441. this._projectionModeMatrix.m[15] = 1.0;
  10442. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  10443. break;
  10444. default:
  10445. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10446. break;
  10447. }
  10448. return this._cachedTextureMatrix;
  10449. };
  10450. Texture.prototype.clone = function () {
  10451. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  10452. newTexture.hasAlpha = this.hasAlpha;
  10453. newTexture.level = this.level;
  10454. newTexture.wrapU = this.wrapU;
  10455. newTexture.wrapV = this.wrapV;
  10456. newTexture.coordinatesIndex = this.coordinatesIndex;
  10457. newTexture.coordinatesMode = this.coordinatesMode;
  10458. newTexture.uOffset = this.uOffset;
  10459. newTexture.vOffset = this.vOffset;
  10460. newTexture.uScale = this.uScale;
  10461. newTexture.vScale = this.vScale;
  10462. newTexture.uAng = this.uAng;
  10463. newTexture.vAng = this.vAng;
  10464. newTexture.wAng = this.wAng;
  10465. return newTexture;
  10466. };
  10467. Texture.NEAREST_SAMPLINGMODE = 1;
  10468. Texture.BILINEAR_SAMPLINGMODE = 2;
  10469. Texture.TRILINEAR_SAMPLINGMODE = 3;
  10470. Texture.EXPLICIT_MODE = 0;
  10471. Texture.SPHERICAL_MODE = 1;
  10472. Texture.PLANAR_MODE = 2;
  10473. Texture.CUBIC_MODE = 3;
  10474. Texture.PROJECTION_MODE = 4;
  10475. Texture.SKYBOX_MODE = 5;
  10476. Texture.CLAMP_ADDRESSMODE = 0;
  10477. Texture.WRAP_ADDRESSMODE = 1;
  10478. Texture.MIRROR_ADDRESSMODE = 2;
  10479. return Texture;
  10480. })(BABYLON.BaseTexture);
  10481. BABYLON.Texture = Texture;
  10482. })(BABYLON || (BABYLON = {}));
  10483. var __extends = this.__extends || function (d, b) {
  10484. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10485. function __() { this.constructor = d; }
  10486. __.prototype = b.prototype;
  10487. d.prototype = new __();
  10488. };
  10489. var BABYLON;
  10490. (function (BABYLON) {
  10491. var CubeTexture = (function (_super) {
  10492. __extends(CubeTexture, _super);
  10493. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  10494. _super.call(this, scene);
  10495. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  10496. this.name = rootUrl;
  10497. this.url = rootUrl;
  10498. this._noMipmap = noMipmap;
  10499. this.hasAlpha = false;
  10500. this._texture = this._getFromCache(rootUrl, noMipmap);
  10501. if (!extensions) {
  10502. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  10503. }
  10504. this._extensions = extensions;
  10505. if (!this._texture) {
  10506. if (!scene.useDelayedTextureLoading) {
  10507. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  10508. } else {
  10509. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10510. }
  10511. }
  10512. this.isCube = true;
  10513. this._textureMatrix = BABYLON.Matrix.Identity();
  10514. }
  10515. CubeTexture.prototype.clone = function () {
  10516. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  10517. newTexture.level = this.level;
  10518. newTexture.wrapU = this.wrapU;
  10519. newTexture.wrapV = this.wrapV;
  10520. newTexture.coordinatesIndex = this.coordinatesIndex;
  10521. newTexture.coordinatesMode = this.coordinatesMode;
  10522. return newTexture;
  10523. };
  10524. CubeTexture.prototype.delayLoad = function () {
  10525. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10526. return;
  10527. }
  10528. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10529. this._texture = this._getFromCache(this.url, this._noMipmap);
  10530. if (!this._texture) {
  10531. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  10532. }
  10533. };
  10534. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  10535. return this._textureMatrix;
  10536. };
  10537. return CubeTexture;
  10538. })(BABYLON.BaseTexture);
  10539. BABYLON.CubeTexture = CubeTexture;
  10540. })(BABYLON || (BABYLON = {}));
  10541. var __extends = this.__extends || function (d, b) {
  10542. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10543. function __() { this.constructor = d; }
  10544. __.prototype = b.prototype;
  10545. d.prototype = new __();
  10546. };
  10547. var BABYLON;
  10548. (function (BABYLON) {
  10549. var ProceduralTexture = (function (_super) {
  10550. __extends(ProceduralTexture, _super);
  10551. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  10552. _super.call(this, null, scene, !generateMipMaps);
  10553. this._currentRefreshId = -1;
  10554. this._refreshRate = 1;
  10555. this._vertexDeclaration = [2];
  10556. this._vertexStrideSize = 2 * 4;
  10557. this._uniforms = new Array();
  10558. this._samplers = new Array();
  10559. this._textures = new Array();
  10560. this._floats = new Array();
  10561. this._floatsArrays = {};
  10562. this._colors3 = new Array();
  10563. this._colors4 = new Array();
  10564. this._vectors2 = new Array();
  10565. this._vectors3 = new Array();
  10566. this._matrices = new Array();
  10567. scene._proceduralTextures.push(this);
  10568. this.name = name;
  10569. this.isRenderTarget = true;
  10570. this._size = size;
  10571. this._generateMipMaps = generateMipMaps;
  10572. this._fragment = fragment;
  10573. this._fallbackTexture = fallbackTexture;
  10574. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10575. var vertices = [];
  10576. vertices.push(1, 1);
  10577. vertices.push(-1, 1);
  10578. vertices.push(-1, -1);
  10579. vertices.push(1, -1);
  10580. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  10581. var indices = [];
  10582. indices.push(0);
  10583. indices.push(1);
  10584. indices.push(2);
  10585. indices.push(0);
  10586. indices.push(2);
  10587. indices.push(3);
  10588. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  10589. }
  10590. ProceduralTexture.prototype.isReady = function () {
  10591. var _this = this;
  10592. var engine = this.getScene().getEngine();
  10593. this._effect = engine.createEffect({ vertex: "procedural", fragment: this._fragment }, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  10594. _this.releaseInternalTexture();
  10595. _this._texture = _this._fallbackTexture._texture;
  10596. _this._texture.references++;
  10597. });
  10598. return this._effect.isReady();
  10599. };
  10600. ProceduralTexture.prototype.resetRefreshCounter = function () {
  10601. this._currentRefreshId = -1;
  10602. };
  10603. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  10604. get: function () {
  10605. return this._refreshRate;
  10606. },
  10607. set: function (value) {
  10608. this._refreshRate = value;
  10609. this.resetRefreshCounter();
  10610. },
  10611. enumerable: true,
  10612. configurable: true
  10613. });
  10614. ProceduralTexture.prototype._shouldRender = function () {
  10615. if (!this.isReady() || !this._texture) {
  10616. return false;
  10617. }
  10618. if (this._currentRefreshId === -1) {
  10619. this._currentRefreshId = 1;
  10620. return true;
  10621. }
  10622. if (this.refreshRate == this._currentRefreshId) {
  10623. this._currentRefreshId = 1;
  10624. return true;
  10625. }
  10626. this._currentRefreshId++;
  10627. return false;
  10628. };
  10629. ProceduralTexture.prototype.getRenderSize = function () {
  10630. return this._size;
  10631. };
  10632. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  10633. this.releaseInternalTexture();
  10634. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  10635. };
  10636. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  10637. if (this._uniforms.indexOf(uniformName) === -1) {
  10638. this._uniforms.push(uniformName);
  10639. }
  10640. };
  10641. ProceduralTexture.prototype.setTexture = function (name, texture) {
  10642. if (this._samplers.indexOf(name) === -1) {
  10643. this._samplers.push(name);
  10644. }
  10645. this._textures[name] = texture;
  10646. return this;
  10647. };
  10648. ProceduralTexture.prototype.setFloat = function (name, value) {
  10649. this._checkUniform(name);
  10650. this._floats[name] = value;
  10651. return this;
  10652. };
  10653. ProceduralTexture.prototype.setFloats = function (name, value) {
  10654. this._checkUniform(name);
  10655. this._floatsArrays[name] = value;
  10656. return this;
  10657. };
  10658. ProceduralTexture.prototype.setColor3 = function (name, value) {
  10659. this._checkUniform(name);
  10660. this._colors3[name] = value;
  10661. return this;
  10662. };
  10663. ProceduralTexture.prototype.setColor4 = function (name, value) {
  10664. this._checkUniform(name);
  10665. this._colors4[name] = value;
  10666. return this;
  10667. };
  10668. ProceduralTexture.prototype.setVector2 = function (name, value) {
  10669. this._checkUniform(name);
  10670. this._vectors2[name] = value;
  10671. return this;
  10672. };
  10673. ProceduralTexture.prototype.setVector3 = function (name, value) {
  10674. this._checkUniform(name);
  10675. this._vectors3[name] = value;
  10676. return this;
  10677. };
  10678. ProceduralTexture.prototype.setMatrix = function (name, value) {
  10679. this._checkUniform(name);
  10680. this._matrices[name] = value;
  10681. return this;
  10682. };
  10683. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  10684. var scene = this.getScene();
  10685. var engine = scene.getEngine();
  10686. engine.bindFramebuffer(this._texture);
  10687. engine.clear(scene.clearColor, true, true);
  10688. engine.enableEffect(this._effect);
  10689. engine.setState(false);
  10690. for (var name in this._textures) {
  10691. this._effect.setTexture(name, this._textures[name]);
  10692. }
  10693. for (name in this._floats) {
  10694. this._effect.setFloat(name, this._floats[name]);
  10695. }
  10696. for (name in this._floatsArrays) {
  10697. this._effect.setArray(name, this._floatsArrays[name]);
  10698. }
  10699. for (name in this._colors3) {
  10700. this._effect.setColor3(name, this._colors3[name]);
  10701. }
  10702. for (name in this._colors4) {
  10703. var color = this._colors4[name];
  10704. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  10705. }
  10706. for (name in this._vectors2) {
  10707. this._effect.setVector2(name, this._vectors2[name]);
  10708. }
  10709. for (name in this._vectors3) {
  10710. this._effect.setVector3(name, this._vectors3[name]);
  10711. }
  10712. for (name in this._matrices) {
  10713. this._effect.setMatrix(name, this._matrices[name]);
  10714. }
  10715. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  10716. engine.draw(WebGLRenderingContext.TRIANGLES, 0, 6);
  10717. engine.unBindFramebuffer(this._texture);
  10718. };
  10719. ProceduralTexture.prototype.clone = function () {
  10720. var textureSize = this.getSize();
  10721. var newTexture = new BABYLON.ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  10722. newTexture.hasAlpha = this.hasAlpha;
  10723. newTexture.level = this.level;
  10724. newTexture.coordinatesMode = this.coordinatesMode;
  10725. return newTexture;
  10726. };
  10727. ProceduralTexture.prototype.dispose = function () {
  10728. var index = this.getScene()._proceduralTextures.indexOf(this);
  10729. if (index >= 0) {
  10730. this.getScene()._proceduralTextures.splice(index, 1);
  10731. }
  10732. _super.prototype.dispose.call(this);
  10733. };
  10734. return ProceduralTexture;
  10735. })(BABYLON.Texture);
  10736. BABYLON.ProceduralTexture = ProceduralTexture;
  10737. })(BABYLON || (BABYLON = {}));
  10738. var __extends = this.__extends || function (d, b) {
  10739. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10740. function __() { this.constructor = d; }
  10741. __.prototype = b.prototype;
  10742. d.prototype = new __();
  10743. };
  10744. var BABYLON;
  10745. (function (BABYLON) {
  10746. var RenderTargetTexture = (function (_super) {
  10747. __extends(RenderTargetTexture, _super);
  10748. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  10749. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  10750. _super.call(this, null, scene, !generateMipMaps);
  10751. this.renderList = new Array();
  10752. this.renderParticles = true;
  10753. this.renderSprites = false;
  10754. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  10755. this._currentRefreshId = -1;
  10756. this._refreshRate = 1;
  10757. this.name = name;
  10758. this.isRenderTarget = true;
  10759. this._size = size;
  10760. this._generateMipMaps = generateMipMaps;
  10761. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  10762. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10763. this._renderingManager = new BABYLON.RenderingManager(scene);
  10764. }
  10765. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  10766. this._currentRefreshId = -1;
  10767. };
  10768. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  10769. get: function () {
  10770. return this._refreshRate;
  10771. },
  10772. set: function (value) {
  10773. this._refreshRate = value;
  10774. this.resetRefreshCounter();
  10775. },
  10776. enumerable: true,
  10777. configurable: true
  10778. });
  10779. RenderTargetTexture.prototype._shouldRender = function () {
  10780. if (this._currentRefreshId === -1) {
  10781. this._currentRefreshId = 1;
  10782. return true;
  10783. }
  10784. if (this.refreshRate == this._currentRefreshId) {
  10785. this._currentRefreshId = 1;
  10786. return true;
  10787. }
  10788. this._currentRefreshId++;
  10789. return false;
  10790. };
  10791. RenderTargetTexture.prototype.getRenderSize = function () {
  10792. return this._size;
  10793. };
  10794. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  10795. this.releaseInternalTexture();
  10796. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  10797. };
  10798. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  10799. var scene = this.getScene();
  10800. var engine = scene.getEngine();
  10801. if (this._waitingRenderList) {
  10802. this.renderList = [];
  10803. for (var index = 0; index < this._waitingRenderList.length; index++) {
  10804. var id = this._waitingRenderList[index];
  10805. this.renderList.push(scene.getMeshByID(id));
  10806. }
  10807. delete this._waitingRenderList;
  10808. }
  10809. if (!this.renderList) {
  10810. return;
  10811. }
  10812. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  10813. engine.bindFramebuffer(this._texture);
  10814. }
  10815. engine.clear(scene.clearColor, true, true);
  10816. this._renderingManager.reset();
  10817. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  10818. var mesh = this.renderList[meshIndex];
  10819. if (mesh) {
  10820. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  10821. this.resetRefreshCounter();
  10822. continue;
  10823. }
  10824. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  10825. mesh._activate(scene.getRenderId());
  10826. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  10827. var subMesh = mesh.subMeshes[subIndex];
  10828. scene._activeVertices += subMesh.verticesCount;
  10829. this._renderingManager.dispatch(subMesh);
  10830. }
  10831. }
  10832. }
  10833. }
  10834. if (!this._doNotChangeAspectRatio) {
  10835. scene.updateTransformMatrix(true);
  10836. }
  10837. if (this.onBeforeRender) {
  10838. this.onBeforeRender();
  10839. }
  10840. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  10841. if (useCameraPostProcess) {
  10842. scene.postProcessManager._finalizeFrame(false, this._texture);
  10843. }
  10844. if (this.onAfterRender) {
  10845. this.onAfterRender();
  10846. }
  10847. engine.unBindFramebuffer(this._texture);
  10848. if (!this._doNotChangeAspectRatio) {
  10849. scene.updateTransformMatrix(true);
  10850. }
  10851. };
  10852. RenderTargetTexture.prototype.clone = function () {
  10853. var textureSize = this.getSize();
  10854. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10855. newTexture.hasAlpha = this.hasAlpha;
  10856. newTexture.level = this.level;
  10857. newTexture.coordinatesMode = this.coordinatesMode;
  10858. newTexture.renderList = this.renderList.slice(0);
  10859. return newTexture;
  10860. };
  10861. return RenderTargetTexture;
  10862. })(BABYLON.Texture);
  10863. BABYLON.RenderTargetTexture = RenderTargetTexture;
  10864. })(BABYLON || (BABYLON = {}));
  10865. var __extends = this.__extends || function (d, b) {
  10866. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10867. function __() { this.constructor = d; }
  10868. __.prototype = b.prototype;
  10869. d.prototype = new __();
  10870. };
  10871. var BABYLON;
  10872. (function (BABYLON) {
  10873. var MirrorTexture = (function (_super) {
  10874. __extends(MirrorTexture, _super);
  10875. function MirrorTexture(name, size, scene, generateMipMaps) {
  10876. var _this = this;
  10877. _super.call(this, name, size, scene, generateMipMaps, true);
  10878. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  10879. this._transformMatrix = BABYLON.Matrix.Zero();
  10880. this._mirrorMatrix = BABYLON.Matrix.Zero();
  10881. this.onBeforeRender = function () {
  10882. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  10883. _this._savedViewMatrix = scene.getViewMatrix();
  10884. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  10885. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  10886. scene.clipPlane = _this.mirrorPlane;
  10887. scene.getEngine().cullBackFaces = false;
  10888. };
  10889. this.onAfterRender = function () {
  10890. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  10891. scene.getEngine().cullBackFaces = true;
  10892. delete scene.clipPlane;
  10893. };
  10894. }
  10895. MirrorTexture.prototype.clone = function () {
  10896. var textureSize = this.getSize();
  10897. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10898. newTexture.hasAlpha = this.hasAlpha;
  10899. newTexture.level = this.level;
  10900. newTexture.mirrorPlane = this.mirrorPlane.clone();
  10901. newTexture.renderList = this.renderList.slice(0);
  10902. return newTexture;
  10903. };
  10904. return MirrorTexture;
  10905. })(BABYLON.RenderTargetTexture);
  10906. BABYLON.MirrorTexture = MirrorTexture;
  10907. })(BABYLON || (BABYLON = {}));
  10908. var __extends = this.__extends || function (d, b) {
  10909. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10910. function __() { this.constructor = d; }
  10911. __.prototype = b.prototype;
  10912. d.prototype = new __();
  10913. };
  10914. var BABYLON;
  10915. (function (BABYLON) {
  10916. var DynamicTexture = (function (_super) {
  10917. __extends(DynamicTexture, _super);
  10918. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  10919. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10920. _super.call(this, null, scene, !generateMipMaps);
  10921. this.name = name;
  10922. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10923. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10924. this._generateMipMaps = generateMipMaps;
  10925. if (options.getContext) {
  10926. this._canvas = options;
  10927. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10928. } else {
  10929. this._canvas = document.createElement("canvas");
  10930. if (options.width) {
  10931. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10932. } else {
  10933. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  10934. }
  10935. }
  10936. var textureSize = this.getSize();
  10937. this._canvas.width = textureSize.width;
  10938. this._canvas.height = textureSize.height;
  10939. this._context = this._canvas.getContext("2d");
  10940. }
  10941. DynamicTexture.prototype.getContext = function () {
  10942. return this._context;
  10943. };
  10944. DynamicTexture.prototype.update = function (invertY) {
  10945. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  10946. };
  10947. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  10948. var size = this.getSize();
  10949. if (clearColor) {
  10950. this._context.fillStyle = clearColor;
  10951. this._context.fillRect(0, 0, size.width, size.height);
  10952. }
  10953. this._context.font = font;
  10954. if (x === null) {
  10955. var textSize = this._context.measureText(text);
  10956. x = (size.width - textSize.width) / 2;
  10957. }
  10958. this._context.fillStyle = color;
  10959. this._context.fillText(text, x, y);
  10960. this.update(invertY);
  10961. };
  10962. DynamicTexture.prototype.clone = function () {
  10963. var textureSize = this.getSize();
  10964. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10965. newTexture.hasAlpha = this.hasAlpha;
  10966. newTexture.level = this.level;
  10967. newTexture.wrapU = this.wrapU;
  10968. newTexture.wrapV = this.wrapV;
  10969. return newTexture;
  10970. };
  10971. return DynamicTexture;
  10972. })(BABYLON.Texture);
  10973. BABYLON.DynamicTexture = DynamicTexture;
  10974. })(BABYLON || (BABYLON = {}));
  10975. var __extends = this.__extends || function (d, b) {
  10976. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10977. function __() { this.constructor = d; }
  10978. __.prototype = b.prototype;
  10979. d.prototype = new __();
  10980. };
  10981. var BABYLON;
  10982. (function (BABYLON) {
  10983. var VideoTexture = (function (_super) {
  10984. __extends(VideoTexture, _super);
  10985. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  10986. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10987. var _this = this;
  10988. _super.call(this, null, scene, !generateMipMaps, invertY);
  10989. this._autoLaunch = true;
  10990. this.name = name;
  10991. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10992. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10993. var requiredWidth = size.width || size;
  10994. var requiredHeight = size.height || size;
  10995. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  10996. var textureSize = this.getSize();
  10997. this.video = document.createElement("video");
  10998. this.video.width = textureSize.width;
  10999. this.video.height = textureSize.height;
  11000. this.video.autoplay = false;
  11001. this.video.loop = true;
  11002. this.video.addEventListener("canplaythrough", function () {
  11003. if (_this._texture) {
  11004. _this._texture.isReady = true;
  11005. }
  11006. });
  11007. urls.forEach(function (url) {
  11008. var source = document.createElement("source");
  11009. source.src = url;
  11010. _this.video.appendChild(source);
  11011. });
  11012. this._lastUpdate = new Date().getTime();
  11013. }
  11014. VideoTexture.prototype.update = function () {
  11015. if (this._autoLaunch) {
  11016. this._autoLaunch = false;
  11017. this.video.play();
  11018. }
  11019. var now = new Date().getTime();
  11020. if (now - this._lastUpdate < 15) {
  11021. return false;
  11022. }
  11023. this._lastUpdate = now;
  11024. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  11025. return true;
  11026. };
  11027. return VideoTexture;
  11028. })(BABYLON.Texture);
  11029. BABYLON.VideoTexture = VideoTexture;
  11030. })(BABYLON || (BABYLON = {}));
  11031. var BABYLON;
  11032. (function (BABYLON) {
  11033. var EffectFallbacks = (function () {
  11034. function EffectFallbacks() {
  11035. this._defines = {};
  11036. this._currentRank = 32;
  11037. this._maxRank = -1;
  11038. }
  11039. EffectFallbacks.prototype.addFallback = function (rank, define) {
  11040. if (!this._defines[rank]) {
  11041. if (rank < this._currentRank) {
  11042. this._currentRank = rank;
  11043. }
  11044. if (rank > this._maxRank) {
  11045. this._maxRank = rank;
  11046. }
  11047. this._defines[rank] = new Array();
  11048. }
  11049. this._defines[rank].push(define);
  11050. };
  11051. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  11052. get: function () {
  11053. return this._currentRank <= this._maxRank;
  11054. },
  11055. enumerable: true,
  11056. configurable: true
  11057. });
  11058. EffectFallbacks.prototype.reduce = function (currentDefines) {
  11059. var currentFallbacks = this._defines[this._currentRank];
  11060. for (var index = 0; index < currentFallbacks.length; index++) {
  11061. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  11062. }
  11063. this._currentRank++;
  11064. return currentDefines;
  11065. };
  11066. return EffectFallbacks;
  11067. })();
  11068. BABYLON.EffectFallbacks = EffectFallbacks;
  11069. var Effect = (function () {
  11070. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  11071. var _this = this;
  11072. this._isReady = false;
  11073. this._compilationError = "";
  11074. this._valueCache = [];
  11075. this._engine = engine;
  11076. this.name = baseName;
  11077. this.defines = defines;
  11078. this._uniformsNames = uniformsNames.concat(samplers);
  11079. this._samplers = samplers;
  11080. this._attributesNames = attributesNames;
  11081. this.onError = onError;
  11082. this.onCompiled = onCompiled;
  11083. var vertexSource;
  11084. var fragmentSource;
  11085. if (baseName.vertexElement) {
  11086. vertexSource = document.getElementById(baseName.vertexElement);
  11087. if (!vertexSource) {
  11088. vertexSource = baseName.vertexElement;
  11089. }
  11090. } else {
  11091. vertexSource = baseName.vertex || baseName;
  11092. }
  11093. if (baseName.fragmentElement) {
  11094. fragmentSource = document.getElementById(baseName.fragmentElement);
  11095. if (!fragmentSource) {
  11096. fragmentSource = baseName.fragmentElement;
  11097. }
  11098. } else {
  11099. fragmentSource = baseName.fragment || baseName;
  11100. }
  11101. this._loadVertexShader(vertexSource, function (vertexCode) {
  11102. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  11103. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  11104. });
  11105. });
  11106. }
  11107. Effect.prototype.isReady = function () {
  11108. return this._isReady;
  11109. };
  11110. Effect.prototype.getProgram = function () {
  11111. return this._program;
  11112. };
  11113. Effect.prototype.getAttributesNames = function () {
  11114. return this._attributesNames;
  11115. };
  11116. Effect.prototype.getAttributeLocation = function (index) {
  11117. return this._attributes[index];
  11118. };
  11119. Effect.prototype.getAttributeLocationByName = function (name) {
  11120. var index = this._attributesNames.indexOf(name);
  11121. return this._attributes[index];
  11122. };
  11123. Effect.prototype.getAttributesCount = function () {
  11124. return this._attributes.length;
  11125. };
  11126. Effect.prototype.getUniformIndex = function (uniformName) {
  11127. return this._uniformsNames.indexOf(uniformName);
  11128. };
  11129. Effect.prototype.getUniform = function (uniformName) {
  11130. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  11131. };
  11132. Effect.prototype.getSamplers = function () {
  11133. return this._samplers;
  11134. };
  11135. Effect.prototype.getCompilationError = function () {
  11136. return this._compilationError;
  11137. };
  11138. Effect.prototype._loadVertexShader = function (vertex, callback) {
  11139. if (vertex instanceof HTMLElement) {
  11140. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  11141. callback(vertexCode);
  11142. return;
  11143. }
  11144. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  11145. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  11146. return;
  11147. }
  11148. var vertexShaderUrl;
  11149. if (vertex[0] === ".") {
  11150. vertexShaderUrl = vertex;
  11151. } else {
  11152. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  11153. }
  11154. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  11155. };
  11156. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  11157. if (fragment instanceof HTMLElement) {
  11158. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  11159. callback(fragmentCode);
  11160. return;
  11161. }
  11162. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  11163. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  11164. return;
  11165. }
  11166. if (BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]) {
  11167. callback(BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]);
  11168. return;
  11169. }
  11170. var fragmentShaderUrl;
  11171. if (fragment[0] === ".") {
  11172. fragmentShaderUrl = fragment;
  11173. } else {
  11174. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  11175. }
  11176. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  11177. };
  11178. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  11179. try {
  11180. var engine = this._engine;
  11181. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  11182. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  11183. this._attributes = engine.getAttributes(this._program, attributesNames);
  11184. for (var index = 0; index < this._samplers.length; index++) {
  11185. var sampler = this.getUniform(this._samplers[index]);
  11186. if (sampler == null) {
  11187. this._samplers.splice(index, 1);
  11188. index--;
  11189. }
  11190. }
  11191. engine.bindSamplers(this);
  11192. this._isReady = true;
  11193. if (this.onCompiled) {
  11194. this.onCompiled(this);
  11195. }
  11196. } catch (e) {
  11197. if (fallbacks && fallbacks.isMoreFallbacks) {
  11198. defines = fallbacks.reduce(defines);
  11199. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  11200. } else {
  11201. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  11202. BABYLON.Tools.Error("Defines: " + defines);
  11203. BABYLON.Tools.Error("Error: " + e.message);
  11204. this._compilationError = e.message;
  11205. if (this.onError) {
  11206. this.onError(this, this._compilationError);
  11207. }
  11208. }
  11209. }
  11210. };
  11211. Effect.prototype._bindTexture = function (channel, texture) {
  11212. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  11213. };
  11214. Effect.prototype.setTexture = function (channel, texture) {
  11215. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  11216. };
  11217. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11218. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  11219. };
  11220. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  11221. if (!this._valueCache[uniformName]) {
  11222. this._valueCache[uniformName] = [x, y];
  11223. return;
  11224. }
  11225. this._valueCache[uniformName][0] = x;
  11226. this._valueCache[uniformName][1] = y;
  11227. };
  11228. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  11229. if (!this._valueCache[uniformName]) {
  11230. this._valueCache[uniformName] = [x, y, z];
  11231. return;
  11232. }
  11233. this._valueCache[uniformName][0] = x;
  11234. this._valueCache[uniformName][1] = y;
  11235. this._valueCache[uniformName][2] = z;
  11236. };
  11237. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  11238. if (!this._valueCache[uniformName]) {
  11239. this._valueCache[uniformName] = [x, y, z, w];
  11240. return;
  11241. }
  11242. this._valueCache[uniformName][0] = x;
  11243. this._valueCache[uniformName][1] = y;
  11244. this._valueCache[uniformName][2] = z;
  11245. this._valueCache[uniformName][3] = w;
  11246. };
  11247. Effect.prototype.setArray = function (uniformName, array) {
  11248. this._engine.setArray(this.getUniform(uniformName), array);
  11249. return this;
  11250. };
  11251. Effect.prototype.setMatrices = function (uniformName, matrices) {
  11252. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  11253. return this;
  11254. };
  11255. Effect.prototype.setMatrix = function (uniformName, matrix) {
  11256. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  11257. return this;
  11258. };
  11259. Effect.prototype.setFloat = function (uniformName, value) {
  11260. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  11261. return this;
  11262. this._valueCache[uniformName] = value;
  11263. this._engine.setFloat(this.getUniform(uniformName), value);
  11264. return this;
  11265. };
  11266. Effect.prototype.setBool = function (uniformName, bool) {
  11267. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  11268. return this;
  11269. this._valueCache[uniformName] = bool;
  11270. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  11271. return this;
  11272. };
  11273. Effect.prototype.setVector2 = function (uniformName, vector2) {
  11274. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  11275. return this;
  11276. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  11277. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  11278. return this;
  11279. };
  11280. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  11281. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  11282. return this;
  11283. this._cacheFloat2(uniformName, x, y);
  11284. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  11285. return this;
  11286. };
  11287. Effect.prototype.setVector3 = function (uniformName, vector3) {
  11288. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  11289. return this;
  11290. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  11291. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  11292. return this;
  11293. };
  11294. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  11295. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  11296. return this;
  11297. this._cacheFloat3(uniformName, x, y, z);
  11298. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  11299. return this;
  11300. };
  11301. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  11302. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  11303. return this;
  11304. this._cacheFloat4(uniformName, x, y, z, w);
  11305. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  11306. return this;
  11307. };
  11308. Effect.prototype.setColor3 = function (uniformName, color3) {
  11309. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  11310. return this;
  11311. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  11312. this._engine.setColor3(this.getUniform(uniformName), color3);
  11313. return this;
  11314. };
  11315. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  11316. 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)
  11317. return this;
  11318. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  11319. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  11320. return this;
  11321. };
  11322. 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}",
  11323. 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}",
  11324. 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}",
  11325. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  11326. 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}",
  11327. 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}",
  11328. 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 vec3 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 for (int i = 0; i<4; i++){\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[i] / 1500.0)) < depth.z){\n visibility -= 0.2;\n }\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 * vBumpInfos.y;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW, -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 diffuseColor *= vColor;\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 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}",
  11329. 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 vec3 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// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 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 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#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\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}",
  11330. 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}",
  11331. 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}",
  11332. firePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform float iGlobalTime;\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 alpha;\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\n vec2 p = vUV * 8.0;\n float q = fbm(p - iGlobalTime * 0.1);\n vec2 r = vec2(fbm(p + q + iGlobalTime * speed.x - p.x - p.y), fbm(p + q - iGlobalTime * speed.y));\n vec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\n gl_FragColor = vec4(c * cos(shift * vUV.y), alpha);\n\n}",
  11333. 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}",
  11334. 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}",
  11335. 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}",
  11336. 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 vec3 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 diffuseColor *= vColor;\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 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}",
  11337. 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 vec3 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 vec3 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}",
  11338. 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}",
  11339. 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}",
  11340. 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}",
  11341. outlinePixelShader:"precision highp float;\n\nuniform vec3 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 = vec4(color, 1.);\n}",
  11342. 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}",
  11343. 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}",
  11344. 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}",
  11345. 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}",
  11346. 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}",
  11347. 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}",
  11348. 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}",
  11349. 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}",
  11350. 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}",
  11351. 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}",
  11352. 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}",
  11353. woodPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition; \nvarying vec2 vUV; \n\nuniform float ampScale;\nuniform float ringScale;\nuniform vec3 woodColor1;\nuniform vec3 woodColor2;\n\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\n vec2 positionWood = vPosition;\n float r = ringScale * sqrt(dot(positionWood.xy, positionWood.xy));\n r = r + fbm(vPosition);\n r = r - floor(r);\n r = smoothstep(0.0, 0.8, r) - smoothstep(0.8, 1.0, r);\n\n gl_FragColor = vec4(mix(woodColor1, woodColor2, r), 1.0);\n}",
  11354. };
  11355. return Effect;
  11356. })();
  11357. BABYLON.Effect = Effect;
  11358. })(BABYLON || (BABYLON = {}));
  11359. var BABYLON;
  11360. (function (BABYLON) {
  11361. var Material = (function () {
  11362. function Material(name, scene, doNotAdd) {
  11363. this.name = name;
  11364. this.checkReadyOnEveryCall = true;
  11365. this.checkReadyOnlyOnce = false;
  11366. this.state = "";
  11367. this.alpha = 1.0;
  11368. this.drawAs = WebGLRenderingContext.TRIANGLES;
  11369. this.backFaceCulling = true;
  11370. this._wasPreviouslyReady = false;
  11371. this.id = name;
  11372. this._scene = scene;
  11373. if (!doNotAdd) {
  11374. scene.materials.push(this);
  11375. }
  11376. }
  11377. Material.prototype.isReady = function (mesh, useInstances) {
  11378. return true;
  11379. };
  11380. Material.prototype.getEffect = function () {
  11381. return this._effect;
  11382. };
  11383. Material.prototype.getScene = function () {
  11384. return this._scene;
  11385. };
  11386. Material.prototype.needAlphaBlending = function () {
  11387. return (this.alpha < 1.0);
  11388. };
  11389. Material.prototype.needAlphaTesting = function () {
  11390. return false;
  11391. };
  11392. Material.prototype.getAlphaTestTexture = function () {
  11393. return null;
  11394. };
  11395. Material.prototype.trackCreation = function (onCompiled, onError) {
  11396. };
  11397. Material.prototype._preBind = function () {
  11398. var engine = this._scene.getEngine();
  11399. engine.enableEffect(this._effect);
  11400. engine.setState(this.backFaceCulling);
  11401. };
  11402. Material.prototype.bind = function (world, mesh) {
  11403. };
  11404. Material.prototype.bindOnlyWorldMatrix = function (world) {
  11405. };
  11406. Material.prototype.unbind = function () {
  11407. };
  11408. Material.prototype.dispose = function (forceDisposeEffect) {
  11409. var index = this._scene.materials.indexOf(this);
  11410. this._scene.materials.splice(index, 1);
  11411. if (forceDisposeEffect && this._effect) {
  11412. this._scene.getEngine()._releaseEffect(this._effect);
  11413. this._effect = null;
  11414. }
  11415. if (this.onDispose) {
  11416. this.onDispose();
  11417. }
  11418. };
  11419. return Material;
  11420. })();
  11421. BABYLON.Material = Material;
  11422. })(BABYLON || (BABYLON = {}));
  11423. var __extends = this.__extends || function (d, b) {
  11424. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11425. function __() { this.constructor = d; }
  11426. __.prototype = b.prototype;
  11427. d.prototype = new __();
  11428. };
  11429. var BABYLON;
  11430. (function (BABYLON) {
  11431. var maxSimultaneousLights = 4;
  11432. var FresnelParameters = (function () {
  11433. function FresnelParameters() {
  11434. this.isEnabled = true;
  11435. this.leftColor = BABYLON.Color3.White();
  11436. this.rightColor = BABYLON.Color3.Black();
  11437. this.bias = 0;
  11438. this.power = 1;
  11439. }
  11440. return FresnelParameters;
  11441. })();
  11442. BABYLON.FresnelParameters = FresnelParameters;
  11443. var StandardMaterial = (function (_super) {
  11444. __extends(StandardMaterial, _super);
  11445. function StandardMaterial(name, scene) {
  11446. var _this = this;
  11447. _super.call(this, name, scene);
  11448. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11449. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  11450. this.specularColor = new BABYLON.Color3(1, 1, 1);
  11451. this.specularPower = 64;
  11452. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  11453. this.useAlphaFromDiffuseTexture = false;
  11454. this.useSpecularOverAlpha = true;
  11455. this.fogEnabled = true;
  11456. this._cachedDefines = null;
  11457. this._renderTargets = new BABYLON.SmartArray(16);
  11458. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  11459. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  11460. this._scaledDiffuse = new BABYLON.Color3();
  11461. this._scaledSpecular = new BABYLON.Color3();
  11462. this.getRenderTargetTextures = function () {
  11463. _this._renderTargets.reset();
  11464. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  11465. _this._renderTargets.push(_this.reflectionTexture);
  11466. }
  11467. return _this._renderTargets;
  11468. };
  11469. }
  11470. StandardMaterial.prototype.needAlphaBlending = function () {
  11471. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  11472. };
  11473. StandardMaterial.prototype.needAlphaTesting = function () {
  11474. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  11475. };
  11476. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  11477. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  11478. };
  11479. StandardMaterial.prototype.getAlphaTestTexture = function () {
  11480. return this.diffuseTexture;
  11481. };
  11482. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  11483. if (this.checkReadyOnlyOnce) {
  11484. if (this._wasPreviouslyReady) {
  11485. return true;
  11486. }
  11487. }
  11488. var scene = this.getScene();
  11489. if (!this.checkReadyOnEveryCall) {
  11490. if (this._renderId === scene.getRenderId()) {
  11491. return true;
  11492. }
  11493. }
  11494. var engine = scene.getEngine();
  11495. var defines = [];
  11496. var fallbacks = new BABYLON.EffectFallbacks();
  11497. if (scene.texturesEnabled) {
  11498. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  11499. if (!this.diffuseTexture.isReady()) {
  11500. return false;
  11501. } else {
  11502. defines.push("#define DIFFUSE");
  11503. }
  11504. }
  11505. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  11506. if (!this.ambientTexture.isReady()) {
  11507. return false;
  11508. } else {
  11509. defines.push("#define AMBIENT");
  11510. }
  11511. }
  11512. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  11513. if (!this.opacityTexture.isReady()) {
  11514. return false;
  11515. } else {
  11516. defines.push("#define OPACITY");
  11517. if (this.opacityTexture.getAlphaFromRGB) {
  11518. defines.push("#define OPACITYRGB");
  11519. }
  11520. }
  11521. }
  11522. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  11523. if (!this.reflectionTexture.isReady()) {
  11524. return false;
  11525. } else {
  11526. defines.push("#define REFLECTION");
  11527. fallbacks.addFallback(0, "REFLECTION");
  11528. }
  11529. }
  11530. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  11531. if (!this.emissiveTexture.isReady()) {
  11532. return false;
  11533. } else {
  11534. defines.push("#define EMISSIVE");
  11535. }
  11536. }
  11537. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  11538. if (!this.specularTexture.isReady()) {
  11539. return false;
  11540. } else {
  11541. defines.push("#define SPECULAR");
  11542. fallbacks.addFallback(0, "SPECULAR");
  11543. }
  11544. }
  11545. }
  11546. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  11547. if (!this.bumpTexture.isReady()) {
  11548. return false;
  11549. } else {
  11550. defines.push("#define BUMP");
  11551. fallbacks.addFallback(0, "BUMP");
  11552. }
  11553. }
  11554. if (this.useSpecularOverAlpha) {
  11555. defines.push("#define SPECULAROVERALPHA");
  11556. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  11557. }
  11558. if (scene.clipPlane) {
  11559. defines.push("#define CLIPPLANE");
  11560. }
  11561. if (engine.getAlphaTesting()) {
  11562. defines.push("#define ALPHATEST");
  11563. }
  11564. if (this._shouldUseAlphaFromDiffuseTexture()) {
  11565. defines.push("#define ALPHAFROMDIFFUSE");
  11566. }
  11567. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  11568. defines.push("#define FOG");
  11569. fallbacks.addFallback(1, "FOG");
  11570. }
  11571. var shadowsActivated = false;
  11572. var lightIndex = 0;
  11573. if (scene.lightsEnabled) {
  11574. for (var index = 0; index < scene.lights.length; index++) {
  11575. var light = scene.lights[index];
  11576. if (!light.isEnabled()) {
  11577. continue;
  11578. }
  11579. if (light._excludedMeshesIds.length > 0) {
  11580. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  11581. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  11582. if (excludedMesh) {
  11583. light.excludedMeshes.push(excludedMesh);
  11584. }
  11585. }
  11586. light._excludedMeshesIds = [];
  11587. }
  11588. if (light._includedOnlyMeshesIds.length > 0) {
  11589. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  11590. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  11591. if (includedOnlyMesh) {
  11592. light.includedOnlyMeshes.push(includedOnlyMesh);
  11593. }
  11594. }
  11595. light._includedOnlyMeshesIds = [];
  11596. }
  11597. if (!light.canAffectMesh(mesh)) {
  11598. continue;
  11599. }
  11600. defines.push("#define LIGHT" + lightIndex);
  11601. if (lightIndex > 0) {
  11602. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  11603. }
  11604. var type;
  11605. if (light instanceof BABYLON.SpotLight) {
  11606. type = "#define SPOTLIGHT" + lightIndex;
  11607. } else if (light instanceof BABYLON.HemisphericLight) {
  11608. type = "#define HEMILIGHT" + lightIndex;
  11609. } else {
  11610. type = "#define POINTDIRLIGHT" + lightIndex;
  11611. }
  11612. defines.push(type);
  11613. if (lightIndex > 0) {
  11614. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  11615. }
  11616. var shadowGenerator = light.getShadowGenerator();
  11617. if (mesh && mesh.receiveShadows && shadowGenerator) {
  11618. defines.push("#define SHADOW" + lightIndex);
  11619. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  11620. if (!shadowsActivated) {
  11621. defines.push("#define SHADOWS");
  11622. shadowsActivated = true;
  11623. }
  11624. if (shadowGenerator.useVarianceShadowMap) {
  11625. defines.push("#define SHADOWVSM" + lightIndex);
  11626. if (lightIndex > 0) {
  11627. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  11628. }
  11629. }
  11630. if (shadowGenerator.usePoissonSampling) {
  11631. defines.push("#define SHADOWPCF" + lightIndex);
  11632. if (lightIndex > 0) {
  11633. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  11634. }
  11635. }
  11636. }
  11637. lightIndex++;
  11638. if (lightIndex == maxSimultaneousLights)
  11639. break;
  11640. }
  11641. }
  11642. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11643. var fresnelRank = 1;
  11644. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  11645. defines.push("#define DIFFUSEFRESNEL");
  11646. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  11647. fresnelRank++;
  11648. }
  11649. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  11650. defines.push("#define OPACITYFRESNEL");
  11651. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  11652. fresnelRank++;
  11653. }
  11654. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11655. defines.push("#define REFLECTIONFRESNEL");
  11656. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  11657. fresnelRank++;
  11658. }
  11659. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  11660. defines.push("#define EMISSIVEFRESNEL");
  11661. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  11662. fresnelRank++;
  11663. }
  11664. defines.push("#define FRESNEL");
  11665. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  11666. }
  11667. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  11668. if (mesh) {
  11669. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11670. attribs.push(BABYLON.VertexBuffer.UVKind);
  11671. defines.push("#define UV1");
  11672. }
  11673. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11674. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11675. defines.push("#define UV2");
  11676. }
  11677. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  11678. attribs.push(BABYLON.VertexBuffer.ColorKind);
  11679. defines.push("#define VERTEXCOLOR");
  11680. }
  11681. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  11682. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11683. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11684. defines.push("#define BONES");
  11685. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11686. defines.push("#define BONES4");
  11687. fallbacks.addFallback(0, "BONES4");
  11688. }
  11689. if (useInstances) {
  11690. defines.push("#define INSTANCES");
  11691. attribs.push("world0");
  11692. attribs.push("world1");
  11693. attribs.push("world2");
  11694. attribs.push("world3");
  11695. }
  11696. }
  11697. var join = defines.join("\n");
  11698. if (this._cachedDefines != join) {
  11699. this._cachedDefines = join;
  11700. var shaderName = "default";
  11701. if (!scene.getEngine().getCaps().standardDerivatives) {
  11702. shaderName = "legacydefault";
  11703. }
  11704. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  11705. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  11706. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  11707. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  11708. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  11709. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  11710. "vFogInfos", "vFogColor",
  11711. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  11712. "mBones",
  11713. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  11714. "darkness0", "darkness1", "darkness2", "darkness3",
  11715. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  11716. ], [
  11717. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  11718. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  11719. ], join, fallbacks, this.onCompiled, this.onError);
  11720. }
  11721. if (!this._effect.isReady()) {
  11722. return false;
  11723. }
  11724. this._renderId = scene.getRenderId();
  11725. this._wasPreviouslyReady = true;
  11726. return true;
  11727. };
  11728. StandardMaterial.prototype.unbind = function () {
  11729. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  11730. this._effect.setTexture("reflection2DSampler", null);
  11731. }
  11732. };
  11733. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  11734. this._effect.setMatrix("world", world);
  11735. };
  11736. StandardMaterial.prototype.bind = function (world, mesh) {
  11737. var scene = this.getScene();
  11738. this.bindOnlyWorldMatrix(world);
  11739. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  11740. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  11741. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  11742. }
  11743. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  11744. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  11745. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  11746. }
  11747. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  11748. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  11749. }
  11750. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11751. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  11752. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  11753. }
  11754. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  11755. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  11756. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  11757. }
  11758. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  11759. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  11760. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  11761. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  11762. }
  11763. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  11764. this._effect.setTexture("ambientSampler", this.ambientTexture);
  11765. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  11766. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  11767. }
  11768. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  11769. this._effect.setTexture("opacitySampler", this.opacityTexture);
  11770. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  11771. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  11772. }
  11773. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  11774. if (this.reflectionTexture.isCube) {
  11775. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  11776. } else {
  11777. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  11778. }
  11779. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  11780. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  11781. }
  11782. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  11783. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  11784. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  11785. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  11786. }
  11787. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  11788. this._effect.setTexture("specularSampler", this.specularTexture);
  11789. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  11790. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  11791. }
  11792. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  11793. this._effect.setTexture("bumpSampler", this.bumpTexture);
  11794. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  11795. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  11796. }
  11797. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  11798. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  11799. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  11800. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  11801. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  11802. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  11803. if (scene.lightsEnabled) {
  11804. var lightIndex = 0;
  11805. for (var index = 0; index < scene.lights.length; index++) {
  11806. var light = scene.lights[index];
  11807. if (!light.isEnabled()) {
  11808. continue;
  11809. }
  11810. if (!light.canAffectMesh(mesh)) {
  11811. continue;
  11812. }
  11813. if (light instanceof BABYLON.PointLight) {
  11814. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  11815. } else if (light instanceof BABYLON.DirectionalLight) {
  11816. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  11817. } else if (light instanceof BABYLON.SpotLight) {
  11818. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  11819. } else if (light instanceof BABYLON.HemisphericLight) {
  11820. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  11821. }
  11822. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  11823. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  11824. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  11825. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  11826. var shadowGenerator = light.getShadowGenerator();
  11827. if (mesh.receiveShadows && shadowGenerator) {
  11828. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  11829. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  11830. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  11831. }
  11832. lightIndex++;
  11833. if (lightIndex == maxSimultaneousLights)
  11834. break;
  11835. }
  11836. }
  11837. if (scene.clipPlane) {
  11838. var clipPlane = scene.clipPlane;
  11839. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  11840. }
  11841. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  11842. this._effect.setMatrix("view", scene.getViewMatrix());
  11843. }
  11844. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11845. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  11846. this._effect.setColor3("vFogColor", scene.fogColor);
  11847. }
  11848. };
  11849. StandardMaterial.prototype.getAnimatables = function () {
  11850. var results = [];
  11851. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  11852. results.push(this.diffuseTexture);
  11853. }
  11854. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  11855. results.push(this.ambientTexture);
  11856. }
  11857. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  11858. results.push(this.opacityTexture);
  11859. }
  11860. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  11861. results.push(this.reflectionTexture);
  11862. }
  11863. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  11864. results.push(this.emissiveTexture);
  11865. }
  11866. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  11867. results.push(this.specularTexture);
  11868. }
  11869. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  11870. results.push(this.bumpTexture);
  11871. }
  11872. return results;
  11873. };
  11874. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  11875. if (this.diffuseTexture) {
  11876. this.diffuseTexture.dispose();
  11877. }
  11878. if (this.ambientTexture) {
  11879. this.ambientTexture.dispose();
  11880. }
  11881. if (this.opacityTexture) {
  11882. this.opacityTexture.dispose();
  11883. }
  11884. if (this.reflectionTexture) {
  11885. this.reflectionTexture.dispose();
  11886. }
  11887. if (this.emissiveTexture) {
  11888. this.emissiveTexture.dispose();
  11889. }
  11890. if (this.specularTexture) {
  11891. this.specularTexture.dispose();
  11892. }
  11893. if (this.bumpTexture) {
  11894. this.bumpTexture.dispose();
  11895. }
  11896. _super.prototype.dispose.call(this, forceDisposeEffect);
  11897. };
  11898. StandardMaterial.prototype.clone = function (name) {
  11899. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  11900. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  11901. newStandardMaterial.alpha = this.alpha;
  11902. newStandardMaterial.drawAs = this.drawAs;
  11903. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  11904. if (this.diffuseTexture && this.diffuseTexture.clone) {
  11905. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  11906. }
  11907. if (this.ambientTexture && this.ambientTexture.clone) {
  11908. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  11909. }
  11910. if (this.opacityTexture && this.opacityTexture.clone) {
  11911. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  11912. }
  11913. if (this.reflectionTexture && this.reflectionTexture.clone) {
  11914. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  11915. }
  11916. if (this.emissiveTexture && this.emissiveTexture.clone) {
  11917. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  11918. }
  11919. if (this.specularTexture && this.specularTexture.clone) {
  11920. newStandardMaterial.specularTexture = this.specularTexture.clone();
  11921. }
  11922. if (this.bumpTexture && this.bumpTexture.clone) {
  11923. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  11924. }
  11925. newStandardMaterial.ambientColor = this.ambientColor.clone();
  11926. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  11927. newStandardMaterial.specularColor = this.specularColor.clone();
  11928. newStandardMaterial.specularPower = this.specularPower;
  11929. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  11930. return newStandardMaterial;
  11931. };
  11932. StandardMaterial.DiffuseTextureEnabled = true;
  11933. StandardMaterial.AmbientTextureEnabled = true;
  11934. StandardMaterial.OpacityTextureEnabled = true;
  11935. StandardMaterial.ReflectionTextureEnabled = true;
  11936. StandardMaterial.EmissiveTextureEnabled = true;
  11937. StandardMaterial.SpecularTextureEnabled = true;
  11938. StandardMaterial.BumpTextureEnabled = true;
  11939. return StandardMaterial;
  11940. })(BABYLON.Material);
  11941. BABYLON.StandardMaterial = StandardMaterial;
  11942. })(BABYLON || (BABYLON = {}));
  11943. var __extends = this.__extends || function (d, b) {
  11944. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11945. function __() { this.constructor = d; }
  11946. __.prototype = b.prototype;
  11947. d.prototype = new __();
  11948. };
  11949. var BABYLON;
  11950. (function (BABYLON) {
  11951. var MultiMaterial = (function (_super) {
  11952. __extends(MultiMaterial, _super);
  11953. function MultiMaterial(name, scene) {
  11954. _super.call(this, name, scene, true);
  11955. this.subMaterials = new Array();
  11956. scene.multiMaterials.push(this);
  11957. }
  11958. MultiMaterial.prototype.getSubMaterial = function (index) {
  11959. if (index < 0 || index >= this.subMaterials.length) {
  11960. return this.getScene().defaultMaterial;
  11961. }
  11962. return this.subMaterials[index];
  11963. };
  11964. MultiMaterial.prototype.isReady = function (mesh) {
  11965. for (var index = 0; index < this.subMaterials.length; index++) {
  11966. var subMaterial = this.subMaterials[index];
  11967. if (subMaterial) {
  11968. if (!this.subMaterials[index].isReady(mesh)) {
  11969. return false;
  11970. }
  11971. }
  11972. }
  11973. return true;
  11974. };
  11975. return MultiMaterial;
  11976. })(BABYLON.Material);
  11977. BABYLON.MultiMaterial = MultiMaterial;
  11978. })(BABYLON || (BABYLON = {}));
  11979. var BABYLON;
  11980. (function (BABYLON) {
  11981. var SceneLoader = (function () {
  11982. function SceneLoader() {
  11983. }
  11984. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  11985. get: function () {
  11986. return SceneLoader._ForceFullSceneLoadingForIncremental;
  11987. },
  11988. set: function (value) {
  11989. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  11990. },
  11991. enumerable: true,
  11992. configurable: true
  11993. });
  11994. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  11995. get: function () {
  11996. return SceneLoader._ShowLoadingScreen;
  11997. },
  11998. set: function (value) {
  11999. SceneLoader._ShowLoadingScreen = value;
  12000. },
  12001. enumerable: true,
  12002. configurable: true
  12003. });
  12004. SceneLoader._getPluginForFilename = function (sceneFilename) {
  12005. var dotPosition = sceneFilename.lastIndexOf(".");
  12006. var queryStringPosition = sceneFilename.indexOf("?");
  12007. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  12008. for (var index = 0; index < this._registeredPlugins.length; index++) {
  12009. var plugin = this._registeredPlugins[index];
  12010. if (plugin.extensions.indexOf(extension) !== -1) {
  12011. return plugin;
  12012. }
  12013. }
  12014. return this._registeredPlugins[this._registeredPlugins.length - 1];
  12015. };
  12016. SceneLoader.RegisterPlugin = function (plugin) {
  12017. plugin.extensions = plugin.extensions.toLowerCase();
  12018. SceneLoader._registeredPlugins.push(plugin);
  12019. };
  12020. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  12021. var _this = this;
  12022. var manifestChecked = function (success) {
  12023. scene.database = database;
  12024. var plugin = _this._getPluginForFilename(sceneFilename);
  12025. var importMeshFromData = function (data) {
  12026. var meshes = [];
  12027. var particleSystems = [];
  12028. var skeletons = [];
  12029. try {
  12030. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  12031. if (onerror) {
  12032. onerror(scene);
  12033. }
  12034. return;
  12035. }
  12036. } catch (e) {
  12037. if (onerror) {
  12038. onerror(scene);
  12039. }
  12040. return;
  12041. }
  12042. if (onsuccess) {
  12043. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  12044. onsuccess(meshes, particleSystems, skeletons);
  12045. }
  12046. };
  12047. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  12048. importMeshFromData(sceneFilename.substr(5));
  12049. return;
  12050. }
  12051. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  12052. importMeshFromData(data);
  12053. }, progressCallBack, database);
  12054. };
  12055. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  12056. };
  12057. /**
  12058. * Load a scene
  12059. * @param rootUrl a string that defines the root url for scene and resources
  12060. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  12061. * @param engine is the instance of BABYLON.Engine to use to create the scene
  12062. */
  12063. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  12064. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  12065. };
  12066. /**
  12067. * Append a scene
  12068. * @param rootUrl a string that defines the root url for scene and resources
  12069. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  12070. * @param scene is the instance of BABYLON.Scene to append to
  12071. */
  12072. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  12073. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  12074. var database;
  12075. if (SceneLoader.ShowLoadingScreen) {
  12076. scene.getEngine().displayLoadingUI();
  12077. }
  12078. var loadSceneFromData = function (data) {
  12079. scene.database = database;
  12080. if (!plugin.load(scene, data, rootUrl)) {
  12081. if (onerror) {
  12082. onerror(scene);
  12083. }
  12084. scene.getEngine().hideLoadingUI();
  12085. return;
  12086. }
  12087. if (onsuccess) {
  12088. onsuccess(scene);
  12089. }
  12090. if (SceneLoader.ShowLoadingScreen) {
  12091. scene.executeWhenReady(function () {
  12092. scene.getEngine().hideLoadingUI();
  12093. });
  12094. }
  12095. };
  12096. var manifestChecked = function (success) {
  12097. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  12098. };
  12099. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  12100. loadSceneFromData(sceneFilename.substr(5));
  12101. return;
  12102. }
  12103. if (rootUrl.indexOf("file:") === -1) {
  12104. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  12105. } else {
  12106. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  12107. }
  12108. };
  12109. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  12110. SceneLoader._ShowLoadingScreen = true;
  12111. SceneLoader._registeredPlugins = new Array();
  12112. return SceneLoader;
  12113. })();
  12114. BABYLON.SceneLoader = SceneLoader;
  12115. ;
  12116. })(BABYLON || (BABYLON = {}));
  12117. var BABYLON;
  12118. (function (BABYLON) {
  12119. (function (Internals) {
  12120. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  12121. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  12122. texture.name = parsedTexture.name;
  12123. texture.hasAlpha = parsedTexture.hasAlpha;
  12124. texture.level = parsedTexture.level;
  12125. texture.coordinatesMode = parsedTexture.coordinatesMode;
  12126. return texture;
  12127. };
  12128. var loadTexture = function (rootUrl, parsedTexture, scene) {
  12129. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  12130. return null;
  12131. }
  12132. if (parsedTexture.isCube) {
  12133. return loadCubeTexture(rootUrl, parsedTexture, scene);
  12134. }
  12135. var texture;
  12136. if (parsedTexture.mirrorPlane) {
  12137. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  12138. texture._waitingRenderList = parsedTexture.renderList;
  12139. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  12140. } else if (parsedTexture.isRenderTarget) {
  12141. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  12142. texture._waitingRenderList = parsedTexture.renderList;
  12143. } else {
  12144. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  12145. }
  12146. texture.name = parsedTexture.name;
  12147. texture.hasAlpha = parsedTexture.hasAlpha;
  12148. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  12149. texture.level = parsedTexture.level;
  12150. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  12151. texture.coordinatesMode = parsedTexture.coordinatesMode;
  12152. texture.uOffset = parsedTexture.uOffset;
  12153. texture.vOffset = parsedTexture.vOffset;
  12154. texture.uScale = parsedTexture.uScale;
  12155. texture.vScale = parsedTexture.vScale;
  12156. texture.uAng = parsedTexture.uAng;
  12157. texture.vAng = parsedTexture.vAng;
  12158. texture.wAng = parsedTexture.wAng;
  12159. texture.wrapU = parsedTexture.wrapU;
  12160. texture.wrapV = parsedTexture.wrapV;
  12161. if (parsedTexture.animations) {
  12162. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  12163. var parsedAnimation = parsedTexture.animations[animationIndex];
  12164. texture.animations.push(parseAnimation(parsedAnimation));
  12165. }
  12166. }
  12167. return texture;
  12168. };
  12169. var parseSkeleton = function (parsedSkeleton, scene) {
  12170. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  12171. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  12172. var parsedBone = parsedSkeleton.bones[index];
  12173. var parentBone = null;
  12174. if (parsedBone.parentBoneIndex > -1) {
  12175. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  12176. }
  12177. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  12178. if (parsedBone.animation) {
  12179. bone.animations.push(parseAnimation(parsedBone.animation));
  12180. }
  12181. }
  12182. return skeleton;
  12183. };
  12184. var parseFresnelParameters = function (parsedFresnelParameters) {
  12185. var fresnelParameters = new BABYLON.FresnelParameters();
  12186. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  12187. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  12188. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  12189. fresnelParameters.bias = parsedFresnelParameters.bias;
  12190. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  12191. return fresnelParameters;
  12192. };
  12193. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  12194. var material;
  12195. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  12196. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  12197. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  12198. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  12199. material.specularPower = parsedMaterial.specularPower;
  12200. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  12201. material.alpha = parsedMaterial.alpha;
  12202. material.id = parsedMaterial.id;
  12203. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  12204. material.backFaceCulling = parsedMaterial.backFaceCulling;
  12205. material.wireframe = parsedMaterial.wireframe;
  12206. if (parsedMaterial.diffuseTexture) {
  12207. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  12208. }
  12209. if (parsedMaterial.diffuseFresnelParameters) {
  12210. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  12211. }
  12212. if (parsedMaterial.ambientTexture) {
  12213. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  12214. }
  12215. if (parsedMaterial.opacityTexture) {
  12216. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  12217. }
  12218. if (parsedMaterial.opacityFresnelParameters) {
  12219. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  12220. }
  12221. if (parsedMaterial.reflectionTexture) {
  12222. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  12223. }
  12224. if (parsedMaterial.reflectionFresnelParameters) {
  12225. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  12226. }
  12227. if (parsedMaterial.emissiveTexture) {
  12228. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  12229. }
  12230. if (parsedMaterial.emissiveFresnelParameters) {
  12231. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  12232. }
  12233. if (parsedMaterial.specularTexture) {
  12234. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  12235. }
  12236. if (parsedMaterial.bumpTexture) {
  12237. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  12238. }
  12239. return material;
  12240. };
  12241. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  12242. for (var index = 0; index < parsedData.materials.length; index++) {
  12243. var parsedMaterial = parsedData.materials[index];
  12244. if (parsedMaterial.id === id) {
  12245. return parseMaterial(parsedMaterial, scene, rootUrl);
  12246. }
  12247. }
  12248. return null;
  12249. };
  12250. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  12251. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  12252. multiMaterial.id = parsedMultiMaterial.id;
  12253. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  12254. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  12255. var subMatId = parsedMultiMaterial.materials[matIndex];
  12256. if (subMatId) {
  12257. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  12258. } else {
  12259. multiMaterial.subMaterials.push(null);
  12260. }
  12261. }
  12262. return multiMaterial;
  12263. };
  12264. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  12265. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  12266. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  12267. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  12268. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  12269. var parsedFlare = parsedLensFlareSystem.flares[index];
  12270. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  12271. }
  12272. return lensFlareSystem;
  12273. };
  12274. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  12275. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  12276. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  12277. if (parsedParticleSystem.textureName) {
  12278. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  12279. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  12280. }
  12281. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  12282. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  12283. particleSystem.minSize = parsedParticleSystem.minSize;
  12284. particleSystem.maxSize = parsedParticleSystem.maxSize;
  12285. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  12286. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  12287. particleSystem.emitter = emitter;
  12288. particleSystem.emitRate = parsedParticleSystem.emitRate;
  12289. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  12290. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  12291. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  12292. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  12293. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  12294. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  12295. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  12296. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  12297. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  12298. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  12299. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  12300. particleSystem.blendMode = parsedParticleSystem.blendMode;
  12301. particleSystem.start();
  12302. return particleSystem;
  12303. };
  12304. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  12305. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  12306. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  12307. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  12308. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  12309. shadowGenerator.getShadowMap().renderList.push(mesh);
  12310. }
  12311. if (parsedShadowGenerator.usePoissonSampling) {
  12312. shadowGenerator.usePoissonSampling = true;
  12313. } else {
  12314. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  12315. }
  12316. return shadowGenerator;
  12317. };
  12318. var parseAnimation = function (parsedAnimation) {
  12319. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  12320. var dataType = parsedAnimation.dataType;
  12321. var keys = [];
  12322. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  12323. var key = parsedAnimation.keys[index];
  12324. var data;
  12325. switch (dataType) {
  12326. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  12327. data = key.values[0];
  12328. break;
  12329. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  12330. data = BABYLON.Quaternion.FromArray(key.values);
  12331. break;
  12332. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  12333. data = BABYLON.Matrix.FromArray(key.values);
  12334. break;
  12335. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  12336. default:
  12337. data = BABYLON.Vector3.FromArray(key.values);
  12338. break;
  12339. }
  12340. keys.push({
  12341. frame: key.frame,
  12342. value: data
  12343. });
  12344. }
  12345. animation.setKeys(keys);
  12346. return animation;
  12347. };
  12348. var parseLight = function (parsedLight, scene) {
  12349. var light;
  12350. switch (parsedLight.type) {
  12351. case 0:
  12352. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  12353. break;
  12354. case 1:
  12355. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  12356. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  12357. break;
  12358. case 2:
  12359. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  12360. break;
  12361. case 3:
  12362. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  12363. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  12364. break;
  12365. }
  12366. light.id = parsedLight.id;
  12367. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  12368. if (parsedLight.intensity !== undefined) {
  12369. light.intensity = parsedLight.intensity;
  12370. }
  12371. if (parsedLight.range) {
  12372. light.range = parsedLight.range;
  12373. }
  12374. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  12375. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  12376. if (parsedLight.excludedMeshesIds) {
  12377. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  12378. }
  12379. if (parsedLight.includedOnlyMeshesIds) {
  12380. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  12381. }
  12382. if (parsedLight.animations) {
  12383. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  12384. var parsedAnimation = parsedLight.animations[animationIndex];
  12385. light.animations.push(parseAnimation(parsedAnimation));
  12386. }
  12387. }
  12388. if (parsedLight.autoAnimate) {
  12389. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  12390. }
  12391. };
  12392. var parseCamera = function (parsedCamera, scene) {
  12393. var camera;
  12394. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  12395. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  12396. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  12397. var alpha = parsedCamera.alpha;
  12398. var beta = parsedCamera.beta;
  12399. var radius = parsedCamera.radius;
  12400. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  12401. var eye_space = parsedCamera.eye_space;
  12402. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  12403. } else {
  12404. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  12405. }
  12406. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  12407. var eye_space = parsedCamera.eye_space;
  12408. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  12409. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  12410. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  12411. } else if (parsedCamera.type === "FollowCamera") {
  12412. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  12413. camera.heightOffset = parsedCamera.heightOffset;
  12414. camera.radius = parsedCamera.radius;
  12415. camera.rotationOffset = parsedCamera.rotationOffset;
  12416. if (lockedTargetMesh)
  12417. camera.target = lockedTargetMesh;
  12418. } else if (parsedCamera.type === "GamepadCamera") {
  12419. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  12420. } else if (parsedCamera.type === "OculusCamera") {
  12421. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  12422. } else if (parsedCamera.type === "TouchCamera") {
  12423. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  12424. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  12425. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  12426. } else if (parsedCamera.type === "WebVRCamera") {
  12427. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  12428. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  12429. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  12430. } else {
  12431. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  12432. }
  12433. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  12434. camera.lockedTarget = lockedTargetMesh;
  12435. }
  12436. camera.id = parsedCamera.id;
  12437. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  12438. if (parsedCamera.parentId) {
  12439. camera._waitingParentId = parsedCamera.parentId;
  12440. }
  12441. if (parsedCamera.target) {
  12442. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  12443. } else {
  12444. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  12445. }
  12446. camera.fov = parsedCamera.fov;
  12447. camera.minZ = parsedCamera.minZ;
  12448. camera.maxZ = parsedCamera.maxZ;
  12449. camera.speed = parsedCamera.speed;
  12450. camera.inertia = parsedCamera.inertia;
  12451. camera.checkCollisions = parsedCamera.checkCollisions;
  12452. camera.applyGravity = parsedCamera.applyGravity;
  12453. if (parsedCamera.ellipsoid) {
  12454. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  12455. }
  12456. if (parsedCamera.animations) {
  12457. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  12458. var parsedAnimation = parsedCamera.animations[animationIndex];
  12459. camera.animations.push(parseAnimation(parsedAnimation));
  12460. }
  12461. }
  12462. if (parsedCamera.autoAnimate) {
  12463. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  12464. }
  12465. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  12466. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  12467. } else {
  12468. camera.layerMask = 0xFFFFFFFF;
  12469. }
  12470. return camera;
  12471. };
  12472. var parseGeometry = function (parsedGeometry, scene) {
  12473. var id = parsedGeometry.id;
  12474. return scene.getGeometryByID(id);
  12475. };
  12476. var parseBox = function (parsedBox, scene) {
  12477. if (parseGeometry(parsedBox, scene)) {
  12478. return null;
  12479. }
  12480. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  12481. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  12482. scene.pushGeometry(box, true);
  12483. return box;
  12484. };
  12485. var parseSphere = function (parsedSphere, scene) {
  12486. if (parseGeometry(parsedSphere, scene)) {
  12487. return null;
  12488. }
  12489. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  12490. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  12491. scene.pushGeometry(sphere, true);
  12492. return sphere;
  12493. };
  12494. var parseCylinder = function (parsedCylinder, scene) {
  12495. if (parseGeometry(parsedCylinder, scene)) {
  12496. return null;
  12497. }
  12498. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  12499. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  12500. scene.pushGeometry(cylinder, true);
  12501. return cylinder;
  12502. };
  12503. var parseTorus = function (parsedTorus, scene) {
  12504. if (parseGeometry(parsedTorus, scene)) {
  12505. return null;
  12506. }
  12507. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  12508. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  12509. scene.pushGeometry(torus, true);
  12510. return torus;
  12511. };
  12512. var parseGround = function (parsedGround, scene) {
  12513. if (parseGeometry(parsedGround, scene)) {
  12514. return null;
  12515. }
  12516. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  12517. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  12518. scene.pushGeometry(ground, true);
  12519. return ground;
  12520. };
  12521. var parsePlane = function (parsedPlane, scene) {
  12522. if (parseGeometry(parsedPlane, scene)) {
  12523. return null;
  12524. }
  12525. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  12526. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  12527. scene.pushGeometry(plane, true);
  12528. return plane;
  12529. };
  12530. var parseTorusKnot = function (parsedTorusKnot, scene) {
  12531. if (parseGeometry(parsedTorusKnot, scene)) {
  12532. return null;
  12533. }
  12534. 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);
  12535. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  12536. scene.pushGeometry(torusKnot, true);
  12537. return torusKnot;
  12538. };
  12539. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  12540. if (parseGeometry(parsedVertexData, scene)) {
  12541. return null;
  12542. }
  12543. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  12544. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  12545. if (parsedVertexData.delayLoadingFile) {
  12546. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12547. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  12548. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  12549. geometry._delayInfo = [];
  12550. if (parsedVertexData.hasUVs) {
  12551. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  12552. }
  12553. if (parsedVertexData.hasUVs2) {
  12554. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  12555. }
  12556. if (parsedVertexData.hasColors) {
  12557. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  12558. }
  12559. if (parsedVertexData.hasMatricesIndices) {
  12560. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12561. }
  12562. if (parsedVertexData.hasMatricesWeights) {
  12563. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12564. }
  12565. geometry._delayLoadingFunction = importVertexData;
  12566. } else {
  12567. importVertexData(parsedVertexData, geometry);
  12568. }
  12569. scene.pushGeometry(geometry, true);
  12570. return geometry;
  12571. };
  12572. var parseMesh = function (parsedMesh, scene, rootUrl) {
  12573. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  12574. mesh.id = parsedMesh.id;
  12575. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  12576. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  12577. if (parsedMesh.rotationQuaternion) {
  12578. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  12579. } else if (parsedMesh.rotation) {
  12580. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  12581. }
  12582. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  12583. if (parsedMesh.localMatrix) {
  12584. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  12585. } else if (parsedMesh.pivotMatrix) {
  12586. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  12587. }
  12588. mesh.setEnabled(parsedMesh.isEnabled);
  12589. mesh.isVisible = parsedMesh.isVisible;
  12590. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  12591. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  12592. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  12593. if (parsedMesh.pickable !== undefined) {
  12594. mesh.isPickable = parsedMesh.pickable;
  12595. }
  12596. mesh.receiveShadows = parsedMesh.receiveShadows;
  12597. mesh.billboardMode = parsedMesh.billboardMode;
  12598. if (parsedMesh.visibility !== undefined) {
  12599. mesh.visibility = parsedMesh.visibility;
  12600. }
  12601. mesh.checkCollisions = parsedMesh.checkCollisions;
  12602. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  12603. if (parsedMesh.parentId) {
  12604. mesh._waitingParentId = parsedMesh.parentId;
  12605. }
  12606. if (parsedMesh.delayLoadingFile) {
  12607. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12608. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  12609. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  12610. if (parsedMesh._binaryInfo) {
  12611. mesh._binaryInfo = parsedMesh._binaryInfo;
  12612. }
  12613. mesh._delayInfo = [];
  12614. if (parsedMesh.hasUVs) {
  12615. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  12616. }
  12617. if (parsedMesh.hasUVs2) {
  12618. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  12619. }
  12620. if (parsedMesh.hasColors) {
  12621. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  12622. }
  12623. if (parsedMesh.hasMatricesIndices) {
  12624. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12625. }
  12626. if (parsedMesh.hasMatricesWeights) {
  12627. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12628. }
  12629. mesh._delayLoadingFunction = importGeometry;
  12630. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  12631. mesh._checkDelayState();
  12632. }
  12633. } else {
  12634. importGeometry(parsedMesh, mesh);
  12635. }
  12636. if (parsedMesh.materialId) {
  12637. mesh.setMaterialByID(parsedMesh.materialId);
  12638. } else {
  12639. mesh.material = null;
  12640. }
  12641. if (parsedMesh.skeletonId > -1) {
  12642. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  12643. }
  12644. if (parsedMesh.physicsImpostor) {
  12645. if (!scene.isPhysicsEnabled()) {
  12646. scene.enablePhysics();
  12647. }
  12648. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  12649. }
  12650. if (parsedMesh.animations) {
  12651. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  12652. var parsedAnimation = parsedMesh.animations[animationIndex];
  12653. mesh.animations.push(parseAnimation(parsedAnimation));
  12654. }
  12655. }
  12656. if (parsedMesh.autoAnimate) {
  12657. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  12658. }
  12659. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  12660. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  12661. } else {
  12662. mesh.layerMask = 0xFFFFFFFF;
  12663. }
  12664. if (parsedMesh.instances) {
  12665. for (var index = 0; index < parsedMesh.instances.length; index++) {
  12666. var parsedInstance = parsedMesh.instances[index];
  12667. var instance = mesh.createInstance(parsedInstance.name);
  12668. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  12669. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  12670. if (parsedInstance.rotationQuaternion) {
  12671. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  12672. } else if (parsedInstance.rotation) {
  12673. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  12674. }
  12675. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  12676. instance.checkCollisions = mesh.checkCollisions;
  12677. if (parsedMesh.animations) {
  12678. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  12679. parsedAnimation = parsedMesh.animations[animationIndex];
  12680. instance.animations.push(parseAnimation(parsedAnimation));
  12681. }
  12682. }
  12683. }
  12684. }
  12685. return mesh;
  12686. };
  12687. var isDescendantOf = function (mesh, names, hierarchyIds) {
  12688. names = (names instanceof Array) ? names : [names];
  12689. for (var i in names) {
  12690. if (mesh.name === names[i]) {
  12691. hierarchyIds.push(mesh.id);
  12692. return true;
  12693. }
  12694. }
  12695. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  12696. hierarchyIds.push(mesh.id);
  12697. return true;
  12698. }
  12699. return false;
  12700. };
  12701. var importVertexData = function (parsedVertexData, geometry) {
  12702. var vertexData = new BABYLON.VertexData();
  12703. var positions = parsedVertexData.positions;
  12704. if (positions) {
  12705. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  12706. }
  12707. var normals = parsedVertexData.normals;
  12708. if (normals) {
  12709. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  12710. }
  12711. var uvs = parsedVertexData.uvs;
  12712. if (uvs) {
  12713. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  12714. }
  12715. var uv2s = parsedVertexData.uv2s;
  12716. if (uv2s) {
  12717. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  12718. }
  12719. var colors = parsedVertexData.colors;
  12720. if (colors) {
  12721. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  12722. }
  12723. var matricesIndices = parsedVertexData.matricesIndices;
  12724. if (matricesIndices) {
  12725. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  12726. }
  12727. var matricesWeights = parsedVertexData.matricesWeights;
  12728. if (matricesWeights) {
  12729. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  12730. }
  12731. var indices = parsedVertexData.indices;
  12732. if (indices) {
  12733. vertexData.indices = indices;
  12734. }
  12735. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  12736. };
  12737. var importGeometry = function (parsedGeometry, mesh) {
  12738. var scene = mesh.getScene();
  12739. var geometryId = parsedGeometry.geometryId;
  12740. if (geometryId) {
  12741. var geometry = scene.getGeometryByID(geometryId);
  12742. if (geometry) {
  12743. geometry.applyToMesh(mesh);
  12744. }
  12745. } else if (parsedGeometry instanceof ArrayBuffer) {
  12746. var binaryInfo = mesh._binaryInfo;
  12747. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  12748. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  12749. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  12750. }
  12751. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  12752. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  12753. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  12754. }
  12755. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  12756. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  12757. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  12758. }
  12759. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  12760. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  12761. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  12762. }
  12763. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  12764. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  12765. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  12766. }
  12767. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  12768. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  12769. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  12770. }
  12771. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  12772. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  12773. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  12774. }
  12775. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  12776. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  12777. mesh.setIndices(indicesData);
  12778. }
  12779. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  12780. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  12781. mesh.subMeshes = [];
  12782. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  12783. var materialIndex = subMeshesData[(i * 5) + 0];
  12784. var verticesStart = subMeshesData[(i * 5) + 1];
  12785. var verticesCount = subMeshesData[(i * 5) + 2];
  12786. var indexStart = subMeshesData[(i * 5) + 3];
  12787. var indexCount = subMeshesData[(i * 5) + 4];
  12788. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  12789. }
  12790. }
  12791. return;
  12792. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  12793. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  12794. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  12795. if (parsedGeometry.uvs) {
  12796. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  12797. }
  12798. if (parsedGeometry.uvs2) {
  12799. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  12800. }
  12801. if (parsedGeometry.colors) {
  12802. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  12803. }
  12804. if (parsedGeometry.matricesIndices) {
  12805. if (!parsedGeometry.matricesIndices._isExpanded) {
  12806. var floatIndices = [];
  12807. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  12808. var matricesIndex = parsedGeometry.matricesIndices[i];
  12809. floatIndices.push(matricesIndex & 0x000000FF);
  12810. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  12811. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  12812. floatIndices.push(matricesIndex >> 24);
  12813. }
  12814. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  12815. } else {
  12816. delete parsedGeometry.matricesIndices._isExpanded;
  12817. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  12818. }
  12819. }
  12820. if (parsedGeometry.matricesWeights) {
  12821. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  12822. }
  12823. mesh.setIndices(parsedGeometry.indices);
  12824. }
  12825. if (parsedGeometry.subMeshes) {
  12826. mesh.subMeshes = [];
  12827. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  12828. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  12829. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  12830. }
  12831. }
  12832. if (mesh._shouldGenerateFlatShading) {
  12833. mesh.convertToFlatShadedMesh();
  12834. delete mesh._shouldGenerateFlatShading;
  12835. }
  12836. mesh.computeWorldMatrix(true);
  12837. if (scene._selectionOctree) {
  12838. scene._selectionOctree.addMesh(mesh);
  12839. }
  12840. };
  12841. BABYLON.SceneLoader.RegisterPlugin({
  12842. extensions: ".babylon",
  12843. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  12844. var parsedData = JSON.parse(data);
  12845. var loadedSkeletonsIds = [];
  12846. var loadedMaterialsIds = [];
  12847. var hierarchyIds = [];
  12848. for (var index = 0; index < parsedData.meshes.length; index++) {
  12849. var parsedMesh = parsedData.meshes[index];
  12850. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  12851. if (meshesNames instanceof Array) {
  12852. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  12853. }
  12854. if (parsedMesh.materialId) {
  12855. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  12856. if (!materialFound) {
  12857. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  12858. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  12859. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  12860. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  12861. var subMatId = parsedMultiMaterial.materials[matIndex];
  12862. loadedMaterialsIds.push(subMatId);
  12863. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  12864. }
  12865. loadedMaterialsIds.push(parsedMultiMaterial.id);
  12866. parseMultiMaterial(parsedMultiMaterial, scene);
  12867. materialFound = true;
  12868. break;
  12869. }
  12870. }
  12871. }
  12872. if (!materialFound) {
  12873. loadedMaterialsIds.push(parsedMesh.materialId);
  12874. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  12875. }
  12876. }
  12877. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  12878. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  12879. if (!skeletonAlreadyLoaded) {
  12880. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  12881. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  12882. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  12883. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  12884. loadedSkeletonsIds.push(parsedSkeleton.id);
  12885. }
  12886. }
  12887. }
  12888. }
  12889. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  12890. meshes.push(mesh);
  12891. }
  12892. }
  12893. for (index = 0; index < scene.meshes.length; index++) {
  12894. var currentMesh = scene.meshes[index];
  12895. if (currentMesh._waitingParentId) {
  12896. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  12897. currentMesh._waitingParentId = undefined;
  12898. }
  12899. }
  12900. if (parsedData.particleSystems) {
  12901. for (index = 0; index < parsedData.particleSystems.length; index++) {
  12902. var parsedParticleSystem = parsedData.particleSystems[index];
  12903. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  12904. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  12905. }
  12906. }
  12907. }
  12908. return true;
  12909. },
  12910. load: function (scene, data, rootUrl) {
  12911. var parsedData = JSON.parse(data);
  12912. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  12913. scene.autoClear = parsedData.autoClear;
  12914. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  12915. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  12916. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  12917. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  12918. scene.fogMode = parsedData.fogMode;
  12919. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  12920. scene.fogStart = parsedData.fogStart;
  12921. scene.fogEnd = parsedData.fogEnd;
  12922. scene.fogDensity = parsedData.fogDensity;
  12923. }
  12924. for (var index = 0; index < parsedData.lights.length; index++) {
  12925. var parsedLight = parsedData.lights[index];
  12926. parseLight(parsedLight, scene);
  12927. }
  12928. if (parsedData.materials) {
  12929. for (index = 0; index < parsedData.materials.length; index++) {
  12930. var parsedMaterial = parsedData.materials[index];
  12931. parseMaterial(parsedMaterial, scene, rootUrl);
  12932. }
  12933. }
  12934. if (parsedData.multiMaterials) {
  12935. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  12936. var parsedMultiMaterial = parsedData.multiMaterials[index];
  12937. parseMultiMaterial(parsedMultiMaterial, scene);
  12938. }
  12939. }
  12940. if (parsedData.skeletons) {
  12941. for (index = 0; index < parsedData.skeletons.length; index++) {
  12942. var parsedSkeleton = parsedData.skeletons[index];
  12943. parseSkeleton(parsedSkeleton, scene);
  12944. }
  12945. }
  12946. var geometries = parsedData.geometries;
  12947. if (geometries) {
  12948. var boxes = geometries.boxes;
  12949. if (boxes) {
  12950. for (index = 0; index < boxes.length; index++) {
  12951. var parsedBox = boxes[index];
  12952. parseBox(parsedBox, scene);
  12953. }
  12954. }
  12955. var spheres = geometries.spheres;
  12956. if (spheres) {
  12957. for (index = 0; index < spheres.length; index++) {
  12958. var parsedSphere = spheres[index];
  12959. parseSphere(parsedSphere, scene);
  12960. }
  12961. }
  12962. var cylinders = geometries.cylinders;
  12963. if (cylinders) {
  12964. for (index = 0; index < cylinders.length; index++) {
  12965. var parsedCylinder = cylinders[index];
  12966. parseCylinder(parsedCylinder, scene);
  12967. }
  12968. }
  12969. var toruses = geometries.toruses;
  12970. if (toruses) {
  12971. for (index = 0; index < toruses.length; index++) {
  12972. var parsedTorus = toruses[index];
  12973. parseTorus(parsedTorus, scene);
  12974. }
  12975. }
  12976. var grounds = geometries.grounds;
  12977. if (grounds) {
  12978. for (index = 0; index < grounds.length; index++) {
  12979. var parsedGround = grounds[index];
  12980. parseGround(parsedGround, scene);
  12981. }
  12982. }
  12983. var planes = geometries.planes;
  12984. if (planes) {
  12985. for (index = 0; index < planes.length; index++) {
  12986. var parsedPlane = planes[index];
  12987. parsePlane(parsedPlane, scene);
  12988. }
  12989. }
  12990. var torusKnots = geometries.torusKnots;
  12991. if (torusKnots) {
  12992. for (index = 0; index < torusKnots.length; index++) {
  12993. var parsedTorusKnot = torusKnots[index];
  12994. parseTorusKnot(parsedTorusKnot, scene);
  12995. }
  12996. }
  12997. var vertexData = geometries.vertexData;
  12998. if (vertexData) {
  12999. for (index = 0; index < vertexData.length; index++) {
  13000. var parsedVertexData = vertexData[index];
  13001. parseVertexData(parsedVertexData, scene, rootUrl);
  13002. }
  13003. }
  13004. }
  13005. for (index = 0; index < parsedData.meshes.length; index++) {
  13006. var parsedMesh = parsedData.meshes[index];
  13007. parseMesh(parsedMesh, scene, rootUrl);
  13008. }
  13009. for (index = 0; index < parsedData.cameras.length; index++) {
  13010. var parsedCamera = parsedData.cameras[index];
  13011. parseCamera(parsedCamera, scene);
  13012. }
  13013. if (parsedData.activeCameraID) {
  13014. scene.setActiveCameraByID(parsedData.activeCameraID);
  13015. }
  13016. for (index = 0; index < scene.cameras.length; index++) {
  13017. var camera = scene.cameras[index];
  13018. if (camera._waitingParentId) {
  13019. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  13020. camera._waitingParentId = undefined;
  13021. }
  13022. }
  13023. for (index = 0; index < scene.meshes.length; index++) {
  13024. var mesh = scene.meshes[index];
  13025. if (mesh._waitingParentId) {
  13026. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  13027. mesh._waitingParentId = undefined;
  13028. }
  13029. }
  13030. if (parsedData.particleSystems) {
  13031. for (index = 0; index < parsedData.particleSystems.length; index++) {
  13032. var parsedParticleSystem = parsedData.particleSystems[index];
  13033. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  13034. }
  13035. }
  13036. if (parsedData.lensFlareSystems) {
  13037. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  13038. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  13039. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  13040. }
  13041. }
  13042. if (parsedData.shadowGenerators) {
  13043. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  13044. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  13045. parseShadowGenerator(parsedShadowGenerator, scene);
  13046. }
  13047. }
  13048. return true;
  13049. }
  13050. });
  13051. })(BABYLON.Internals || (BABYLON.Internals = {}));
  13052. var Internals = BABYLON.Internals;
  13053. })(BABYLON || (BABYLON = {}));
  13054. var BABYLON;
  13055. (function (BABYLON) {
  13056. var SpriteManager = (function () {
  13057. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  13058. this.name = name;
  13059. this.cellSize = cellSize;
  13060. this.sprites = new Array();
  13061. this.renderingGroupId = 0;
  13062. this._vertexDeclaration = [3, 4, 4, 4];
  13063. this._vertexStrideSize = 15 * 4;
  13064. this._capacity = capacity;
  13065. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  13066. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13067. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13068. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  13069. this._scene = scene;
  13070. this._scene.spriteManagers.push(this);
  13071. this._vertexDeclaration = [3, 4, 4, 4];
  13072. this._vertexStrideSize = 15 * 4;
  13073. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13074. var indices = [];
  13075. var index = 0;
  13076. for (var count = 0; count < capacity; count++) {
  13077. indices.push(index);
  13078. indices.push(index + 1);
  13079. indices.push(index + 2);
  13080. indices.push(index);
  13081. indices.push(index + 2);
  13082. indices.push(index + 3);
  13083. index += 4;
  13084. }
  13085. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13086. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13087. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  13088. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  13089. }
  13090. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  13091. var arrayOffset = index * 15;
  13092. if (offsetX == 0)
  13093. offsetX = this._epsilon;
  13094. else if (offsetX == 1)
  13095. offsetX = 1 - this._epsilon;
  13096. if (offsetY == 0)
  13097. offsetY = this._epsilon;
  13098. else if (offsetY == 1)
  13099. offsetY = 1 - this._epsilon;
  13100. this._vertices[arrayOffset] = sprite.position.x;
  13101. this._vertices[arrayOffset + 1] = sprite.position.y;
  13102. this._vertices[arrayOffset + 2] = sprite.position.z;
  13103. this._vertices[arrayOffset + 3] = sprite.angle;
  13104. this._vertices[arrayOffset + 4] = sprite.size;
  13105. this._vertices[arrayOffset + 5] = offsetX;
  13106. this._vertices[arrayOffset + 6] = offsetY;
  13107. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  13108. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  13109. var offset = (sprite.cellIndex / rowSize) >> 0;
  13110. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  13111. this._vertices[arrayOffset + 10] = offset;
  13112. this._vertices[arrayOffset + 11] = sprite.color.r;
  13113. this._vertices[arrayOffset + 12] = sprite.color.g;
  13114. this._vertices[arrayOffset + 13] = sprite.color.b;
  13115. this._vertices[arrayOffset + 14] = sprite.color.a;
  13116. };
  13117. SpriteManager.prototype.render = function () {
  13118. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  13119. return;
  13120. var engine = this._scene.getEngine();
  13121. var baseSize = this._spriteTexture.getBaseSize();
  13122. var deltaTime = BABYLON.Tools.GetDeltaTime();
  13123. var max = Math.min(this._capacity, this.sprites.length);
  13124. var rowSize = baseSize.width / this.cellSize;
  13125. var offset = 0;
  13126. for (var index = 0; index < max; index++) {
  13127. var sprite = this.sprites[index];
  13128. if (!sprite) {
  13129. continue;
  13130. }
  13131. sprite._animate(deltaTime);
  13132. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  13133. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  13134. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  13135. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  13136. }
  13137. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  13138. var effect = this._effectBase;
  13139. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13140. effect = this._effectFog;
  13141. }
  13142. engine.enableEffect(effect);
  13143. var viewMatrix = this._scene.getViewMatrix();
  13144. effect.setTexture("diffuseSampler", this._spriteTexture);
  13145. effect.setMatrix("view", viewMatrix);
  13146. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  13147. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  13148. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13149. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  13150. effect.setColor3("vFogColor", this._scene.fogColor);
  13151. }
  13152. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13153. effect.setBool("alphaTest", true);
  13154. engine.setColorWrite(false);
  13155. engine.draw(WebGLRenderingContext.TRIANGLES, 0, max * 6);
  13156. engine.setColorWrite(true);
  13157. effect.setBool("alphaTest", false);
  13158. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13159. engine.draw(WebGLRenderingContext.TRIANGLES, 0, max * 6);
  13160. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13161. };
  13162. SpriteManager.prototype.dispose = function () {
  13163. if (this._vertexBuffer) {
  13164. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13165. this._vertexBuffer = null;
  13166. }
  13167. if (this._indexBuffer) {
  13168. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13169. this._indexBuffer = null;
  13170. }
  13171. if (this._spriteTexture) {
  13172. this._spriteTexture.dispose();
  13173. this._spriteTexture = null;
  13174. }
  13175. var index = this._scene.spriteManagers.indexOf(this);
  13176. this._scene.spriteManagers.splice(index, 1);
  13177. if (this.onDispose) {
  13178. this.onDispose();
  13179. }
  13180. };
  13181. return SpriteManager;
  13182. })();
  13183. BABYLON.SpriteManager = SpriteManager;
  13184. })(BABYLON || (BABYLON = {}));
  13185. var BABYLON;
  13186. (function (BABYLON) {
  13187. var Sprite = (function () {
  13188. function Sprite(name, manager) {
  13189. this.name = name;
  13190. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13191. this.size = 1.0;
  13192. this.angle = 0;
  13193. this.cellIndex = 0;
  13194. this.invertU = 0;
  13195. this.invertV = 0;
  13196. this.animations = new Array();
  13197. this._animationStarted = false;
  13198. this._loopAnimation = false;
  13199. this._fromIndex = 0;
  13200. this._toIndex = 0;
  13201. this._delay = 0;
  13202. this._direction = 1;
  13203. this._frameCount = 0;
  13204. this._time = 0;
  13205. this._manager = manager;
  13206. this._manager.sprites.push(this);
  13207. this.position = BABYLON.Vector3.Zero();
  13208. }
  13209. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  13210. this._fromIndex = from;
  13211. this._toIndex = to;
  13212. this._loopAnimation = loop;
  13213. this._delay = delay;
  13214. this._animationStarted = true;
  13215. this._direction = from < to ? 1 : -1;
  13216. this.cellIndex = from;
  13217. this._time = 0;
  13218. };
  13219. Sprite.prototype.stopAnimation = function () {
  13220. this._animationStarted = false;
  13221. };
  13222. Sprite.prototype._animate = function (deltaTime) {
  13223. if (!this._animationStarted)
  13224. return;
  13225. this._time += deltaTime;
  13226. if (this._time > this._delay) {
  13227. this._time = this._time % this._delay;
  13228. this.cellIndex += this._direction;
  13229. if (this.cellIndex == this._toIndex) {
  13230. if (this._loopAnimation) {
  13231. this.cellIndex = this._fromIndex;
  13232. } else {
  13233. this._animationStarted = false;
  13234. if (this.disposeWhenFinishedAnimating) {
  13235. this.dispose();
  13236. }
  13237. }
  13238. }
  13239. }
  13240. };
  13241. Sprite.prototype.dispose = function () {
  13242. for (var i = 0; i < this._manager.sprites.length; i++) {
  13243. if (this._manager.sprites[i] == this) {
  13244. this._manager.sprites.splice(i, 1);
  13245. }
  13246. }
  13247. };
  13248. return Sprite;
  13249. })();
  13250. BABYLON.Sprite = Sprite;
  13251. })(BABYLON || (BABYLON = {}));
  13252. var BABYLON;
  13253. (function (BABYLON) {
  13254. var Layer = (function () {
  13255. function Layer(name, imgUrl, scene, isBackground, color) {
  13256. this.name = name;
  13257. this._vertexDeclaration = [2];
  13258. this._vertexStrideSize = 2 * 4;
  13259. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  13260. this.isBackground = isBackground === undefined ? true : isBackground;
  13261. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  13262. this._scene = scene;
  13263. this._scene.layers.push(this);
  13264. var vertices = [];
  13265. vertices.push(1, 1);
  13266. vertices.push(-1, 1);
  13267. vertices.push(-1, -1);
  13268. vertices.push(1, -1);
  13269. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13270. var indices = [];
  13271. indices.push(0);
  13272. indices.push(1);
  13273. indices.push(2);
  13274. indices.push(0);
  13275. indices.push(2);
  13276. indices.push(3);
  13277. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13278. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  13279. }
  13280. Layer.prototype.render = function () {
  13281. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  13282. return;
  13283. var engine = this._scene.getEngine();
  13284. engine.enableEffect(this._effect);
  13285. engine.setState(false);
  13286. this._effect.setTexture("textureSampler", this.texture);
  13287. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  13288. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  13289. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13290. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13291. engine.draw(WebGLRenderingContext.TRIANGLES, 0, 6);
  13292. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13293. };
  13294. Layer.prototype.dispose = function () {
  13295. if (this._vertexBuffer) {
  13296. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13297. this._vertexBuffer = null;
  13298. }
  13299. if (this._indexBuffer) {
  13300. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13301. this._indexBuffer = null;
  13302. }
  13303. if (this.texture) {
  13304. this.texture.dispose();
  13305. this.texture = null;
  13306. }
  13307. var index = this._scene.layers.indexOf(this);
  13308. this._scene.layers.splice(index, 1);
  13309. if (this.onDispose) {
  13310. this.onDispose();
  13311. }
  13312. };
  13313. return Layer;
  13314. })();
  13315. BABYLON.Layer = Layer;
  13316. })(BABYLON || (BABYLON = {}));
  13317. var BABYLON;
  13318. (function (BABYLON) {
  13319. var Particle = (function () {
  13320. function Particle() {
  13321. this.position = BABYLON.Vector3.Zero();
  13322. this.direction = BABYLON.Vector3.Zero();
  13323. this.color = new BABYLON.Color4(0, 0, 0, 0);
  13324. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  13325. this.lifeTime = 1.0;
  13326. this.age = 0;
  13327. this.size = 0;
  13328. this.angle = 0;
  13329. this.angularSpeed = 0;
  13330. }
  13331. return Particle;
  13332. })();
  13333. BABYLON.Particle = Particle;
  13334. })(BABYLON || (BABYLON = {}));
  13335. var BABYLON;
  13336. (function (BABYLON) {
  13337. var randomNumber = function (min, max) {
  13338. if (min == max) {
  13339. return (min);
  13340. }
  13341. var random = Math.random();
  13342. return ((random * (max - min)) + min);
  13343. };
  13344. var ParticleSystem = (function () {
  13345. function ParticleSystem(name, capacity, scene, customEffect) {
  13346. var _this = this;
  13347. this.name = name;
  13348. this.renderingGroupId = 0;
  13349. this.emitter = null;
  13350. this.emitRate = 10;
  13351. this.manualEmitCount = -1;
  13352. this.updateSpeed = 0.01;
  13353. this.targetStopDuration = 0;
  13354. this.disposeOnStop = false;
  13355. this.minEmitPower = 1;
  13356. this.maxEmitPower = 1;
  13357. this.minLifeTime = 1;
  13358. this.maxLifeTime = 1;
  13359. this.minSize = 1;
  13360. this.maxSize = 1;
  13361. this.minAngularSpeed = 0;
  13362. this.maxAngularSpeed = 0;
  13363. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  13364. this.forceDepthWrite = false;
  13365. this.gravity = BABYLON.Vector3.Zero();
  13366. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  13367. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  13368. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  13369. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13370. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13371. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13372. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  13373. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13374. this.particles = new Array();
  13375. this._vertexDeclaration = [3, 4, 4];
  13376. this._vertexStrideSize = 11 * 4;
  13377. this._stockParticles = new Array();
  13378. this._newPartsExcess = 0;
  13379. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  13380. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  13381. this._scaledDirection = BABYLON.Vector3.Zero();
  13382. this._scaledGravity = BABYLON.Vector3.Zero();
  13383. this._currentRenderId = -1;
  13384. this._started = false;
  13385. this._stopped = false;
  13386. this._actualFrame = 0;
  13387. this.id = name;
  13388. this._capacity = capacity;
  13389. this._scene = scene;
  13390. this._customEffect = customEffect;
  13391. scene.particleSystems.push(this);
  13392. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13393. var indices = [];
  13394. var index = 0;
  13395. for (var count = 0; count < capacity; count++) {
  13396. indices.push(index);
  13397. indices.push(index + 1);
  13398. indices.push(index + 2);
  13399. indices.push(index);
  13400. indices.push(index + 2);
  13401. indices.push(index + 3);
  13402. index += 4;
  13403. }
  13404. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13405. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13406. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  13407. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  13408. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  13409. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  13410. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  13411. };
  13412. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  13413. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  13414. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  13415. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  13416. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  13417. };
  13418. }
  13419. ParticleSystem.prototype.getCapacity = function () {
  13420. return this._capacity;
  13421. };
  13422. ParticleSystem.prototype.isAlive = function () {
  13423. return this._alive;
  13424. };
  13425. ParticleSystem.prototype.isStarted = function () {
  13426. return this._started;
  13427. };
  13428. ParticleSystem.prototype.start = function () {
  13429. this._started = true;
  13430. this._stopped = false;
  13431. this._actualFrame = 0;
  13432. };
  13433. ParticleSystem.prototype.stop = function () {
  13434. this._stopped = true;
  13435. };
  13436. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  13437. var offset = index * 11;
  13438. this._vertices[offset] = particle.position.x;
  13439. this._vertices[offset + 1] = particle.position.y;
  13440. this._vertices[offset + 2] = particle.position.z;
  13441. this._vertices[offset + 3] = particle.color.r;
  13442. this._vertices[offset + 4] = particle.color.g;
  13443. this._vertices[offset + 5] = particle.color.b;
  13444. this._vertices[offset + 6] = particle.color.a;
  13445. this._vertices[offset + 7] = particle.angle;
  13446. this._vertices[offset + 8] = particle.size;
  13447. this._vertices[offset + 9] = offsetX;
  13448. this._vertices[offset + 10] = offsetY;
  13449. };
  13450. ParticleSystem.prototype._update = function (newParticles) {
  13451. this._alive = this.particles.length > 0;
  13452. for (var index = 0; index < this.particles.length; index++) {
  13453. var particle = this.particles[index];
  13454. particle.age += this._scaledUpdateSpeed;
  13455. if (particle.age >= particle.lifeTime) {
  13456. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  13457. index--;
  13458. continue;
  13459. } else {
  13460. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  13461. particle.color.addInPlace(this._scaledColorStep);
  13462. if (particle.color.a < 0)
  13463. particle.color.a = 0;
  13464. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  13465. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  13466. particle.position.addInPlace(this._scaledDirection);
  13467. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  13468. particle.direction.addInPlace(this._scaledGravity);
  13469. }
  13470. }
  13471. var worldMatrix;
  13472. if (this.emitter.position) {
  13473. worldMatrix = this.emitter.getWorldMatrix();
  13474. } else {
  13475. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  13476. }
  13477. for (index = 0; index < newParticles; index++) {
  13478. if (this.particles.length == this._capacity) {
  13479. break;
  13480. }
  13481. if (this._stockParticles.length !== 0) {
  13482. particle = this._stockParticles.pop();
  13483. particle.age = 0;
  13484. } else {
  13485. particle = new BABYLON.Particle();
  13486. }
  13487. this.particles.push(particle);
  13488. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  13489. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  13490. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  13491. particle.size = randomNumber(this.minSize, this.maxSize);
  13492. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  13493. this.startPositionFunction(worldMatrix, particle.position);
  13494. var step = randomNumber(0, 1.0);
  13495. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  13496. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  13497. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  13498. }
  13499. };
  13500. ParticleSystem.prototype._getEffect = function () {
  13501. if (this._customEffect) {
  13502. return this._customEffect;
  13503. }
  13504. ;
  13505. var defines = [];
  13506. if (this._scene.clipPlane) {
  13507. defines.push("#define CLIPPLANE");
  13508. }
  13509. var join = defines.join("\n");
  13510. if (this._cachedDefines != join) {
  13511. this._cachedDefines = join;
  13512. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  13513. }
  13514. return this._effect;
  13515. };
  13516. ParticleSystem.prototype.animate = function () {
  13517. if (!this._started)
  13518. return;
  13519. var effect = this._getEffect();
  13520. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  13521. return;
  13522. if (this._currentRenderId === this._scene.getRenderId()) {
  13523. return;
  13524. }
  13525. this._currentRenderId = this._scene.getRenderId();
  13526. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  13527. var emitCout;
  13528. if (this.manualEmitCount > -1) {
  13529. emitCout = this.manualEmitCount;
  13530. this.manualEmitCount = 0;
  13531. } else {
  13532. emitCout = this.emitRate;
  13533. }
  13534. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  13535. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  13536. if (this._newPartsExcess > 1.0) {
  13537. newParticles += this._newPartsExcess >> 0;
  13538. this._newPartsExcess -= this._newPartsExcess >> 0;
  13539. }
  13540. this._alive = false;
  13541. if (!this._stopped) {
  13542. this._actualFrame += this._scaledUpdateSpeed;
  13543. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  13544. this.stop();
  13545. } else {
  13546. newParticles = 0;
  13547. }
  13548. this._update(newParticles);
  13549. if (this._stopped) {
  13550. if (!this._alive) {
  13551. this._started = false;
  13552. if (this.disposeOnStop) {
  13553. this._scene._toBeDisposed.push(this);
  13554. }
  13555. }
  13556. }
  13557. var offset = 0;
  13558. for (var index = 0; index < this.particles.length; index++) {
  13559. var particle = this.particles[index];
  13560. this._appendParticleVertex(offset++, particle, 0, 0);
  13561. this._appendParticleVertex(offset++, particle, 1, 0);
  13562. this._appendParticleVertex(offset++, particle, 1, 1);
  13563. this._appendParticleVertex(offset++, particle, 0, 1);
  13564. }
  13565. var engine = this._scene.getEngine();
  13566. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  13567. };
  13568. ParticleSystem.prototype.render = function () {
  13569. var effect = this._getEffect();
  13570. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  13571. return 0;
  13572. var engine = this._scene.getEngine();
  13573. engine.enableEffect(effect);
  13574. var viewMatrix = this._scene.getViewMatrix();
  13575. effect.setTexture("diffuseSampler", this.particleTexture);
  13576. effect.setMatrix("view", viewMatrix);
  13577. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  13578. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  13579. if (this._scene.clipPlane) {
  13580. var clipPlane = this._scene.clipPlane;
  13581. var invView = viewMatrix.clone();
  13582. invView.invert();
  13583. effect.setMatrix("invView", invView);
  13584. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13585. }
  13586. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13587. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  13588. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  13589. } else {
  13590. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13591. }
  13592. if (this.forceDepthWrite) {
  13593. engine.setDepthWrite(true);
  13594. }
  13595. engine.draw(WebGLRenderingContext.TRIANGLES, 0, this.particles.length * 6);
  13596. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13597. return this.particles.length;
  13598. };
  13599. ParticleSystem.prototype.dispose = function () {
  13600. if (this._vertexBuffer) {
  13601. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13602. this._vertexBuffer = null;
  13603. }
  13604. if (this._indexBuffer) {
  13605. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13606. this._indexBuffer = null;
  13607. }
  13608. if (this.particleTexture) {
  13609. this.particleTexture.dispose();
  13610. this.particleTexture = null;
  13611. }
  13612. var index = this._scene.particleSystems.indexOf(this);
  13613. this._scene.particleSystems.splice(index, 1);
  13614. if (this.onDispose) {
  13615. this.onDispose();
  13616. }
  13617. };
  13618. ParticleSystem.prototype.clone = function (name, newEmitter) {
  13619. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  13620. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  13621. if (newEmitter === undefined) {
  13622. newEmitter = this.emitter;
  13623. }
  13624. result.emitter = newEmitter;
  13625. if (this.particleTexture) {
  13626. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  13627. }
  13628. result.start();
  13629. return result;
  13630. };
  13631. ParticleSystem.BLENDMODE_ONEONE = 0;
  13632. ParticleSystem.BLENDMODE_STANDARD = 1;
  13633. return ParticleSystem;
  13634. })();
  13635. BABYLON.ParticleSystem = ParticleSystem;
  13636. })(BABYLON || (BABYLON = {}));
  13637. var BABYLON;
  13638. (function (BABYLON) {
  13639. var Animation = (function () {
  13640. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  13641. this.name = name;
  13642. this.targetProperty = targetProperty;
  13643. this.framePerSecond = framePerSecond;
  13644. this.dataType = dataType;
  13645. this.loopMode = loopMode;
  13646. this._offsetsCache = {};
  13647. this._highLimitsCache = {};
  13648. this._stopped = false;
  13649. this.targetPropertyPath = targetProperty.split(".");
  13650. this.dataType = dataType;
  13651. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  13652. }
  13653. Animation.prototype.isStopped = function () {
  13654. return this._stopped;
  13655. };
  13656. Animation.prototype.getKeys = function () {
  13657. return this._keys;
  13658. };
  13659. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  13660. return startValue + (endValue - startValue) * gradient;
  13661. };
  13662. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  13663. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  13664. };
  13665. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  13666. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  13667. };
  13668. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  13669. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  13670. };
  13671. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  13672. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  13673. };
  13674. Animation.prototype.clone = function () {
  13675. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  13676. clone.setKeys(this._keys);
  13677. return clone;
  13678. };
  13679. Animation.prototype.setKeys = function (values) {
  13680. this._keys = values.slice(0);
  13681. this._offsetsCache = {};
  13682. this._highLimitsCache = {};
  13683. };
  13684. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  13685. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  13686. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  13687. }
  13688. this.currentFrame = currentFrame;
  13689. for (var key = 0; key < this._keys.length; key++) {
  13690. if (this._keys[key + 1].frame >= currentFrame) {
  13691. var startValue = this._keys[key].value;
  13692. var endValue = this._keys[key + 1].value;
  13693. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  13694. switch (this.dataType) {
  13695. case Animation.ANIMATIONTYPE_FLOAT:
  13696. switch (loopMode) {
  13697. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13698. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13699. return this.floatInterpolateFunction(startValue, endValue, gradient);
  13700. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13701. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  13702. }
  13703. break;
  13704. case Animation.ANIMATIONTYPE_QUATERNION:
  13705. var quaternion = null;
  13706. switch (loopMode) {
  13707. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13708. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13709. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  13710. break;
  13711. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13712. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13713. break;
  13714. }
  13715. return quaternion;
  13716. case Animation.ANIMATIONTYPE_VECTOR3:
  13717. switch (loopMode) {
  13718. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13719. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13720. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  13721. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13722. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13723. }
  13724. case Animation.ANIMATIONTYPE_VECTOR2:
  13725. switch (loopMode) {
  13726. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13727. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13728. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  13729. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13730. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13731. }
  13732. case Animation.ANIMATIONTYPE_COLOR3:
  13733. switch (loopMode) {
  13734. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13735. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13736. return this.color3InterpolateFunction(startValue, endValue, gradient);
  13737. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13738. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13739. }
  13740. case Animation.ANIMATIONTYPE_MATRIX:
  13741. switch (loopMode) {
  13742. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13743. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13744. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13745. return startValue;
  13746. }
  13747. default:
  13748. break;
  13749. }
  13750. break;
  13751. }
  13752. }
  13753. return this._keys[this._keys.length - 1].value;
  13754. };
  13755. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  13756. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  13757. this._stopped = true;
  13758. return false;
  13759. }
  13760. var returnValue = true;
  13761. if (this._keys[0].frame != 0) {
  13762. var newKey = {
  13763. frame: 0,
  13764. value: this._keys[0].value
  13765. };
  13766. this._keys.splice(0, 0, newKey);
  13767. }
  13768. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  13769. from = this._keys[0].frame;
  13770. }
  13771. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  13772. to = this._keys[this._keys.length - 1].frame;
  13773. }
  13774. var range = to - from;
  13775. var offsetValue;
  13776. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  13777. if (ratio > range && !loop) {
  13778. returnValue = false;
  13779. highLimitValue = this._keys[this._keys.length - 1].value;
  13780. } else {
  13781. var highLimitValue = 0;
  13782. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  13783. var keyOffset = to.toString() + from.toString();
  13784. if (!this._offsetsCache[keyOffset]) {
  13785. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  13786. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  13787. switch (this.dataType) {
  13788. case Animation.ANIMATIONTYPE_FLOAT:
  13789. this._offsetsCache[keyOffset] = toValue - fromValue;
  13790. break;
  13791. case Animation.ANIMATIONTYPE_QUATERNION:
  13792. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13793. break;
  13794. case Animation.ANIMATIONTYPE_VECTOR3:
  13795. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13796. case Animation.ANIMATIONTYPE_VECTOR2:
  13797. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13798. case Animation.ANIMATIONTYPE_COLOR3:
  13799. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13800. default:
  13801. break;
  13802. }
  13803. this._highLimitsCache[keyOffset] = toValue;
  13804. }
  13805. highLimitValue = this._highLimitsCache[keyOffset];
  13806. offsetValue = this._offsetsCache[keyOffset];
  13807. }
  13808. }
  13809. if (offsetValue === undefined) {
  13810. switch (this.dataType) {
  13811. case Animation.ANIMATIONTYPE_FLOAT:
  13812. offsetValue = 0;
  13813. break;
  13814. case Animation.ANIMATIONTYPE_QUATERNION:
  13815. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  13816. break;
  13817. case Animation.ANIMATIONTYPE_VECTOR3:
  13818. offsetValue = BABYLON.Vector3.Zero();
  13819. break;
  13820. case Animation.ANIMATIONTYPE_VECTOR2:
  13821. offsetValue = BABYLON.Vector2.Zero();
  13822. break;
  13823. case Animation.ANIMATIONTYPE_COLOR3:
  13824. offsetValue = BABYLON.Color3.Black();
  13825. }
  13826. }
  13827. var repeatCount = (ratio / range) >> 0;
  13828. var currentFrame = returnValue ? from + ratio % range : to;
  13829. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  13830. if (this.targetPropertyPath.length > 1) {
  13831. var property = this._target[this.targetPropertyPath[0]];
  13832. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  13833. property = property[this.targetPropertyPath[index]];
  13834. }
  13835. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  13836. } else {
  13837. this._target[this.targetPropertyPath[0]] = currentValue;
  13838. }
  13839. if (this._target.markAsDirty) {
  13840. this._target.markAsDirty(this.targetProperty);
  13841. }
  13842. if (!returnValue) {
  13843. this._stopped = true;
  13844. }
  13845. return returnValue;
  13846. };
  13847. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  13848. get: function () {
  13849. return Animation._ANIMATIONTYPE_FLOAT;
  13850. },
  13851. enumerable: true,
  13852. configurable: true
  13853. });
  13854. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  13855. get: function () {
  13856. return Animation._ANIMATIONTYPE_VECTOR3;
  13857. },
  13858. enumerable: true,
  13859. configurable: true
  13860. });
  13861. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  13862. get: function () {
  13863. return Animation._ANIMATIONTYPE_VECTOR2;
  13864. },
  13865. enumerable: true,
  13866. configurable: true
  13867. });
  13868. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  13869. get: function () {
  13870. return Animation._ANIMATIONTYPE_QUATERNION;
  13871. },
  13872. enumerable: true,
  13873. configurable: true
  13874. });
  13875. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  13876. get: function () {
  13877. return Animation._ANIMATIONTYPE_MATRIX;
  13878. },
  13879. enumerable: true,
  13880. configurable: true
  13881. });
  13882. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  13883. get: function () {
  13884. return Animation._ANIMATIONTYPE_COLOR3;
  13885. },
  13886. enumerable: true,
  13887. configurable: true
  13888. });
  13889. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  13890. get: function () {
  13891. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  13892. },
  13893. enumerable: true,
  13894. configurable: true
  13895. });
  13896. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  13897. get: function () {
  13898. return Animation._ANIMATIONLOOPMODE_CYCLE;
  13899. },
  13900. enumerable: true,
  13901. configurable: true
  13902. });
  13903. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  13904. get: function () {
  13905. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  13906. },
  13907. enumerable: true,
  13908. configurable: true
  13909. });
  13910. Animation._ANIMATIONTYPE_FLOAT = 0;
  13911. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  13912. Animation._ANIMATIONTYPE_QUATERNION = 2;
  13913. Animation._ANIMATIONTYPE_MATRIX = 3;
  13914. Animation._ANIMATIONTYPE_COLOR3 = 4;
  13915. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  13916. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  13917. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  13918. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  13919. return Animation;
  13920. })();
  13921. BABYLON.Animation = Animation;
  13922. })(BABYLON || (BABYLON = {}));
  13923. var BABYLON;
  13924. (function (BABYLON) {
  13925. var Animatable = (function () {
  13926. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  13927. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  13928. if (typeof toFrame === "undefined") { toFrame = 100; }
  13929. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  13930. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  13931. this.target = target;
  13932. this.fromFrame = fromFrame;
  13933. this.toFrame = toFrame;
  13934. this.loopAnimation = loopAnimation;
  13935. this.speedRatio = speedRatio;
  13936. this.onAnimationEnd = onAnimationEnd;
  13937. this._animations = new Array();
  13938. this._paused = false;
  13939. this.animationStarted = false;
  13940. if (animations) {
  13941. this.appendAnimations(target, animations);
  13942. }
  13943. this._scene = scene;
  13944. scene._activeAnimatables.push(this);
  13945. }
  13946. Animatable.prototype.appendAnimations = function (target, animations) {
  13947. for (var index = 0; index < animations.length; index++) {
  13948. var animation = animations[index];
  13949. animation._target = target;
  13950. this._animations.push(animation);
  13951. }
  13952. };
  13953. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  13954. var animations = this._animations;
  13955. for (var index = 0; index < animations.length; index++) {
  13956. if (animations[index].targetProperty === property) {
  13957. return animations[index];
  13958. }
  13959. }
  13960. return null;
  13961. };
  13962. Animatable.prototype.pause = function () {
  13963. this._paused = true;
  13964. };
  13965. Animatable.prototype.restart = function () {
  13966. this._paused = false;
  13967. };
  13968. Animatable.prototype.stop = function () {
  13969. var index = this._scene._activeAnimatables.indexOf(this);
  13970. if (index > -1) {
  13971. this._scene._activeAnimatables.splice(index, 1);
  13972. }
  13973. if (this.onAnimationEnd) {
  13974. this.onAnimationEnd();
  13975. }
  13976. };
  13977. Animatable.prototype._animate = function (delay) {
  13978. if (this._paused) {
  13979. return true;
  13980. }
  13981. if (!this._localDelayOffset) {
  13982. this._localDelayOffset = delay;
  13983. }
  13984. var running = false;
  13985. var animations = this._animations;
  13986. for (var index = 0; index < animations.length; index++) {
  13987. var animation = animations[index];
  13988. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  13989. running = running || isRunning;
  13990. }
  13991. if (!running && this.onAnimationEnd) {
  13992. this.onAnimationEnd();
  13993. }
  13994. return running;
  13995. };
  13996. return Animatable;
  13997. })();
  13998. BABYLON.Animatable = Animatable;
  13999. })(BABYLON || (BABYLON = {}));
  14000. var BABYLON;
  14001. (function (BABYLON) {
  14002. var Octree = (function () {
  14003. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  14004. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  14005. this.maxDepth = maxDepth;
  14006. this.dynamicContent = new Array();
  14007. this._maxBlockCapacity = maxBlockCapacity || 64;
  14008. this._selectionContent = new BABYLON.SmartArray(1024);
  14009. this._creationFunc = creationFunc;
  14010. }
  14011. Octree.prototype.update = function (worldMin, worldMax, entries) {
  14012. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  14013. };
  14014. Octree.prototype.addMesh = function (entry) {
  14015. for (var index = 0; index < this.blocks.length; index++) {
  14016. var block = this.blocks[index];
  14017. block.addEntry(entry);
  14018. }
  14019. };
  14020. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  14021. this._selectionContent.reset();
  14022. for (var index = 0; index < this.blocks.length; index++) {
  14023. var block = this.blocks[index];
  14024. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  14025. }
  14026. if (allowDuplicate) {
  14027. this._selectionContent.concat(this.dynamicContent);
  14028. } else {
  14029. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14030. }
  14031. return this._selectionContent;
  14032. };
  14033. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  14034. this._selectionContent.reset();
  14035. for (var index = 0; index < this.blocks.length; index++) {
  14036. var block = this.blocks[index];
  14037. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  14038. }
  14039. if (allowDuplicate) {
  14040. this._selectionContent.concat(this.dynamicContent);
  14041. } else {
  14042. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14043. }
  14044. return this._selectionContent;
  14045. };
  14046. Octree.prototype.intersectsRay = function (ray) {
  14047. this._selectionContent.reset();
  14048. for (var index = 0; index < this.blocks.length; index++) {
  14049. var block = this.blocks[index];
  14050. block.intersectsRay(ray, this._selectionContent);
  14051. }
  14052. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14053. return this._selectionContent;
  14054. };
  14055. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  14056. target.blocks = new Array();
  14057. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  14058. for (var x = 0; x < 2; x++) {
  14059. for (var y = 0; y < 2; y++) {
  14060. for (var z = 0; z < 2; z++) {
  14061. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  14062. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  14063. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  14064. block.addEntries(entries);
  14065. target.blocks.push(block);
  14066. }
  14067. }
  14068. }
  14069. };
  14070. Octree.CreationFuncForMeshes = function (entry, block) {
  14071. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14072. block.entries.push(entry);
  14073. }
  14074. };
  14075. Octree.CreationFuncForSubMeshes = function (entry, block) {
  14076. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14077. block.entries.push(entry);
  14078. }
  14079. };
  14080. return Octree;
  14081. })();
  14082. BABYLON.Octree = Octree;
  14083. })(BABYLON || (BABYLON = {}));
  14084. var BABYLON;
  14085. (function (BABYLON) {
  14086. var OctreeBlock = (function () {
  14087. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  14088. this.entries = new Array();
  14089. this._boundingVectors = new Array();
  14090. this._capacity = capacity;
  14091. this._depth = depth;
  14092. this._maxDepth = maxDepth;
  14093. this._creationFunc = creationFunc;
  14094. this._minPoint = minPoint;
  14095. this._maxPoint = maxPoint;
  14096. this._boundingVectors.push(minPoint.clone());
  14097. this._boundingVectors.push(maxPoint.clone());
  14098. this._boundingVectors.push(minPoint.clone());
  14099. this._boundingVectors[2].x = maxPoint.x;
  14100. this._boundingVectors.push(minPoint.clone());
  14101. this._boundingVectors[3].y = maxPoint.y;
  14102. this._boundingVectors.push(minPoint.clone());
  14103. this._boundingVectors[4].z = maxPoint.z;
  14104. this._boundingVectors.push(maxPoint.clone());
  14105. this._boundingVectors[5].z = minPoint.z;
  14106. this._boundingVectors.push(maxPoint.clone());
  14107. this._boundingVectors[6].x = minPoint.x;
  14108. this._boundingVectors.push(maxPoint.clone());
  14109. this._boundingVectors[7].y = minPoint.y;
  14110. }
  14111. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  14112. get: function () {
  14113. return this._capacity;
  14114. },
  14115. enumerable: true,
  14116. configurable: true
  14117. });
  14118. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  14119. get: function () {
  14120. return this._minPoint;
  14121. },
  14122. enumerable: true,
  14123. configurable: true
  14124. });
  14125. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  14126. get: function () {
  14127. return this._maxPoint;
  14128. },
  14129. enumerable: true,
  14130. configurable: true
  14131. });
  14132. OctreeBlock.prototype.addEntry = function (entry) {
  14133. if (this.blocks) {
  14134. for (var index = 0; index < this.blocks.length; index++) {
  14135. var block = this.blocks[index];
  14136. block.addEntry(entry);
  14137. }
  14138. return;
  14139. }
  14140. this._creationFunc(entry, this);
  14141. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  14142. this.createInnerBlocks();
  14143. }
  14144. };
  14145. OctreeBlock.prototype.addEntries = function (entries) {
  14146. for (var index = 0; index < entries.length; index++) {
  14147. var mesh = entries[index];
  14148. this.addEntry(mesh);
  14149. }
  14150. };
  14151. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  14152. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  14153. if (this.blocks) {
  14154. for (var index = 0; index < this.blocks.length; index++) {
  14155. var block = this.blocks[index];
  14156. block.select(frustumPlanes, selection, allowDuplicate);
  14157. }
  14158. return;
  14159. }
  14160. if (allowDuplicate) {
  14161. selection.concat(this.entries);
  14162. } else {
  14163. selection.concatWithNoDuplicate(this.entries);
  14164. }
  14165. }
  14166. };
  14167. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  14168. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  14169. if (this.blocks) {
  14170. for (var index = 0; index < this.blocks.length; index++) {
  14171. var block = this.blocks[index];
  14172. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  14173. }
  14174. return;
  14175. }
  14176. if (allowDuplicate) {
  14177. selection.concat(this.entries);
  14178. } else {
  14179. selection.concatWithNoDuplicate(this.entries);
  14180. }
  14181. }
  14182. };
  14183. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  14184. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  14185. if (this.blocks) {
  14186. for (var index = 0; index < this.blocks.length; index++) {
  14187. var block = this.blocks[index];
  14188. block.intersectsRay(ray, selection);
  14189. }
  14190. return;
  14191. }
  14192. selection.concatWithNoDuplicate(this.entries);
  14193. }
  14194. };
  14195. OctreeBlock.prototype.createInnerBlocks = function () {
  14196. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  14197. };
  14198. return OctreeBlock;
  14199. })();
  14200. BABYLON.OctreeBlock = OctreeBlock;
  14201. })(BABYLON || (BABYLON = {}));
  14202. var BABYLON;
  14203. (function (BABYLON) {
  14204. var Skeleton = (function () {
  14205. function Skeleton(name, id, scene) {
  14206. this.name = name;
  14207. this.id = id;
  14208. this.bones = new Array();
  14209. this._isDirty = true;
  14210. this._identity = BABYLON.Matrix.Identity();
  14211. this.bones = [];
  14212. this._scene = scene;
  14213. scene.skeletons.push(this);
  14214. }
  14215. Skeleton.prototype.getTransformMatrices = function () {
  14216. return this._transformMatrices;
  14217. };
  14218. Skeleton.prototype._markAsDirty = function () {
  14219. this._isDirty = true;
  14220. };
  14221. Skeleton.prototype.prepare = function () {
  14222. if (!this._isDirty) {
  14223. return;
  14224. }
  14225. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  14226. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  14227. }
  14228. for (var index = 0; index < this.bones.length; index++) {
  14229. var bone = this.bones[index];
  14230. var parentBone = bone.getParent();
  14231. if (parentBone) {
  14232. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  14233. } else {
  14234. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  14235. }
  14236. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  14237. }
  14238. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  14239. this._isDirty = false;
  14240. };
  14241. Skeleton.prototype.getAnimatables = function () {
  14242. if (!this._animatables || this._animatables.length != this.bones.length) {
  14243. this._animatables = [];
  14244. for (var index = 0; index < this.bones.length; index++) {
  14245. this._animatables.push(this.bones[index]);
  14246. }
  14247. }
  14248. return this._animatables;
  14249. };
  14250. Skeleton.prototype.clone = function (name, id) {
  14251. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  14252. for (var index = 0; index < this.bones.length; index++) {
  14253. var source = this.bones[index];
  14254. var parentBone = null;
  14255. if (source.getParent()) {
  14256. var parentIndex = this.bones.indexOf(source.getParent());
  14257. parentBone = result.bones[parentIndex];
  14258. }
  14259. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  14260. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  14261. }
  14262. return result;
  14263. };
  14264. return Skeleton;
  14265. })();
  14266. BABYLON.Skeleton = Skeleton;
  14267. })(BABYLON || (BABYLON = {}));
  14268. var BABYLON;
  14269. (function (BABYLON) {
  14270. var Bone = (function () {
  14271. function Bone(name, skeleton, parentBone, matrix) {
  14272. this.name = name;
  14273. this.children = new Array();
  14274. this.animations = new Array();
  14275. this._worldTransform = new BABYLON.Matrix();
  14276. this._absoluteTransform = new BABYLON.Matrix();
  14277. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  14278. this._skeleton = skeleton;
  14279. this._matrix = matrix;
  14280. this._baseMatrix = matrix;
  14281. skeleton.bones.push(this);
  14282. if (parentBone) {
  14283. this._parent = parentBone;
  14284. parentBone.children.push(this);
  14285. } else {
  14286. this._parent = null;
  14287. }
  14288. this._updateDifferenceMatrix();
  14289. }
  14290. Bone.prototype.getParent = function () {
  14291. return this._parent;
  14292. };
  14293. Bone.prototype.getLocalMatrix = function () {
  14294. return this._matrix;
  14295. };
  14296. Bone.prototype.getBaseMatrix = function () {
  14297. return this._baseMatrix;
  14298. };
  14299. Bone.prototype.getWorldMatrix = function () {
  14300. return this._worldTransform;
  14301. };
  14302. Bone.prototype.getInvertedAbsoluteTransform = function () {
  14303. return this._invertedAbsoluteTransform;
  14304. };
  14305. Bone.prototype.getAbsoluteMatrix = function () {
  14306. var matrix = this._matrix.clone();
  14307. var parent = this._parent;
  14308. while (parent) {
  14309. matrix = matrix.multiply(parent.getLocalMatrix());
  14310. parent = parent.getParent();
  14311. }
  14312. return matrix;
  14313. };
  14314. Bone.prototype.updateMatrix = function (matrix) {
  14315. this._matrix = matrix;
  14316. this._skeleton._markAsDirty();
  14317. this._updateDifferenceMatrix();
  14318. };
  14319. Bone.prototype._updateDifferenceMatrix = function () {
  14320. if (this._parent) {
  14321. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  14322. } else {
  14323. this._absoluteTransform.copyFrom(this._matrix);
  14324. }
  14325. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  14326. for (var index = 0; index < this.children.length; index++) {
  14327. this.children[index]._updateDifferenceMatrix();
  14328. }
  14329. };
  14330. Bone.prototype.markAsDirty = function () {
  14331. this._skeleton._markAsDirty();
  14332. };
  14333. return Bone;
  14334. })();
  14335. BABYLON.Bone = Bone;
  14336. })(BABYLON || (BABYLON = {}));
  14337. var BABYLON;
  14338. (function (BABYLON) {
  14339. var PostProcess = (function () {
  14340. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  14341. this.name = name;
  14342. this.width = -1;
  14343. this.height = -1;
  14344. this._reusable = false;
  14345. this._textures = new BABYLON.SmartArray(2);
  14346. this._currentRenderTextureInd = 0;
  14347. if (camera != null) {
  14348. this._camera = camera;
  14349. this._scene = camera.getScene();
  14350. camera.attachPostProcess(this);
  14351. this._engine = this._scene.getEngine();
  14352. } else {
  14353. this._engine = engine;
  14354. }
  14355. this._renderRatio = ratio;
  14356. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14357. this._reusable = reusable || false;
  14358. samplers = samplers || [];
  14359. samplers.push("textureSampler");
  14360. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  14361. }
  14362. PostProcess.prototype.isReusable = function () {
  14363. return this._reusable;
  14364. };
  14365. PostProcess.prototype.activate = function (camera, sourceTexture) {
  14366. camera = camera || this._camera;
  14367. var scene = camera.getScene();
  14368. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  14369. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  14370. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  14371. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  14372. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  14373. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  14374. if (this._textures.length > 0) {
  14375. for (var i = 0; i < this._textures.length; i++) {
  14376. this._engine._releaseTexture(this._textures.data[i]);
  14377. }
  14378. this._textures.reset();
  14379. }
  14380. this.width = desiredWidth;
  14381. this.height = desiredHeight;
  14382. 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 }));
  14383. if (this._reusable) {
  14384. 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 }));
  14385. }
  14386. if (this.onSizeChanged) {
  14387. this.onSizeChanged();
  14388. }
  14389. }
  14390. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  14391. if (this.onActivate) {
  14392. this.onActivate(camera);
  14393. }
  14394. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  14395. if (this._reusable) {
  14396. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  14397. }
  14398. };
  14399. PostProcess.prototype.apply = function () {
  14400. if (!this._effect.isReady())
  14401. return null;
  14402. this._engine.enableEffect(this._effect);
  14403. this._engine.setState(false);
  14404. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14405. this._engine.setDepthBuffer(false);
  14406. this._engine.setDepthWrite(false);
  14407. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  14408. if (this.onApply) {
  14409. this.onApply(this._effect);
  14410. }
  14411. return this._effect;
  14412. };
  14413. PostProcess.prototype.dispose = function (camera) {
  14414. camera = camera || this._camera;
  14415. if (this._textures.length > 0) {
  14416. for (var i = 0; i < this._textures.length; i++) {
  14417. this._engine._releaseTexture(this._textures.data[i]);
  14418. }
  14419. this._textures.reset();
  14420. }
  14421. camera.detachPostProcess(this);
  14422. var index = camera._postProcesses.indexOf(this);
  14423. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  14424. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  14425. }
  14426. };
  14427. return PostProcess;
  14428. })();
  14429. BABYLON.PostProcess = PostProcess;
  14430. })(BABYLON || (BABYLON = {}));
  14431. var BABYLON;
  14432. (function (BABYLON) {
  14433. var PostProcessManager = (function () {
  14434. function PostProcessManager(scene) {
  14435. this._vertexDeclaration = [2];
  14436. this._vertexStrideSize = 2 * 4;
  14437. this._scene = scene;
  14438. var vertices = [];
  14439. vertices.push(1, 1);
  14440. vertices.push(-1, 1);
  14441. vertices.push(-1, -1);
  14442. vertices.push(1, -1);
  14443. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14444. var indices = [];
  14445. indices.push(0);
  14446. indices.push(1);
  14447. indices.push(2);
  14448. indices.push(0);
  14449. indices.push(2);
  14450. indices.push(3);
  14451. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14452. }
  14453. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  14454. var postProcesses = this._scene.activeCamera._postProcesses;
  14455. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  14456. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  14457. return false;
  14458. }
  14459. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  14460. return true;
  14461. };
  14462. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  14463. var postProcesses = this._scene.activeCamera._postProcesses;
  14464. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  14465. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  14466. return;
  14467. }
  14468. var engine = this._scene.getEngine();
  14469. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  14470. if (index < postProcessesTakenIndices.length - 1) {
  14471. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  14472. } else {
  14473. if (targetTexture) {
  14474. engine.bindFramebuffer(targetTexture);
  14475. } else {
  14476. engine.restoreDefaultFramebuffer();
  14477. }
  14478. }
  14479. if (doNotPresent) {
  14480. break;
  14481. }
  14482. var pp = postProcesses[postProcessesTakenIndices[index]];
  14483. var effect = pp.apply();
  14484. if (effect) {
  14485. if (pp.onBeforeRender) {
  14486. pp.onBeforeRender(effect);
  14487. }
  14488. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14489. engine.draw(WebGLRenderingContext.TRIANGLES, 0, 6);
  14490. }
  14491. }
  14492. engine.setDepthBuffer(true);
  14493. engine.setDepthWrite(true);
  14494. };
  14495. PostProcessManager.prototype.dispose = function () {
  14496. if (this._vertexBuffer) {
  14497. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14498. this._vertexBuffer = null;
  14499. }
  14500. if (this._indexBuffer) {
  14501. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14502. this._indexBuffer = null;
  14503. }
  14504. };
  14505. return PostProcessManager;
  14506. })();
  14507. BABYLON.PostProcessManager = PostProcessManager;
  14508. })(BABYLON || (BABYLON = {}));
  14509. var __extends = this.__extends || function (d, b) {
  14510. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14511. function __() { this.constructor = d; }
  14512. __.prototype = b.prototype;
  14513. d.prototype = new __();
  14514. };
  14515. var BABYLON;
  14516. (function (BABYLON) {
  14517. var PassPostProcess = (function (_super) {
  14518. __extends(PassPostProcess, _super);
  14519. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  14520. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  14521. }
  14522. return PassPostProcess;
  14523. })(BABYLON.PostProcess);
  14524. BABYLON.PassPostProcess = PassPostProcess;
  14525. })(BABYLON || (BABYLON = {}));
  14526. var __extends = this.__extends || function (d, b) {
  14527. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14528. function __() { this.constructor = d; }
  14529. __.prototype = b.prototype;
  14530. d.prototype = new __();
  14531. };
  14532. var BABYLON;
  14533. (function (BABYLON) {
  14534. var BlurPostProcess = (function (_super) {
  14535. __extends(BlurPostProcess, _super);
  14536. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  14537. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  14538. var _this = this;
  14539. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  14540. this.direction = direction;
  14541. this.blurWidth = blurWidth;
  14542. this.onApply = function (effect) {
  14543. effect.setFloat2("screenSize", _this.width, _this.height);
  14544. effect.setVector2("direction", _this.direction);
  14545. effect.setFloat("blurWidth", _this.blurWidth);
  14546. };
  14547. }
  14548. return BlurPostProcess;
  14549. })(BABYLON.PostProcess);
  14550. BABYLON.BlurPostProcess = BlurPostProcess;
  14551. })(BABYLON || (BABYLON = {}));
  14552. var __extends = this.__extends || function (d, b) {
  14553. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14554. function __() { this.constructor = d; }
  14555. __.prototype = b.prototype;
  14556. d.prototype = new __();
  14557. };
  14558. var BABYLON;
  14559. (function (BABYLON) {
  14560. var RefractionPostProcess = (function (_super) {
  14561. __extends(RefractionPostProcess, _super);
  14562. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  14563. var _this = this;
  14564. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  14565. this.color = color;
  14566. this.depth = depth;
  14567. this.colorLevel = colorLevel;
  14568. this.onActivate = function (cam) {
  14569. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  14570. };
  14571. this.onApply = function (effect) {
  14572. effect.setColor3("baseColor", _this.color);
  14573. effect.setFloat("depth", _this.depth);
  14574. effect.setFloat("colorLevel", _this.colorLevel);
  14575. effect.setTexture("refractionSampler", _this._refRexture);
  14576. };
  14577. }
  14578. RefractionPostProcess.prototype.dispose = function (camera) {
  14579. if (this._refRexture) {
  14580. this._refRexture.dispose();
  14581. }
  14582. _super.prototype.dispose.call(this, camera);
  14583. };
  14584. return RefractionPostProcess;
  14585. })(BABYLON.PostProcess);
  14586. BABYLON.RefractionPostProcess = RefractionPostProcess;
  14587. })(BABYLON || (BABYLON = {}));
  14588. var __extends = this.__extends || function (d, b) {
  14589. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14590. function __() { this.constructor = d; }
  14591. __.prototype = b.prototype;
  14592. d.prototype = new __();
  14593. };
  14594. var BABYLON;
  14595. (function (BABYLON) {
  14596. var BlackAndWhitePostProcess = (function (_super) {
  14597. __extends(BlackAndWhitePostProcess, _super);
  14598. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  14599. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  14600. }
  14601. return BlackAndWhitePostProcess;
  14602. })(BABYLON.PostProcess);
  14603. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  14604. })(BABYLON || (BABYLON = {}));
  14605. var __extends = this.__extends || function (d, b) {
  14606. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14607. function __() { this.constructor = d; }
  14608. __.prototype = b.prototype;
  14609. d.prototype = new __();
  14610. };
  14611. var BABYLON;
  14612. (function (BABYLON) {
  14613. var ConvolutionPostProcess = (function (_super) {
  14614. __extends(ConvolutionPostProcess, _super);
  14615. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  14616. var _this = this;
  14617. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  14618. this.kernel = kernel;
  14619. this.onApply = function (effect) {
  14620. effect.setFloat2("screenSize", _this.width, _this.height);
  14621. effect.setArray("kernel", _this.kernel);
  14622. };
  14623. }
  14624. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  14625. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  14626. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  14627. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  14628. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  14629. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  14630. return ConvolutionPostProcess;
  14631. })(BABYLON.PostProcess);
  14632. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  14633. })(BABYLON || (BABYLON = {}));
  14634. var __extends = this.__extends || function (d, b) {
  14635. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14636. function __() { this.constructor = d; }
  14637. __.prototype = b.prototype;
  14638. d.prototype = new __();
  14639. };
  14640. var BABYLON;
  14641. (function (BABYLON) {
  14642. var FilterPostProcess = (function (_super) {
  14643. __extends(FilterPostProcess, _super);
  14644. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  14645. var _this = this;
  14646. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  14647. this.kernelMatrix = kernelMatrix;
  14648. this.onApply = function (effect) {
  14649. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  14650. };
  14651. }
  14652. return FilterPostProcess;
  14653. })(BABYLON.PostProcess);
  14654. BABYLON.FilterPostProcess = FilterPostProcess;
  14655. })(BABYLON || (BABYLON = {}));
  14656. var __extends = this.__extends || function (d, b) {
  14657. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14658. function __() { this.constructor = d; }
  14659. __.prototype = b.prototype;
  14660. d.prototype = new __();
  14661. };
  14662. var BABYLON;
  14663. (function (BABYLON) {
  14664. var FxaaPostProcess = (function (_super) {
  14665. __extends(FxaaPostProcess, _super);
  14666. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  14667. var _this = this;
  14668. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  14669. this.onSizeChanged = function () {
  14670. _this.texelWidth = 1.0 / _this.width;
  14671. _this.texelHeight = 1.0 / _this.height;
  14672. };
  14673. this.onApply = function (effect) {
  14674. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  14675. };
  14676. }
  14677. return FxaaPostProcess;
  14678. })(BABYLON.PostProcess);
  14679. BABYLON.FxaaPostProcess = FxaaPostProcess;
  14680. })(BABYLON || (BABYLON = {}));
  14681. var BABYLON;
  14682. (function (BABYLON) {
  14683. var LensFlare = (function () {
  14684. function LensFlare(size, position, color, imgUrl, system) {
  14685. this.size = size;
  14686. this.position = position;
  14687. this.dispose = function () {
  14688. if (this.texture) {
  14689. this.texture.dispose();
  14690. }
  14691. var index = this._system.lensFlares.indexOf(this);
  14692. this._system.lensFlares.splice(index, 1);
  14693. };
  14694. this.color = color || new BABYLON.Color3(1, 1, 1);
  14695. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  14696. this._system = system;
  14697. system.lensFlares.push(this);
  14698. }
  14699. return LensFlare;
  14700. })();
  14701. BABYLON.LensFlare = LensFlare;
  14702. })(BABYLON || (BABYLON = {}));
  14703. var BABYLON;
  14704. (function (BABYLON) {
  14705. var LensFlareSystem = (function () {
  14706. function LensFlareSystem(name, emitter, scene) {
  14707. this.name = name;
  14708. this.lensFlares = new Array();
  14709. this.borderLimit = 300;
  14710. this._vertexDeclaration = [2];
  14711. this._vertexStrideSize = 2 * 4;
  14712. this._isEnabled = true;
  14713. this._scene = scene;
  14714. this._emitter = emitter;
  14715. scene.lensFlareSystems.push(this);
  14716. this.meshesSelectionPredicate = function (m) {
  14717. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  14718. };
  14719. var vertices = [];
  14720. vertices.push(1, 1);
  14721. vertices.push(-1, 1);
  14722. vertices.push(-1, -1);
  14723. vertices.push(1, -1);
  14724. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14725. var indices = [];
  14726. indices.push(0);
  14727. indices.push(1);
  14728. indices.push(2);
  14729. indices.push(0);
  14730. indices.push(2);
  14731. indices.push(3);
  14732. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14733. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  14734. }
  14735. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  14736. get: function () {
  14737. return this._isEnabled;
  14738. },
  14739. set: function (value) {
  14740. this._isEnabled = value;
  14741. },
  14742. enumerable: true,
  14743. configurable: true
  14744. });
  14745. LensFlareSystem.prototype.getScene = function () {
  14746. return this._scene;
  14747. };
  14748. LensFlareSystem.prototype.getEmitter = function () {
  14749. return this._emitter;
  14750. };
  14751. LensFlareSystem.prototype.getEmitterPosition = function () {
  14752. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  14753. };
  14754. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  14755. var position = this.getEmitterPosition();
  14756. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  14757. this._positionX = position.x;
  14758. this._positionY = position.y;
  14759. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  14760. if (position.z > 0) {
  14761. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  14762. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  14763. return true;
  14764. }
  14765. }
  14766. return false;
  14767. };
  14768. LensFlareSystem.prototype._isVisible = function () {
  14769. if (!this._isEnabled) {
  14770. return false;
  14771. }
  14772. var emitterPosition = this.getEmitterPosition();
  14773. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  14774. var distance = direction.length();
  14775. direction.normalize();
  14776. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  14777. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  14778. return !pickInfo.hit || pickInfo.distance > distance;
  14779. };
  14780. LensFlareSystem.prototype.render = function () {
  14781. if (!this._effect.isReady())
  14782. return false;
  14783. var engine = this._scene.getEngine();
  14784. var viewport = this._scene.activeCamera.viewport;
  14785. var globalViewport = viewport.toGlobal(engine);
  14786. if (!this.computeEffectivePosition(globalViewport)) {
  14787. return false;
  14788. }
  14789. if (!this._isVisible()) {
  14790. return false;
  14791. }
  14792. var awayX;
  14793. var awayY;
  14794. if (this._positionX < this.borderLimit + globalViewport.x) {
  14795. awayX = this.borderLimit + globalViewport.x - this._positionX;
  14796. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  14797. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  14798. } else {
  14799. awayX = 0;
  14800. }
  14801. if (this._positionY < this.borderLimit + globalViewport.y) {
  14802. awayY = this.borderLimit + globalViewport.y - this._positionY;
  14803. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  14804. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  14805. } else {
  14806. awayY = 0;
  14807. }
  14808. var away = (awayX > awayY) ? awayX : awayY;
  14809. if (away > this.borderLimit) {
  14810. away = this.borderLimit;
  14811. }
  14812. var intensity = 1.0 - (away / this.borderLimit);
  14813. if (intensity < 0) {
  14814. return false;
  14815. }
  14816. if (intensity > 1.0) {
  14817. intensity = 1.0;
  14818. }
  14819. var centerX = globalViewport.x + globalViewport.width / 2;
  14820. var centerY = globalViewport.y + globalViewport.height / 2;
  14821. var distX = centerX - this._positionX;
  14822. var distY = centerY - this._positionY;
  14823. engine.enableEffect(this._effect);
  14824. engine.setState(false);
  14825. engine.setDepthBuffer(false);
  14826. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14827. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14828. for (var index = 0; index < this.lensFlares.length; index++) {
  14829. var flare = this.lensFlares[index];
  14830. var x = centerX - (distX * flare.position);
  14831. var y = centerY - (distY * flare.position);
  14832. var cw = flare.size;
  14833. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  14834. var cx = 2 * (x / globalViewport.width) - 1.0;
  14835. var cy = 1.0 - 2 * (y / globalViewport.height);
  14836. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  14837. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  14838. this._effect.setTexture("textureSampler", flare.texture);
  14839. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  14840. engine.draw(WebGLRenderingContext.TRIANGLES, 0, 6);
  14841. }
  14842. engine.setDepthBuffer(true);
  14843. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14844. return true;
  14845. };
  14846. LensFlareSystem.prototype.dispose = function () {
  14847. if (this._vertexBuffer) {
  14848. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14849. this._vertexBuffer = null;
  14850. }
  14851. if (this._indexBuffer) {
  14852. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14853. this._indexBuffer = null;
  14854. }
  14855. while (this.lensFlares.length) {
  14856. this.lensFlares[0].dispose();
  14857. }
  14858. var index = this._scene.lensFlareSystems.indexOf(this);
  14859. this._scene.lensFlareSystems.splice(index, 1);
  14860. };
  14861. return LensFlareSystem;
  14862. })();
  14863. BABYLON.LensFlareSystem = LensFlareSystem;
  14864. })(BABYLON || (BABYLON = {}));
  14865. var BABYLON;
  14866. (function (BABYLON) {
  14867. var OimoJSPlugin = (function () {
  14868. function OimoJSPlugin() {
  14869. this._registeredMeshes = [];
  14870. /**
  14871. * Update the body position according to the mesh position
  14872. * @param mesh
  14873. */
  14874. this.updateBodyPosition = function (mesh) {
  14875. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14876. var registeredMesh = this._registeredMeshes[index];
  14877. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  14878. var body = registeredMesh.body.body;
  14879. mesh.computeWorldMatrix(true);
  14880. var center = mesh.getBoundingInfo().boundingBox.center;
  14881. body.setPosition(center.x, center.y, center.z);
  14882. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  14883. return;
  14884. }
  14885. if (registeredMesh.mesh.parent === mesh) {
  14886. mesh.computeWorldMatrix(true);
  14887. registeredMesh.mesh.computeWorldMatrix(true);
  14888. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  14889. var absoluteRotation = mesh.rotation;
  14890. body = registeredMesh.body.body;
  14891. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  14892. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  14893. return;
  14894. }
  14895. }
  14896. };
  14897. }
  14898. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  14899. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  14900. };
  14901. OimoJSPlugin.prototype.initialize = function (iterations) {
  14902. this._world = new OIMO.World();
  14903. this._world.clear();
  14904. };
  14905. OimoJSPlugin.prototype.setGravity = function (gravity) {
  14906. this._world.gravity = gravity;
  14907. };
  14908. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  14909. var body = null;
  14910. this.unregisterMesh(mesh);
  14911. mesh.computeWorldMatrix(true);
  14912. switch (impostor) {
  14913. case BABYLON.PhysicsEngine.SphereImpostor:
  14914. var bbox = mesh.getBoundingInfo().boundingBox;
  14915. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  14916. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  14917. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  14918. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  14919. var deltaPosition = mesh.position.subtract(bbox.center);
  14920. body = new OIMO.Body({
  14921. type: 'sphere',
  14922. size: [size],
  14923. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  14924. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  14925. move: options.mass != 0,
  14926. config: [options.mass, options.friction, options.restitution],
  14927. world: this._world
  14928. });
  14929. this._registeredMeshes.push({
  14930. mesh: mesh,
  14931. body: body,
  14932. delta: deltaPosition
  14933. });
  14934. break;
  14935. case BABYLON.PhysicsEngine.PlaneImpostor:
  14936. case BABYLON.PhysicsEngine.BoxImpostor:
  14937. bbox = mesh.getBoundingInfo().boundingBox;
  14938. var min = bbox.minimumWorld;
  14939. var max = bbox.maximumWorld;
  14940. var box = max.subtract(min);
  14941. var sizeX = this._checkWithEpsilon(box.x);
  14942. var sizeY = this._checkWithEpsilon(box.y);
  14943. var sizeZ = this._checkWithEpsilon(box.z);
  14944. var deltaPosition = mesh.position.subtract(bbox.center);
  14945. body = new OIMO.Body({
  14946. type: 'box',
  14947. size: [sizeX, sizeY, sizeZ],
  14948. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  14949. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  14950. move: options.mass != 0,
  14951. config: [options.mass, options.friction, options.restitution],
  14952. world: this._world
  14953. });
  14954. this._registeredMeshes.push({
  14955. mesh: mesh,
  14956. body: body,
  14957. delta: deltaPosition
  14958. });
  14959. break;
  14960. }
  14961. return body;
  14962. };
  14963. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  14964. var types = [], sizes = [], positions = [], rotations = [];
  14965. var initialMesh = parts[0].mesh;
  14966. for (var index = 0; index < parts.length; index++) {
  14967. var part = parts[index];
  14968. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  14969. types.push(bodyParameters.type);
  14970. sizes.push.apply(sizes, bodyParameters.size);
  14971. positions.push.apply(positions, bodyParameters.pos);
  14972. rotations.push.apply(rotations, bodyParameters.rot);
  14973. }
  14974. var body = new OIMO.Body({
  14975. type: types,
  14976. size: sizes,
  14977. pos: positions,
  14978. rot: rotations,
  14979. move: options.mass != 0,
  14980. config: [options.mass, options.friction, options.restitution],
  14981. world: this._world
  14982. });
  14983. this._registeredMeshes.push({
  14984. mesh: initialMesh,
  14985. body: body
  14986. });
  14987. return body;
  14988. };
  14989. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  14990. var bodyParameters = null;
  14991. var mesh = part.mesh;
  14992. switch (part.impostor) {
  14993. case BABYLON.PhysicsEngine.SphereImpostor:
  14994. var bbox = mesh.getBoundingInfo().boundingBox;
  14995. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  14996. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  14997. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  14998. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  14999. bodyParameters = {
  15000. type: 'sphere',
  15001. /* bug with oimo : sphere needs 3 sizes in this case */
  15002. size: [size, -1, -1],
  15003. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  15004. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  15005. };
  15006. break;
  15007. case BABYLON.PhysicsEngine.PlaneImpostor:
  15008. case BABYLON.PhysicsEngine.BoxImpostor:
  15009. bbox = mesh.getBoundingInfo().boundingBox;
  15010. var min = bbox.minimumWorld;
  15011. var max = bbox.maximumWorld;
  15012. var box = max.subtract(min);
  15013. var sizeX = this._checkWithEpsilon(box.x);
  15014. var sizeY = this._checkWithEpsilon(box.y);
  15015. var sizeZ = this._checkWithEpsilon(box.z);
  15016. var relativePosition = mesh.position;
  15017. bodyParameters = {
  15018. type: 'box',
  15019. size: [sizeX, sizeY, sizeZ],
  15020. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  15021. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  15022. };
  15023. break;
  15024. }
  15025. return bodyParameters;
  15026. };
  15027. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  15028. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15029. var registeredMesh = this._registeredMeshes[index];
  15030. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  15031. if (registeredMesh.body) {
  15032. this._world.removeRigidBody(registeredMesh.body.body);
  15033. this._unbindBody(registeredMesh.body);
  15034. }
  15035. this._registeredMeshes.splice(index, 1);
  15036. return;
  15037. }
  15038. }
  15039. };
  15040. OimoJSPlugin.prototype._unbindBody = function (body) {
  15041. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15042. var registeredMesh = this._registeredMeshes[index];
  15043. if (registeredMesh.body === body) {
  15044. registeredMesh.body = null;
  15045. }
  15046. }
  15047. };
  15048. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  15049. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15050. var registeredMesh = this._registeredMeshes[index];
  15051. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  15052. var mass = registeredMesh.body.body.massInfo.mass;
  15053. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  15054. return;
  15055. }
  15056. }
  15057. };
  15058. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  15059. var body1 = null, body2 = null;
  15060. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15061. var registeredMesh = this._registeredMeshes[index];
  15062. if (registeredMesh.mesh === mesh1) {
  15063. body1 = registeredMesh.body.body;
  15064. } else if (registeredMesh.mesh === mesh2) {
  15065. body2 = registeredMesh.body.body;
  15066. }
  15067. }
  15068. if (!body1 || !body2) {
  15069. return false;
  15070. }
  15071. if (!options) {
  15072. options = {};
  15073. }
  15074. new OIMO.Link({
  15075. type: options.type,
  15076. body1: body1,
  15077. body2: body2,
  15078. min: options.min,
  15079. max: options.max,
  15080. axe1: options.axe1,
  15081. axe2: options.axe2,
  15082. pos1: [pivot1.x, pivot1.y, pivot1.z],
  15083. pos2: [pivot2.x, pivot2.y, pivot2.z],
  15084. collision: options.collision,
  15085. spring: options.spring,
  15086. world: this._world
  15087. });
  15088. return true;
  15089. };
  15090. OimoJSPlugin.prototype.dispose = function () {
  15091. this._world.clear();
  15092. while (this._registeredMeshes.length) {
  15093. this.unregisterMesh(this._registeredMeshes[0].mesh);
  15094. }
  15095. };
  15096. OimoJSPlugin.prototype.isSupported = function () {
  15097. return OIMO !== undefined;
  15098. };
  15099. OimoJSPlugin.prototype._getLastShape = function (body) {
  15100. var lastShape = body.shapes;
  15101. while (lastShape.next) {
  15102. lastShape = lastShape.next;
  15103. }
  15104. return lastShape;
  15105. };
  15106. OimoJSPlugin.prototype.runOneStep = function (time) {
  15107. this._world.step();
  15108. var i = this._registeredMeshes.length;
  15109. var m;
  15110. while (i--) {
  15111. var body = this._registeredMeshes[i].body.body;
  15112. var mesh = this._registeredMeshes[i].mesh;
  15113. var delta = this._registeredMeshes[i].delta;
  15114. if (!body.sleeping) {
  15115. if (body.shapes.next) {
  15116. var parentShape = this._getLastShape(body);
  15117. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  15118. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  15119. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  15120. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  15121. if (!mesh.rotationQuaternion) {
  15122. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  15123. }
  15124. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  15125. } else {
  15126. m = body.getMatrix();
  15127. mtx = BABYLON.Matrix.FromArray(m);
  15128. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  15129. if (!delta) {
  15130. mesh.position.x = bodyX;
  15131. mesh.position.y = bodyY;
  15132. mesh.position.z = bodyZ;
  15133. } else {
  15134. mesh.position.x = bodyX + delta.x;
  15135. mesh.position.y = bodyY + delta.y;
  15136. mesh.position.z = bodyZ + delta.z;
  15137. }
  15138. if (!mesh.rotationQuaternion) {
  15139. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  15140. }
  15141. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  15142. }
  15143. }
  15144. }
  15145. };
  15146. return OimoJSPlugin;
  15147. })();
  15148. BABYLON.OimoJSPlugin = OimoJSPlugin;
  15149. })(BABYLON || (BABYLON = {}));
  15150. var BABYLON;
  15151. (function (BABYLON) {
  15152. var CannonJSPlugin = (function () {
  15153. function CannonJSPlugin() {
  15154. this._registeredMeshes = [];
  15155. this._physicsMaterials = [];
  15156. this.updateBodyPosition = function (mesh) {
  15157. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15158. var registeredMesh = this._registeredMeshes[index];
  15159. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  15160. var body = registeredMesh.body;
  15161. var center = mesh.getBoundingInfo().boundingBox.center;
  15162. body.position.set(center.x, center.z, center.y);
  15163. body.quaternion.x = mesh.rotationQuaternion.x;
  15164. body.quaternion.z = mesh.rotationQuaternion.y;
  15165. body.quaternion.y = mesh.rotationQuaternion.z;
  15166. body.quaternion.w = -mesh.rotationQuaternion.w;
  15167. return;
  15168. }
  15169. }
  15170. };
  15171. }
  15172. CannonJSPlugin.prototype.initialize = function (iterations) {
  15173. if (typeof iterations === "undefined") { iterations = 10; }
  15174. this._world = new CANNON.World();
  15175. this._world.broadphase = new CANNON.NaiveBroadphase();
  15176. this._world.solver.iterations = iterations;
  15177. };
  15178. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  15179. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  15180. };
  15181. CannonJSPlugin.prototype.runOneStep = function (delta) {
  15182. this._world.step(delta);
  15183. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15184. var registeredMesh = this._registeredMeshes[index];
  15185. if (registeredMesh.isChild) {
  15186. continue;
  15187. }
  15188. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  15189. var deltaPos = registeredMesh.delta;
  15190. if (deltaPos) {
  15191. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  15192. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  15193. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  15194. } else {
  15195. registeredMesh.mesh.position.x = bodyX;
  15196. registeredMesh.mesh.position.y = bodyZ;
  15197. registeredMesh.mesh.position.z = bodyY;
  15198. }
  15199. if (!registeredMesh.mesh.rotationQuaternion) {
  15200. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  15201. }
  15202. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  15203. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  15204. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  15205. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  15206. }
  15207. };
  15208. CannonJSPlugin.prototype.setGravity = function (gravity) {
  15209. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  15210. };
  15211. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  15212. this.unregisterMesh(mesh);
  15213. mesh.computeWorldMatrix(true);
  15214. switch (impostor) {
  15215. case BABYLON.PhysicsEngine.SphereImpostor:
  15216. var bbox = mesh.getBoundingInfo().boundingBox;
  15217. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  15218. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  15219. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  15220. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  15221. case BABYLON.PhysicsEngine.BoxImpostor:
  15222. bbox = mesh.getBoundingInfo().boundingBox;
  15223. var min = bbox.minimumWorld;
  15224. var max = bbox.maximumWorld;
  15225. var box = max.subtract(min).scale(0.5);
  15226. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  15227. case BABYLON.PhysicsEngine.PlaneImpostor:
  15228. return this._createPlane(mesh, options);
  15229. case BABYLON.PhysicsEngine.MeshImpostor:
  15230. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15231. var rawFaces = mesh.getIndices();
  15232. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  15233. }
  15234. return null;
  15235. };
  15236. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  15237. var shape = new CANNON.Sphere(radius);
  15238. if (!options) {
  15239. return shape;
  15240. }
  15241. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  15242. };
  15243. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  15244. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  15245. if (!options) {
  15246. return shape;
  15247. }
  15248. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  15249. };
  15250. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  15251. var shape = new CANNON.Plane();
  15252. if (!options) {
  15253. return shape;
  15254. }
  15255. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  15256. };
  15257. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  15258. var verts = [], faces = [];
  15259. mesh.computeWorldMatrix(true);
  15260. for (var i = 0; i < rawVerts.length; i += 3) {
  15261. var transformed = BABYLON.Vector3.Zero();
  15262. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  15263. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  15264. }
  15265. for (var j = 0; j < rawFaces.length; j += 3) {
  15266. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  15267. }
  15268. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  15269. if (!options) {
  15270. return shape;
  15271. }
  15272. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  15273. };
  15274. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  15275. var index;
  15276. var mat;
  15277. for (index = 0; index < this._physicsMaterials.length; index++) {
  15278. mat = this._physicsMaterials[index];
  15279. if (mat.friction === friction && mat.restitution === restitution) {
  15280. return mat;
  15281. }
  15282. }
  15283. var currentMat = new CANNON.Material();
  15284. currentMat.friction = friction;
  15285. currentMat.restitution = restitution;
  15286. this._physicsMaterials.push(currentMat);
  15287. for (index = 0; index < this._physicsMaterials.length; index++) {
  15288. mat = this._physicsMaterials[index];
  15289. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  15290. contactMaterial.contactEquationStiffness = 1e10;
  15291. contactMaterial.contactEquationRegularizationTime = 10;
  15292. this._world.addContactMaterial(contactMaterial);
  15293. }
  15294. return currentMat;
  15295. };
  15296. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  15297. var initialRotation = null;
  15298. if (mesh.rotationQuaternion) {
  15299. initialRotation = mesh.rotationQuaternion.clone();
  15300. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  15301. }
  15302. var bbox = mesh.getBoundingInfo().boundingBox;
  15303. var deltaPosition = mesh.position.subtract(bbox.center);
  15304. var material = this._addMaterial(friction, restitution);
  15305. var body = new CANNON.RigidBody(mass, shape, material);
  15306. if (initialRotation) {
  15307. body.quaternion.x = initialRotation.x;
  15308. body.quaternion.z = initialRotation.y;
  15309. body.quaternion.y = initialRotation.z;
  15310. body.quaternion.w = -initialRotation.w;
  15311. }
  15312. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  15313. this._world.add(body);
  15314. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  15315. return body;
  15316. };
  15317. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  15318. var compoundShape = new CANNON.Compound();
  15319. for (var index = 0; index < parts.length; index++) {
  15320. var mesh = parts[index].mesh;
  15321. var shape = this.registerMesh(mesh, parts[index].impostor);
  15322. if (index == 0) {
  15323. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  15324. } else {
  15325. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  15326. }
  15327. }
  15328. var initialMesh = parts[0].mesh;
  15329. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  15330. body.parts = parts;
  15331. return body;
  15332. };
  15333. CannonJSPlugin.prototype._unbindBody = function (body) {
  15334. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15335. var registeredMesh = this._registeredMeshes[index];
  15336. if (registeredMesh.body === body) {
  15337. registeredMesh.body = null;
  15338. registeredMesh.delta = 0;
  15339. }
  15340. }
  15341. };
  15342. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  15343. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15344. var registeredMesh = this._registeredMeshes[index];
  15345. if (registeredMesh.mesh === mesh) {
  15346. if (registeredMesh.body) {
  15347. this._world.remove(registeredMesh.body);
  15348. this._unbindBody(registeredMesh.body);
  15349. }
  15350. this._registeredMeshes.splice(index, 1);
  15351. return;
  15352. }
  15353. }
  15354. };
  15355. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  15356. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  15357. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  15358. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15359. var registeredMesh = this._registeredMeshes[index];
  15360. if (registeredMesh.mesh === mesh) {
  15361. registeredMesh.body.applyImpulse(impulse, worldPoint);
  15362. return;
  15363. }
  15364. }
  15365. };
  15366. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  15367. var body1 = null, body2 = null;
  15368. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15369. var registeredMesh = this._registeredMeshes[index];
  15370. if (registeredMesh.mesh === mesh1) {
  15371. body1 = registeredMesh.body;
  15372. } else if (registeredMesh.mesh === mesh2) {
  15373. body2 = registeredMesh.body;
  15374. }
  15375. }
  15376. if (!body1 || !body2) {
  15377. return false;
  15378. }
  15379. 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));
  15380. this._world.addConstraint(constraint);
  15381. return true;
  15382. };
  15383. CannonJSPlugin.prototype.dispose = function () {
  15384. while (this._registeredMeshes.length) {
  15385. this.unregisterMesh(this._registeredMeshes[0].mesh);
  15386. }
  15387. };
  15388. CannonJSPlugin.prototype.isSupported = function () {
  15389. return window.CANNON !== undefined;
  15390. };
  15391. return CannonJSPlugin;
  15392. })();
  15393. BABYLON.CannonJSPlugin = CannonJSPlugin;
  15394. })(BABYLON || (BABYLON = {}));
  15395. var BABYLON;
  15396. (function (BABYLON) {
  15397. var PhysicsEngine = (function () {
  15398. function PhysicsEngine(plugin) {
  15399. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  15400. }
  15401. PhysicsEngine.prototype._initialize = function (gravity) {
  15402. this._currentPlugin.initialize();
  15403. this._setGravity(gravity);
  15404. };
  15405. PhysicsEngine.prototype._runOneStep = function (delta) {
  15406. if (delta > 0.1) {
  15407. delta = 0.1;
  15408. } else if (delta <= 0) {
  15409. delta = 1.0 / 60.0;
  15410. }
  15411. this._currentPlugin.runOneStep(delta);
  15412. };
  15413. PhysicsEngine.prototype._setGravity = function (gravity) {
  15414. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  15415. this._currentPlugin.setGravity(this.gravity);
  15416. };
  15417. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  15418. return this._currentPlugin.registerMesh(mesh, impostor, options);
  15419. };
  15420. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  15421. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  15422. };
  15423. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  15424. this._currentPlugin.unregisterMesh(mesh);
  15425. };
  15426. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  15427. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  15428. };
  15429. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  15430. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  15431. };
  15432. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  15433. this._currentPlugin.updateBodyPosition(mesh);
  15434. };
  15435. PhysicsEngine.prototype.dispose = function () {
  15436. this._currentPlugin.dispose();
  15437. };
  15438. PhysicsEngine.prototype.isSupported = function () {
  15439. return this._currentPlugin.isSupported();
  15440. };
  15441. PhysicsEngine.NoImpostor = 0;
  15442. PhysicsEngine.SphereImpostor = 1;
  15443. PhysicsEngine.BoxImpostor = 2;
  15444. PhysicsEngine.PlaneImpostor = 3;
  15445. PhysicsEngine.MeshImpostor = 4;
  15446. PhysicsEngine.CapsuleImpostor = 5;
  15447. PhysicsEngine.ConeImpostor = 6;
  15448. PhysicsEngine.CylinderImpostor = 7;
  15449. PhysicsEngine.ConvexHullImpostor = 8;
  15450. PhysicsEngine.Epsilon = 0.001;
  15451. return PhysicsEngine;
  15452. })();
  15453. BABYLON.PhysicsEngine = PhysicsEngine;
  15454. })(BABYLON || (BABYLON = {}));
  15455. var BABYLON;
  15456. (function (BABYLON) {
  15457. var serializeLight = function (light) {
  15458. var serializationObject = {};
  15459. serializationObject.name = light.name;
  15460. serializationObject.id = light.id;
  15461. serializationObject.tags = BABYLON.Tags.GetTags(light);
  15462. if (light instanceof BABYLON.PointLight) {
  15463. serializationObject.type = 0;
  15464. serializationObject.position = light.position.asArray();
  15465. } else if (light instanceof BABYLON.DirectionalLight) {
  15466. serializationObject.type = 1;
  15467. var directionalLight = light;
  15468. serializationObject.position = directionalLight.position.asArray();
  15469. serializationObject.direction = directionalLight.direction.asArray();
  15470. } else if (light instanceof BABYLON.SpotLight) {
  15471. serializationObject.type = 2;
  15472. var spotLight = light;
  15473. serializationObject.position = spotLight.position.asArray();
  15474. serializationObject.direction = spotLight.position.asArray();
  15475. serializationObject.angle = spotLight.angle;
  15476. serializationObject.exponent = spotLight.exponent;
  15477. } else if (light instanceof BABYLON.HemisphericLight) {
  15478. serializationObject.type = 3;
  15479. var hemisphericLight = light;
  15480. serializationObject.direction = hemisphericLight.direction.asArray();
  15481. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  15482. }
  15483. if (light.intensity) {
  15484. serializationObject.intensity = light.intensity;
  15485. }
  15486. serializationObject.range = light.range;
  15487. serializationObject.diffuse = light.diffuse.asArray();
  15488. serializationObject.specular = light.specular.asArray();
  15489. return serializationObject;
  15490. };
  15491. var serializeFresnelParameter = function (fresnelParameter) {
  15492. var serializationObject = {};
  15493. serializationObject.isEnabled = fresnelParameter.isEnabled;
  15494. serializationObject.leftColor = fresnelParameter.leftColor;
  15495. serializationObject.rightColor = fresnelParameter.rightColor;
  15496. serializationObject.bias = fresnelParameter.bias;
  15497. serializationObject.power = fresnelParameter.power;
  15498. return serializationObject;
  15499. };
  15500. var serializeCamera = function (camera) {
  15501. var serializationObject = {};
  15502. serializationObject.name = camera.name;
  15503. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  15504. serializationObject.id = camera.id;
  15505. serializationObject.position = camera.position.asArray();
  15506. if (camera.parent) {
  15507. serializationObject.parentId = camera.parent.id;
  15508. }
  15509. serializationObject.rotation = camera.rotation.asArray();
  15510. if (camera.lockedTarget && camera.lockedTarget.id) {
  15511. serializationObject.lockedTargetId = camera.lockedTarget.id;
  15512. }
  15513. serializationObject.fov = camera.fov;
  15514. serializationObject.minZ = camera.minZ;
  15515. serializationObject.maxZ = camera.maxZ;
  15516. serializationObject.speed = camera.speed;
  15517. serializationObject.inertia = camera.inertia;
  15518. serializationObject.checkCollisions = camera.checkCollisions;
  15519. serializationObject.applyGravity = camera.applyGravity;
  15520. if (camera.ellipsoid) {
  15521. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  15522. }
  15523. appendAnimations(camera, serializationObject);
  15524. serializationObject.layerMask = camera.layerMask;
  15525. return serializationObject;
  15526. };
  15527. var appendAnimations = function (source, destination) {
  15528. if (source.animations) {
  15529. destination.animations = [];
  15530. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  15531. var animation = source.animations[animationIndex];
  15532. destination.animations.push(serializeAnimation(animation));
  15533. }
  15534. }
  15535. };
  15536. var serializeAnimation = function (animation) {
  15537. var serializationObject = {};
  15538. serializationObject.name = animation.name;
  15539. serializationObject.property = animation.targetProperty;
  15540. serializationObject.framePerSecond = animation.framePerSecond;
  15541. serializationObject.dataType = animation.dataType;
  15542. serializationObject.loopBehavior = animation.loopMode;
  15543. var dataType = animation.dataType;
  15544. serializationObject.keys = [];
  15545. var keys = animation.getKeys();
  15546. for (var index = 0; index < keys.length; index++) {
  15547. var animationKey = keys[index];
  15548. var key = {};
  15549. key.frame = animationKey.frame;
  15550. switch (dataType) {
  15551. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  15552. key.values = [animationKey.value];
  15553. break;
  15554. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  15555. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  15556. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  15557. key.values = animationKey.value.asArray();
  15558. break;
  15559. }
  15560. serializationObject.keys.push(key);
  15561. }
  15562. return serializationObject;
  15563. };
  15564. var serializeMultiMaterial = function (material) {
  15565. var serializationObject = {};
  15566. serializationObject.name = material.name;
  15567. serializationObject.id = material.id;
  15568. serializationObject.tags = BABYLON.Tags.GetTags(material);
  15569. serializationObject.materials = [];
  15570. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  15571. var subMat = material.subMaterials[matIndex];
  15572. if (subMat) {
  15573. serializationObject.materials.push(subMat.id);
  15574. } else {
  15575. serializationObject.materials.push(null);
  15576. }
  15577. }
  15578. return serializationObject;
  15579. };
  15580. var serializeMaterial = function (material) {
  15581. var serializationObject = {};
  15582. serializationObject.name = material.name;
  15583. serializationObject.ambient = material.ambientColor.asArray();
  15584. serializationObject.diffuse = material.diffuseColor.asArray();
  15585. serializationObject.specular = material.specularColor.asArray();
  15586. serializationObject.specularPower = material.specularPower;
  15587. serializationObject.emissive = material.emissiveColor.asArray();
  15588. serializationObject.alpha = material.alpha;
  15589. serializationObject.id = material.id;
  15590. serializationObject.tags = BABYLON.Tags.GetTags(material);
  15591. serializationObject.backFaceCulling = material.backFaceCulling;
  15592. if (material.diffuseTexture) {
  15593. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  15594. }
  15595. if (material.diffuseFresnelParameters) {
  15596. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  15597. }
  15598. if (material.ambientTexture) {
  15599. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  15600. }
  15601. if (material.opacityTexture) {
  15602. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  15603. }
  15604. if (material.opacityFresnelParameters) {
  15605. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  15606. }
  15607. if (material.reflectionTexture) {
  15608. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  15609. }
  15610. if (material.reflectionFresnelParameters) {
  15611. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  15612. }
  15613. if (material.emissiveTexture) {
  15614. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  15615. }
  15616. if (material.emissiveFresnelParameters) {
  15617. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  15618. }
  15619. if (material.specularTexture) {
  15620. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  15621. }
  15622. if (material.bumpTexture) {
  15623. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  15624. }
  15625. return serializationObject;
  15626. };
  15627. var serializeTexture = function (texture) {
  15628. var serializationObject = {};
  15629. if (!texture.name) {
  15630. return null;
  15631. }
  15632. if (texture instanceof BABYLON.CubeTexture) {
  15633. serializationObject.name = texture.name;
  15634. serializationObject.hasAlpha = texture.hasAlpha;
  15635. serializationObject.level = texture.level;
  15636. serializationObject.coordinatesMode = texture.coordinatesMode;
  15637. return serializationObject;
  15638. }
  15639. if (texture instanceof BABYLON.MirrorTexture) {
  15640. var mirrorTexture = texture;
  15641. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  15642. serializationObject.renderList = [];
  15643. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  15644. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  15645. }
  15646. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  15647. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  15648. var renderTargetTexture = texture;
  15649. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  15650. serializationObject.renderList = [];
  15651. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  15652. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  15653. }
  15654. }
  15655. var regularTexture = texture;
  15656. serializationObject.name = texture.name;
  15657. serializationObject.hasAlpha = texture.hasAlpha;
  15658. serializationObject.level = texture.level;
  15659. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  15660. serializationObject.coordinatesMode = texture.coordinatesMode;
  15661. serializationObject.uOffset = regularTexture.uOffset;
  15662. serializationObject.vOffset = regularTexture.vOffset;
  15663. serializationObject.uScale = regularTexture.uScale;
  15664. serializationObject.vScale = regularTexture.vScale;
  15665. serializationObject.uAng = regularTexture.uAng;
  15666. serializationObject.vAng = regularTexture.vAng;
  15667. serializationObject.wAng = regularTexture.wAng;
  15668. serializationObject.wrapU = texture.wrapU;
  15669. serializationObject.wrapV = texture.wrapV;
  15670. appendAnimations(texture, serializationObject);
  15671. return serializationObject;
  15672. };
  15673. var serializeSkeleton = function (skeleton) {
  15674. var serializationObject = {};
  15675. serializationObject.name = skeleton.name;
  15676. serializationObject.id = skeleton.id;
  15677. serializationObject.bones = [];
  15678. for (var index = 0; index < skeleton.bones.length; index++) {
  15679. var bone = skeleton.bones[index];
  15680. var serializedBone = {
  15681. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  15682. name: bone.name,
  15683. matrix: bone.getLocalMatrix().toArray()
  15684. };
  15685. serializationObject.bones.push(serializedBone);
  15686. if (bone.animations && bone.animations.length > 0) {
  15687. serializedBone.animation = serializeAnimation(bone.animations[0]);
  15688. }
  15689. }
  15690. return serializationObject;
  15691. };
  15692. var serializeParticleSystem = function (particleSystem) {
  15693. var serializationObject = {};
  15694. serializationObject.emitterId = particleSystem.emitter.id;
  15695. serializationObject.capacity = particleSystem.getCapacity();
  15696. if (particleSystem.particleTexture) {
  15697. serializationObject.textureName = particleSystem.particleTexture.name;
  15698. }
  15699. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  15700. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  15701. serializationObject.minSize = particleSystem.minSize;
  15702. serializationObject.maxSize = particleSystem.maxSize;
  15703. serializationObject.minLifeTime = particleSystem.minLifeTime;
  15704. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  15705. serializationObject.emitRate = particleSystem.emitRate;
  15706. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  15707. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  15708. serializationObject.gravity = particleSystem.gravity.asArray();
  15709. serializationObject.direction1 = particleSystem.direction1.asArray();
  15710. serializationObject.direction2 = particleSystem.direction2.asArray();
  15711. serializationObject.color1 = particleSystem.color1.asArray();
  15712. serializationObject.color2 = particleSystem.color2.asArray();
  15713. serializationObject.colorDead = particleSystem.colorDead.asArray();
  15714. serializationObject.updateSpeed = particleSystem.updateSpeed;
  15715. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  15716. serializationObject.textureMask = particleSystem.textureMask.asArray();
  15717. serializationObject.blendMode = particleSystem.blendMode;
  15718. return serializationObject;
  15719. };
  15720. var serializeLensFlareSystem = function (lensFlareSystem) {
  15721. var serializationObject = {};
  15722. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  15723. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  15724. serializationObject.flares = [];
  15725. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  15726. var flare = lensFlareSystem.lensFlares[index];
  15727. serializationObject.flares.push({
  15728. size: flare.size,
  15729. position: flare.position,
  15730. color: flare.color.asArray(),
  15731. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  15732. });
  15733. }
  15734. return serializationObject;
  15735. };
  15736. var serializeShadowGenerator = function (light) {
  15737. var serializationObject = {};
  15738. var shadowGenerator = light.getShadowGenerator();
  15739. serializationObject.lightId = light.id;
  15740. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  15741. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  15742. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  15743. serializationObject.renderList = [];
  15744. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  15745. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  15746. serializationObject.renderList.push(mesh.id);
  15747. }
  15748. return serializationObject;
  15749. };
  15750. var serializedGeometries = [];
  15751. var serializeGeometry = function (geometry, serializationGeometries) {
  15752. if (serializedGeometries[geometry.id]) {
  15753. return;
  15754. }
  15755. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  15756. serializationGeometries.boxes.push(serializeBox(geometry));
  15757. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  15758. serializationGeometries.spheres.push(serializeSphere(geometry));
  15759. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  15760. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  15761. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  15762. serializationGeometries.toruses.push(serializeTorus(geometry));
  15763. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  15764. serializationGeometries.grounds.push(serializeGround(geometry));
  15765. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  15766. serializationGeometries.planes.push(serializePlane(geometry));
  15767. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  15768. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  15769. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  15770. throw new Error("Unknow primitive type");
  15771. } else {
  15772. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  15773. }
  15774. serializedGeometries[geometry.id] = true;
  15775. };
  15776. var serializeGeometryBase = function (geometry) {
  15777. var serializationObject = {};
  15778. serializationObject.id = geometry.id;
  15779. if (BABYLON.Tags.HasTags(geometry)) {
  15780. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  15781. }
  15782. return serializationObject;
  15783. };
  15784. var serializeVertexData = function (vertexData) {
  15785. var serializationObject = serializeGeometryBase(vertexData);
  15786. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15787. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15788. }
  15789. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15790. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15791. }
  15792. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15793. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15794. }
  15795. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  15796. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  15797. }
  15798. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  15799. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  15800. }
  15801. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15802. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15803. serializationObject.matricesIndices._isExpanded = true;
  15804. }
  15805. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15806. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15807. }
  15808. serializationObject.indices = vertexData.getIndices();
  15809. return serializationObject;
  15810. };
  15811. var serializePrimitive = function (primitive) {
  15812. var serializationObject = serializeGeometryBase(primitive);
  15813. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  15814. return serializationObject;
  15815. };
  15816. var serializeBox = function (box) {
  15817. var serializationObject = serializePrimitive(box);
  15818. serializationObject.size = box.size;
  15819. return serializationObject;
  15820. };
  15821. var serializeSphere = function (sphere) {
  15822. var serializationObject = serializePrimitive(sphere);
  15823. serializationObject.segments = sphere.segments;
  15824. serializationObject.diameter = sphere.diameter;
  15825. return serializationObject;
  15826. };
  15827. var serializeCylinder = function (cylinder) {
  15828. var serializationObject = serializePrimitive(cylinder);
  15829. serializationObject.height = cylinder.height;
  15830. serializationObject.diameterTop = cylinder.diameterTop;
  15831. serializationObject.diameterBottom = cylinder.diameterBottom;
  15832. serializationObject.tessellation = cylinder.tessellation;
  15833. return serializationObject;
  15834. };
  15835. var serializeTorus = function (torus) {
  15836. var serializationObject = serializePrimitive(torus);
  15837. serializationObject.diameter = torus.diameter;
  15838. serializationObject.thickness = torus.thickness;
  15839. serializationObject.tessellation = torus.tessellation;
  15840. return serializationObject;
  15841. };
  15842. var serializeGround = function (ground) {
  15843. var serializationObject = serializePrimitive(ground);
  15844. serializationObject.width = ground.width;
  15845. serializationObject.height = ground.height;
  15846. serializationObject.subdivisions = ground.subdivisions;
  15847. return serializationObject;
  15848. };
  15849. var serializePlane = function (plane) {
  15850. var serializationObject = serializePrimitive(plane);
  15851. serializationObject.size = plane.size;
  15852. return serializationObject;
  15853. };
  15854. var serializeTorusKnot = function (torusKnot) {
  15855. var serializationObject = serializePrimitive(torusKnot);
  15856. serializationObject.radius = torusKnot.radius;
  15857. serializationObject.tube = torusKnot.tube;
  15858. serializationObject.radialSegments = torusKnot.radialSegments;
  15859. serializationObject.tubularSegments = torusKnot.tubularSegments;
  15860. serializationObject.p = torusKnot.p;
  15861. serializationObject.q = torusKnot.q;
  15862. return serializationObject;
  15863. };
  15864. var serializeMesh = function (mesh, serializationScene) {
  15865. var serializationObject = {};
  15866. serializationObject.name = mesh.name;
  15867. serializationObject.id = mesh.id;
  15868. if (BABYLON.Tags.HasTags(mesh)) {
  15869. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  15870. }
  15871. serializationObject.position = mesh.position.asArray();
  15872. if (mesh.rotationQuaternion) {
  15873. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  15874. } else if (mesh.rotation) {
  15875. serializationObject.rotation = mesh.rotation.asArray();
  15876. }
  15877. serializationObject.scaling = mesh.scaling.asArray();
  15878. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  15879. serializationObject.isEnabled = mesh.isEnabled();
  15880. serializationObject.isVisible = mesh.isVisible;
  15881. serializationObject.infiniteDistance = mesh.infiniteDistance;
  15882. serializationObject.pickable = mesh.isPickable;
  15883. serializationObject.receiveShadows = mesh.receiveShadows;
  15884. serializationObject.billboardMode = mesh.billboardMode;
  15885. serializationObject.visibility = mesh.visibility;
  15886. serializationObject.checkCollisions = mesh.checkCollisions;
  15887. if (mesh.parent) {
  15888. serializationObject.parentId = mesh.parent.id;
  15889. }
  15890. var geometry = mesh._geometry;
  15891. if (geometry) {
  15892. var geometryId = geometry.id;
  15893. serializationObject.geometryId = geometryId;
  15894. if (!mesh.getScene().getGeometryByID(geometryId)) {
  15895. serializeGeometry(geometry, serializationScene.geometries);
  15896. }
  15897. serializationObject.subMeshes = [];
  15898. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  15899. var subMesh = mesh.subMeshes[subIndex];
  15900. serializationObject.subMeshes.push({
  15901. materialIndex: subMesh.materialIndex,
  15902. verticesStart: subMesh.verticesStart,
  15903. verticesCount: subMesh.verticesCount,
  15904. indexStart: subMesh.indexStart,
  15905. indexCount: subMesh.indexCount
  15906. });
  15907. }
  15908. }
  15909. if (mesh.material) {
  15910. serializationObject.materialId = mesh.material.id;
  15911. } else {
  15912. mesh.material = null;
  15913. }
  15914. if (mesh.skeleton) {
  15915. serializationObject.skeletonId = mesh.skeleton.id;
  15916. }
  15917. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  15918. serializationObject.physicsMass = mesh.getPhysicsMass();
  15919. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  15920. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  15921. switch (mesh.getPhysicsImpostor()) {
  15922. case BABYLON.PhysicsEngine.BoxImpostor:
  15923. serializationObject.physicsImpostor = 1;
  15924. break;
  15925. case BABYLON.PhysicsEngine.SphereImpostor:
  15926. serializationObject.physicsImpostor = 2;
  15927. break;
  15928. }
  15929. }
  15930. serializationObject.instances = [];
  15931. for (var index = 0; index < mesh.instances.length; index++) {
  15932. var instance = mesh.instances[index];
  15933. var serializationInstance = {
  15934. name: instance.name,
  15935. position: instance.position,
  15936. rotation: instance.rotation,
  15937. rotationQuaternion: instance.rotationQuaternion,
  15938. scaling: instance.scaling
  15939. };
  15940. serializationObject.instances.push(serializationInstance);
  15941. appendAnimations(instance, serializationInstance);
  15942. }
  15943. appendAnimations(mesh, serializationObject);
  15944. serializationObject.layerMask = mesh.layerMask;
  15945. return serializationObject;
  15946. };
  15947. var SceneSerializer = (function () {
  15948. function SceneSerializer() {
  15949. }
  15950. SceneSerializer.Serialize = function (scene) {
  15951. var serializationObject = {};
  15952. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  15953. serializationObject.autoClear = scene.autoClear;
  15954. serializationObject.clearColor = scene.clearColor.asArray();
  15955. serializationObject.ambientColor = scene.ambientColor.asArray();
  15956. serializationObject.gravity = scene.gravity.asArray();
  15957. if (scene.fogMode && scene.fogMode !== 0) {
  15958. serializationObject.fogMode = scene.fogMode;
  15959. serializationObject.fogColor = scene.fogColor.asArray();
  15960. serializationObject.fogStart = scene.fogStart;
  15961. serializationObject.fogEnd = scene.fogEnd;
  15962. serializationObject.fogDensity = scene.fogDensity;
  15963. }
  15964. serializationObject.lights = [];
  15965. for (var index = 0; index < scene.lights.length; index++) {
  15966. var light = scene.lights[index];
  15967. serializationObject.lights.push(serializeLight(light));
  15968. }
  15969. serializationObject.cameras = [];
  15970. for (index = 0; index < scene.cameras.length; index++) {
  15971. var camera = scene.cameras[index];
  15972. if (camera instanceof BABYLON.FreeCamera) {
  15973. serializationObject.cameras.push(serializeCamera(camera));
  15974. }
  15975. }
  15976. if (scene.activeCamera) {
  15977. serializationObject.activeCameraID = scene.activeCamera.id;
  15978. }
  15979. serializationObject.materials = [];
  15980. serializationObject.multiMaterials = [];
  15981. for (index = 0; index < scene.materials.length; index++) {
  15982. var material = scene.materials[index];
  15983. if (material instanceof BABYLON.StandardMaterial) {
  15984. serializationObject.materials.push(serializeMaterial(material));
  15985. } else if (material instanceof BABYLON.MultiMaterial) {
  15986. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  15987. }
  15988. }
  15989. serializationObject.skeletons = [];
  15990. for (index = 0; index < scene.skeletons.length; index++) {
  15991. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  15992. }
  15993. serializationObject.geometries = {};
  15994. serializationObject.geometries.boxes = [];
  15995. serializationObject.geometries.spheres = [];
  15996. serializationObject.geometries.cylinders = [];
  15997. serializationObject.geometries.toruses = [];
  15998. serializationObject.geometries.grounds = [];
  15999. serializationObject.geometries.planes = [];
  16000. serializationObject.geometries.torusKnots = [];
  16001. serializationObject.geometries.vertexData = [];
  16002. serializedGeometries = [];
  16003. var geometries = scene.getGeometries();
  16004. for (var index = 0; index < geometries.length; index++) {
  16005. var geometry = geometries[index];
  16006. if (geometry.isReady()) {
  16007. serializeGeometry(geometry, serializationObject.geometries);
  16008. }
  16009. }
  16010. serializationObject.meshes = [];
  16011. for (index = 0; index < scene.meshes.length; index++) {
  16012. var abstractMesh = scene.meshes[index];
  16013. if (abstractMesh instanceof BABYLON.Mesh) {
  16014. var mesh = abstractMesh;
  16015. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  16016. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  16017. }
  16018. }
  16019. }
  16020. serializationObject.particleSystems = [];
  16021. for (index = 0; index < scene.particleSystems.length; index++) {
  16022. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  16023. }
  16024. serializationObject.lensFlareSystems = [];
  16025. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  16026. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  16027. }
  16028. serializationObject.shadowGenerators = [];
  16029. for (index = 0; index < scene.lights.length; index++) {
  16030. light = scene.lights[index];
  16031. if (light.getShadowGenerator()) {
  16032. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  16033. }
  16034. }
  16035. return serializationObject;
  16036. };
  16037. return SceneSerializer;
  16038. })();
  16039. BABYLON.SceneSerializer = SceneSerializer;
  16040. })(BABYLON || (BABYLON = {}));
  16041. var BABYLON;
  16042. (function (BABYLON) {
  16043. var currentCSGMeshId = 0;
  16044. var Vertex = (function () {
  16045. function Vertex(pos, normal, uv) {
  16046. this.pos = pos;
  16047. this.normal = normal;
  16048. this.uv = uv;
  16049. }
  16050. Vertex.prototype.clone = function () {
  16051. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  16052. };
  16053. Vertex.prototype.flip = function () {
  16054. this.normal = this.normal.scale(-1);
  16055. };
  16056. Vertex.prototype.interpolate = function (other, t) {
  16057. 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));
  16058. };
  16059. return Vertex;
  16060. })();
  16061. var Plane = (function () {
  16062. function Plane(normal, w) {
  16063. this.normal = normal;
  16064. this.w = w;
  16065. }
  16066. Plane.FromPoints = function (a, b, c) {
  16067. var v0 = c.subtract(a);
  16068. var v1 = b.subtract(a);
  16069. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  16070. return null;
  16071. }
  16072. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  16073. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  16074. };
  16075. Plane.prototype.clone = function () {
  16076. return new Plane(this.normal.clone(), this.w);
  16077. };
  16078. Plane.prototype.flip = function () {
  16079. this.normal.scaleInPlace(-1);
  16080. this.w = -this.w;
  16081. };
  16082. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  16083. var COPLANAR = 0;
  16084. var FRONT = 1;
  16085. var BACK = 2;
  16086. var SPANNING = 3;
  16087. var polygonType = 0;
  16088. var types = [];
  16089. for (var i = 0; i < polygon.vertices.length; i++) {
  16090. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  16091. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  16092. polygonType |= type;
  16093. types.push(type);
  16094. }
  16095. switch (polygonType) {
  16096. case COPLANAR:
  16097. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  16098. break;
  16099. case FRONT:
  16100. front.push(polygon);
  16101. break;
  16102. case BACK:
  16103. back.push(polygon);
  16104. break;
  16105. case SPANNING:
  16106. var f = [], b = [];
  16107. for (i = 0; i < polygon.vertices.length; i++) {
  16108. var j = (i + 1) % polygon.vertices.length;
  16109. var ti = types[i], tj = types[j];
  16110. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  16111. if (ti != BACK)
  16112. f.push(vi);
  16113. if (ti != FRONT)
  16114. b.push(ti != BACK ? vi.clone() : vi);
  16115. if ((ti | tj) == SPANNING) {
  16116. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  16117. var v = vi.interpolate(vj, t);
  16118. f.push(v);
  16119. b.push(v.clone());
  16120. }
  16121. }
  16122. if (f.length >= 3) {
  16123. var poly = new Polygon(f, polygon.shared);
  16124. if (poly.plane)
  16125. front.push(poly);
  16126. }
  16127. if (b.length >= 3) {
  16128. poly = new Polygon(b, polygon.shared);
  16129. if (poly.plane)
  16130. back.push(poly);
  16131. }
  16132. break;
  16133. }
  16134. };
  16135. Plane.EPSILON = 1e-5;
  16136. return Plane;
  16137. })();
  16138. var Polygon = (function () {
  16139. function Polygon(vertices, shared) {
  16140. this.vertices = vertices;
  16141. this.shared = shared;
  16142. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  16143. }
  16144. Polygon.prototype.clone = function () {
  16145. var vertices = this.vertices.map(function (v) {
  16146. return v.clone();
  16147. });
  16148. return new Polygon(vertices, this.shared);
  16149. };
  16150. Polygon.prototype.flip = function () {
  16151. this.vertices.reverse().map(function (v) {
  16152. v.flip();
  16153. });
  16154. this.plane.flip();
  16155. };
  16156. return Polygon;
  16157. })();
  16158. var Node = (function () {
  16159. function Node(polygons) {
  16160. this.plane = null;
  16161. this.front = null;
  16162. this.back = null;
  16163. this.polygons = [];
  16164. if (polygons) {
  16165. this.build(polygons);
  16166. }
  16167. }
  16168. Node.prototype.clone = function () {
  16169. var node = new Node();
  16170. node.plane = this.plane && this.plane.clone();
  16171. node.front = this.front && this.front.clone();
  16172. node.back = this.back && this.back.clone();
  16173. node.polygons = this.polygons.map(function (p) {
  16174. return p.clone();
  16175. });
  16176. return node;
  16177. };
  16178. Node.prototype.invert = function () {
  16179. for (var i = 0; i < this.polygons.length; i++) {
  16180. this.polygons[i].flip();
  16181. }
  16182. if (this.plane) {
  16183. this.plane.flip();
  16184. }
  16185. if (this.front) {
  16186. this.front.invert();
  16187. }
  16188. if (this.back) {
  16189. this.back.invert();
  16190. }
  16191. var temp = this.front;
  16192. this.front = this.back;
  16193. this.back = temp;
  16194. };
  16195. Node.prototype.clipPolygons = function (polygons) {
  16196. if (!this.plane)
  16197. return polygons.slice();
  16198. var front = [], back = [];
  16199. for (var i = 0; i < polygons.length; i++) {
  16200. this.plane.splitPolygon(polygons[i], front, back, front, back);
  16201. }
  16202. if (this.front) {
  16203. front = this.front.clipPolygons(front);
  16204. }
  16205. if (this.back) {
  16206. back = this.back.clipPolygons(back);
  16207. } else {
  16208. back = [];
  16209. }
  16210. return front.concat(back);
  16211. };
  16212. Node.prototype.clipTo = function (bsp) {
  16213. this.polygons = bsp.clipPolygons(this.polygons);
  16214. if (this.front)
  16215. this.front.clipTo(bsp);
  16216. if (this.back)
  16217. this.back.clipTo(bsp);
  16218. };
  16219. Node.prototype.allPolygons = function () {
  16220. var polygons = this.polygons.slice();
  16221. if (this.front)
  16222. polygons = polygons.concat(this.front.allPolygons());
  16223. if (this.back)
  16224. polygons = polygons.concat(this.back.allPolygons());
  16225. return polygons;
  16226. };
  16227. Node.prototype.build = function (polygons) {
  16228. if (!polygons.length)
  16229. return;
  16230. if (!this.plane)
  16231. this.plane = polygons[0].plane.clone();
  16232. var front = [], back = [];
  16233. for (var i = 0; i < polygons.length; i++) {
  16234. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  16235. }
  16236. if (front.length) {
  16237. if (!this.front)
  16238. this.front = new Node();
  16239. this.front.build(front);
  16240. }
  16241. if (back.length) {
  16242. if (!this.back)
  16243. this.back = new Node();
  16244. this.back.build(back);
  16245. }
  16246. };
  16247. return Node;
  16248. })();
  16249. var CSG = (function () {
  16250. function CSG() {
  16251. this.polygons = new Array();
  16252. }
  16253. CSG.FromMesh = function (mesh) {
  16254. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  16255. if (mesh instanceof BABYLON.Mesh) {
  16256. mesh.computeWorldMatrix(true);
  16257. var matrix = mesh.getWorldMatrix();
  16258. var meshPosition = mesh.position.clone();
  16259. var meshRotation = mesh.rotation.clone();
  16260. var meshScaling = mesh.scaling.clone();
  16261. } else {
  16262. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  16263. }
  16264. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16265. var subMeshes = mesh.subMeshes;
  16266. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  16267. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  16268. vertices = [];
  16269. for (var j = 0; j < 3; j++) {
  16270. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  16271. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  16272. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  16273. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  16274. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  16275. vertex = new Vertex(position, normal, uv);
  16276. vertices.push(vertex);
  16277. }
  16278. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  16279. if (polygon.plane)
  16280. polygons.push(polygon);
  16281. }
  16282. }
  16283. var csg = CSG.FromPolygons(polygons);
  16284. csg.matrix = matrix;
  16285. csg.position = meshPosition;
  16286. csg.rotation = meshRotation;
  16287. csg.scaling = meshScaling;
  16288. currentCSGMeshId++;
  16289. return csg;
  16290. };
  16291. CSG.FromPolygons = function (polygons) {
  16292. var csg = new BABYLON.CSG();
  16293. csg.polygons = polygons;
  16294. return csg;
  16295. };
  16296. CSG.prototype.clone = function () {
  16297. var csg = new BABYLON.CSG();
  16298. csg.polygons = this.polygons.map(function (p) {
  16299. return p.clone();
  16300. });
  16301. csg.copyTransformAttributes(this);
  16302. return csg;
  16303. };
  16304. CSG.prototype.toPolygons = function () {
  16305. return this.polygons;
  16306. };
  16307. CSG.prototype.union = function (csg) {
  16308. var a = new Node(this.clone().polygons);
  16309. var b = new Node(csg.clone().polygons);
  16310. a.clipTo(b);
  16311. b.clipTo(a);
  16312. b.invert();
  16313. b.clipTo(a);
  16314. b.invert();
  16315. a.build(b.allPolygons());
  16316. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16317. };
  16318. CSG.prototype.unionInPlace = function (csg) {
  16319. var a = new Node(this.polygons);
  16320. var b = new Node(csg.polygons);
  16321. a.clipTo(b);
  16322. b.clipTo(a);
  16323. b.invert();
  16324. b.clipTo(a);
  16325. b.invert();
  16326. a.build(b.allPolygons());
  16327. this.polygons = a.allPolygons();
  16328. };
  16329. CSG.prototype.subtract = function (csg) {
  16330. var a = new Node(this.clone().polygons);
  16331. var b = new Node(csg.clone().polygons);
  16332. a.invert();
  16333. a.clipTo(b);
  16334. b.clipTo(a);
  16335. b.invert();
  16336. b.clipTo(a);
  16337. b.invert();
  16338. a.build(b.allPolygons());
  16339. a.invert();
  16340. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16341. };
  16342. CSG.prototype.subtractInPlace = function (csg) {
  16343. var a = new Node(this.polygons);
  16344. var b = new Node(csg.polygons);
  16345. a.invert();
  16346. a.clipTo(b);
  16347. b.clipTo(a);
  16348. b.invert();
  16349. b.clipTo(a);
  16350. b.invert();
  16351. a.build(b.allPolygons());
  16352. a.invert();
  16353. this.polygons = a.allPolygons();
  16354. };
  16355. CSG.prototype.intersect = function (csg) {
  16356. var a = new Node(this.clone().polygons);
  16357. var b = new Node(csg.clone().polygons);
  16358. a.invert();
  16359. b.clipTo(a);
  16360. b.invert();
  16361. a.clipTo(b);
  16362. b.clipTo(a);
  16363. a.build(b.allPolygons());
  16364. a.invert();
  16365. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16366. };
  16367. CSG.prototype.intersectInPlace = function (csg) {
  16368. var a = new Node(this.polygons);
  16369. var b = new Node(csg.polygons);
  16370. a.invert();
  16371. b.clipTo(a);
  16372. b.invert();
  16373. a.clipTo(b);
  16374. b.clipTo(a);
  16375. a.build(b.allPolygons());
  16376. a.invert();
  16377. this.polygons = a.allPolygons();
  16378. };
  16379. CSG.prototype.inverse = function () {
  16380. var csg = this.clone();
  16381. csg.inverseInPlace();
  16382. return csg;
  16383. };
  16384. CSG.prototype.inverseInPlace = function () {
  16385. this.polygons.map(function (p) {
  16386. p.flip();
  16387. });
  16388. };
  16389. CSG.prototype.copyTransformAttributes = function (csg) {
  16390. this.matrix = csg.matrix;
  16391. this.position = csg.position;
  16392. this.rotation = csg.rotation;
  16393. this.scaling = csg.scaling;
  16394. return this;
  16395. };
  16396. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  16397. var matrix = this.matrix.clone();
  16398. matrix.invert();
  16399. 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;
  16400. if (keepSubMeshes) {
  16401. polygons.sort(function (a, b) {
  16402. if (a.shared.meshId === b.shared.meshId) {
  16403. return a.shared.subMeshId - b.shared.subMeshId;
  16404. } else {
  16405. return a.shared.meshId - b.shared.meshId;
  16406. }
  16407. });
  16408. }
  16409. for (var i = 0, il = polygons.length; i < il; i++) {
  16410. polygon = polygons[i];
  16411. if (!subMesh_dict[polygon.shared.meshId]) {
  16412. subMesh_dict[polygon.shared.meshId] = {};
  16413. }
  16414. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  16415. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  16416. indexStart: +Infinity,
  16417. indexEnd: -Infinity,
  16418. materialIndex: polygon.shared.materialIndex
  16419. };
  16420. }
  16421. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  16422. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  16423. polygonIndices[0] = 0;
  16424. polygonIndices[1] = j - 1;
  16425. polygonIndices[2] = j;
  16426. for (var k = 0; k < 3; k++) {
  16427. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  16428. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  16429. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  16430. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  16431. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  16432. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  16433. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === normal.x && normals[vertex_idx * 3 + 1] === normal.y && normals[vertex_idx * 3 + 2] === normal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  16434. vertices.push(vertex.x, vertex.y, vertex.z);
  16435. uvs.push(uv.x, uv.y);
  16436. normals.push(normal.x, normal.y, normal.z);
  16437. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  16438. }
  16439. indices.push(vertex_idx);
  16440. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  16441. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  16442. currentIndex++;
  16443. }
  16444. }
  16445. }
  16446. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  16447. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  16448. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  16449. mesh.setIndices(indices);
  16450. if (keepSubMeshes) {
  16451. var materialIndexOffset = 0, materialMaxIndex;
  16452. mesh.subMeshes.length = 0;
  16453. for (var m in subMesh_dict) {
  16454. materialMaxIndex = -1;
  16455. for (var sm in subMesh_dict[m]) {
  16456. subMesh_obj = subMesh_dict[m][sm];
  16457. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  16458. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  16459. }
  16460. materialIndexOffset += ++materialMaxIndex;
  16461. }
  16462. }
  16463. return mesh;
  16464. };
  16465. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  16466. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  16467. mesh.material = material;
  16468. mesh.position.copyFrom(this.position);
  16469. mesh.rotation.copyFrom(this.rotation);
  16470. mesh.scaling.copyFrom(this.scaling);
  16471. mesh.computeWorldMatrix(true);
  16472. return mesh;
  16473. };
  16474. return CSG;
  16475. })();
  16476. BABYLON.CSG = CSG;
  16477. })(BABYLON || (BABYLON = {}));
  16478. var __extends = this.__extends || function (d, b) {
  16479. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16480. function __() { this.constructor = d; }
  16481. __.prototype = b.prototype;
  16482. d.prototype = new __();
  16483. };
  16484. var BABYLON;
  16485. (function (BABYLON) {
  16486. var OculusDistortionCorrectionPostProcess = (function (_super) {
  16487. __extends(OculusDistortionCorrectionPostProcess, _super);
  16488. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  16489. var _this = this;
  16490. _super.call(this, name, "oculusDistortionCorrection", [
  16491. 'LensCenter',
  16492. 'Scale',
  16493. 'ScaleIn',
  16494. 'HmdWarpParam'
  16495. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  16496. this._isRightEye = isRightEye;
  16497. this._distortionFactors = cameraSettings.DistortionK;
  16498. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  16499. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  16500. this.onSizeChanged = function () {
  16501. _this.aspectRatio = _this.width * .5 / _this.height;
  16502. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  16503. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  16504. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  16505. };
  16506. this.onApply = function (effect) {
  16507. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  16508. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  16509. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  16510. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  16511. };
  16512. }
  16513. return OculusDistortionCorrectionPostProcess;
  16514. })(BABYLON.PostProcess);
  16515. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  16516. })(BABYLON || (BABYLON = {}));
  16517. var BABYLON;
  16518. (function (BABYLON) {
  16519. (function (JoystickAxis) {
  16520. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  16521. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  16522. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  16523. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  16524. var JoystickAxis = BABYLON.JoystickAxis;
  16525. var VirtualJoystick = (function () {
  16526. function VirtualJoystick(leftJoystick) {
  16527. var _this = this;
  16528. if (leftJoystick) {
  16529. this._leftJoystick = true;
  16530. } else {
  16531. this._leftJoystick = false;
  16532. }
  16533. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  16534. VirtualJoystick._globalJoystickIndex++;
  16535. this._axisTargetedByLeftAndRight = 0 /* X */;
  16536. this._axisTargetedByUpAndDown = 1 /* Y */;
  16537. this.reverseLeftRight = false;
  16538. this.reverseUpDown = false;
  16539. this._touches = new BABYLON.VirtualJoystick.Collection();
  16540. this.deltaPosition = BABYLON.Vector3.Zero();
  16541. this._joystickSensibility = 25;
  16542. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  16543. this._rotationSpeed = 25;
  16544. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  16545. this._rotateOnAxisRelativeToMesh = false;
  16546. if (!VirtualJoystick.vjCanvas) {
  16547. window.addEventListener("resize", function () {
  16548. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  16549. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  16550. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  16551. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  16552. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  16553. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  16554. }, false);
  16555. VirtualJoystick.vjCanvas = document.createElement("canvas");
  16556. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  16557. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  16558. VirtualJoystick.vjCanvas.width = window.innerWidth;
  16559. VirtualJoystick.vjCanvas.height = window.innerHeight;
  16560. VirtualJoystick.vjCanvas.style.width = "100%";
  16561. VirtualJoystick.vjCanvas.style.height = "100%";
  16562. VirtualJoystick.vjCanvas.style.position = "absolute";
  16563. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  16564. VirtualJoystick.vjCanvas.style.top = "0px";
  16565. VirtualJoystick.vjCanvas.style.left = "0px";
  16566. VirtualJoystick.vjCanvas.style.zIndex = "5";
  16567. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  16568. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  16569. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  16570. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  16571. document.body.appendChild(VirtualJoystick.vjCanvas);
  16572. }
  16573. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  16574. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  16575. this.pressed = false;
  16576. this._joystickColor = "cyan";
  16577. this._joystickPointerID = -1;
  16578. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  16579. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  16580. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  16581. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  16582. _this._onPointerDown(evt);
  16583. }, false);
  16584. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  16585. _this._onPointerMove(evt);
  16586. }, false);
  16587. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  16588. _this._onPointerUp(evt);
  16589. }, false);
  16590. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  16591. _this._onPointerUp(evt);
  16592. }, false);
  16593. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  16594. evt.preventDefault();
  16595. }, false);
  16596. requestAnimationFrame(function () {
  16597. _this._drawVirtualJoystick();
  16598. });
  16599. }
  16600. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  16601. this._joystickSensibility = newJoystickSensibility;
  16602. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  16603. };
  16604. VirtualJoystick.prototype._onPointerDown = function (e) {
  16605. var positionOnScreenCondition;
  16606. e.preventDefault();
  16607. if (this._leftJoystick === true) {
  16608. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  16609. } else {
  16610. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  16611. }
  16612. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  16613. this._joystickPointerID = e.pointerId;
  16614. this._joystickPointerStartPos.x = e.clientX;
  16615. this._joystickPointerStartPos.y = e.clientY;
  16616. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  16617. this._deltaJoystickVector.x = 0;
  16618. this._deltaJoystickVector.y = 0;
  16619. this.pressed = true;
  16620. this._touches.add(e.pointerId.toString(), e);
  16621. } else {
  16622. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  16623. this._action();
  16624. this._touches.add(e.pointerId.toString(), e);
  16625. }
  16626. }
  16627. };
  16628. VirtualJoystick.prototype._onPointerMove = function (e) {
  16629. if (this._joystickPointerID == e.pointerId) {
  16630. this._joystickPointerPos.x = e.clientX;
  16631. this._joystickPointerPos.y = e.clientY;
  16632. this._deltaJoystickVector = this._joystickPointerPos.clone();
  16633. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  16634. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  16635. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  16636. switch (this._axisTargetedByLeftAndRight) {
  16637. case 0 /* X */:
  16638. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  16639. break;
  16640. case 1 /* Y */:
  16641. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  16642. break;
  16643. case 2 /* Z */:
  16644. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  16645. break;
  16646. }
  16647. var directionUpDown = this.reverseUpDown ? 1 : -1;
  16648. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  16649. switch (this._axisTargetedByUpAndDown) {
  16650. case 0 /* X */:
  16651. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  16652. break;
  16653. case 1 /* Y */:
  16654. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  16655. break;
  16656. case 2 /* Z */:
  16657. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  16658. break;
  16659. }
  16660. } else {
  16661. if (this._touches.item(e.pointerId.toString())) {
  16662. this._touches.item(e.pointerId.toString()).x = e.clientX;
  16663. this._touches.item(e.pointerId.toString()).y = e.clientY;
  16664. }
  16665. }
  16666. };
  16667. VirtualJoystick.prototype._onPointerUp = function (e) {
  16668. this._clearCanvas();
  16669. if (this._joystickPointerID == e.pointerId) {
  16670. this._joystickPointerID = -1;
  16671. this.pressed = false;
  16672. }
  16673. this._deltaJoystickVector.x = 0;
  16674. this._deltaJoystickVector.y = 0;
  16675. this._touches.remove(e.pointerId.toString());
  16676. };
  16677. /**
  16678. * Change the color of the virtual joystick
  16679. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  16680. */
  16681. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  16682. this._joystickColor = newColor;
  16683. };
  16684. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  16685. this._action = action;
  16686. };
  16687. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  16688. switch (axis) {
  16689. case 0 /* X */:
  16690. case 1 /* Y */:
  16691. case 2 /* Z */:
  16692. this._axisTargetedByLeftAndRight = axis;
  16693. break;
  16694. default:
  16695. this._axisTargetedByLeftAndRight = 0 /* X */;
  16696. break;
  16697. }
  16698. };
  16699. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  16700. switch (axis) {
  16701. case 0 /* X */:
  16702. case 1 /* Y */:
  16703. case 2 /* Z */:
  16704. this._axisTargetedByUpAndDown = axis;
  16705. break;
  16706. default:
  16707. this._axisTargetedByUpAndDown = 1 /* Y */;
  16708. break;
  16709. }
  16710. };
  16711. VirtualJoystick.prototype._clearCanvas = function () {
  16712. if (this._leftJoystick) {
  16713. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  16714. } else {
  16715. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  16716. }
  16717. };
  16718. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  16719. var _this = this;
  16720. if (this.pressed) {
  16721. this._clearCanvas();
  16722. this._touches.forEach(function (touch) {
  16723. if (touch.pointerId === _this._joystickPointerID) {
  16724. VirtualJoystick.vjCanvasContext.beginPath();
  16725. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16726. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  16727. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  16728. VirtualJoystick.vjCanvasContext.stroke();
  16729. VirtualJoystick.vjCanvasContext.beginPath();
  16730. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16731. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  16732. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  16733. VirtualJoystick.vjCanvasContext.stroke();
  16734. VirtualJoystick.vjCanvasContext.beginPath();
  16735. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16736. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  16737. VirtualJoystick.vjCanvasContext.stroke();
  16738. } else {
  16739. VirtualJoystick.vjCanvasContext.beginPath();
  16740. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  16741. VirtualJoystick.vjCanvasContext.beginPath();
  16742. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  16743. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  16744. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  16745. VirtualJoystick.vjCanvasContext.stroke();
  16746. }
  16747. ;
  16748. });
  16749. }
  16750. requestAnimationFrame(function () {
  16751. _this._drawVirtualJoystick();
  16752. });
  16753. };
  16754. VirtualJoystick.prototype.releaseCanvas = function () {
  16755. if (VirtualJoystick.vjCanvas) {
  16756. document.body.removeChild(VirtualJoystick.vjCanvas);
  16757. VirtualJoystick.vjCanvas = null;
  16758. }
  16759. };
  16760. VirtualJoystick._globalJoystickIndex = 0;
  16761. return VirtualJoystick;
  16762. })();
  16763. BABYLON.VirtualJoystick = VirtualJoystick;
  16764. })(BABYLON || (BABYLON = {}));
  16765. var BABYLON;
  16766. (function (BABYLON) {
  16767. (function (VirtualJoystick) {
  16768. var Collection = (function () {
  16769. function Collection() {
  16770. this._count = 0;
  16771. this._collection = new Array();
  16772. }
  16773. Collection.prototype.Count = function () {
  16774. return this._count;
  16775. };
  16776. Collection.prototype.add = function (key, item) {
  16777. if (this._collection[key] != undefined) {
  16778. return undefined;
  16779. }
  16780. this._collection[key] = item;
  16781. return ++this._count;
  16782. };
  16783. Collection.prototype.remove = function (key) {
  16784. if (this._collection[key] == undefined) {
  16785. return undefined;
  16786. }
  16787. delete this._collection[key];
  16788. return --this._count;
  16789. };
  16790. Collection.prototype.item = function (key) {
  16791. return this._collection[key];
  16792. };
  16793. Collection.prototype.forEach = function (block) {
  16794. var key;
  16795. for (key in this._collection) {
  16796. if (this._collection.hasOwnProperty(key)) {
  16797. block(this._collection[key]);
  16798. }
  16799. }
  16800. };
  16801. return Collection;
  16802. })();
  16803. VirtualJoystick.Collection = Collection;
  16804. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  16805. var VirtualJoystick = BABYLON.VirtualJoystick;
  16806. })(BABYLON || (BABYLON = {}));
  16807. var __extends = this.__extends || function (d, b) {
  16808. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16809. function __() { this.constructor = d; }
  16810. __.prototype = b.prototype;
  16811. d.prototype = new __();
  16812. };
  16813. var BABYLON;
  16814. (function (BABYLON) {
  16815. var OculusRiftDevKit2013_Metric = {
  16816. HResolution: 1280,
  16817. VResolution: 800,
  16818. HScreenSize: 0.149759993,
  16819. VScreenSize: 0.0935999975,
  16820. VScreenCenter: 0.0467999987,
  16821. EyeToScreenDistance: 0.0410000011,
  16822. LensSeparationDistance: 0.0635000020,
  16823. InterpupillaryDistance: 0.0640000030,
  16824. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  16825. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  16826. PostProcessScaleFactor: 1.714605507808412,
  16827. LensCenterOffset: 0.151976421
  16828. };
  16829. var _OculusInnerCamera = (function (_super) {
  16830. __extends(_OculusInnerCamera, _super);
  16831. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  16832. _super.call(this, name, position, scene);
  16833. this._workMatrix = new BABYLON.Matrix();
  16834. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  16835. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  16836. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  16837. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  16838. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  16839. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  16840. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  16841. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  16842. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  16843. }
  16844. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  16845. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  16846. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  16847. return this._projectionMatrix;
  16848. };
  16849. _OculusInnerCamera.prototype._getViewMatrix = function () {
  16850. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  16851. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  16852. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  16853. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  16854. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  16855. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  16856. return this._viewMatrix;
  16857. };
  16858. return _OculusInnerCamera;
  16859. })(BABYLON.FreeCamera);
  16860. var OculusCamera = (function (_super) {
  16861. __extends(OculusCamera, _super);
  16862. function OculusCamera(name, position, scene) {
  16863. _super.call(this, name, position, scene);
  16864. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  16865. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  16866. this.subCameras.push(this._leftCamera);
  16867. this.subCameras.push(this._rightCamera);
  16868. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  16869. }
  16870. OculusCamera.prototype._update = function () {
  16871. this._leftCamera.position.copyFrom(this.position);
  16872. this._rightCamera.position.copyFrom(this.position);
  16873. this._updateCamera(this._leftCamera);
  16874. this._updateCamera(this._rightCamera);
  16875. _super.prototype._update.call(this);
  16876. };
  16877. OculusCamera.prototype._updateCamera = function (camera) {
  16878. camera.minZ = this.minZ;
  16879. camera.maxZ = this.maxZ;
  16880. camera.rotation.x = this.rotation.x;
  16881. camera.rotation.y = this.rotation.y;
  16882. camera.rotation.z = this.rotation.z;
  16883. };
  16884. OculusCamera.prototype._onOrientationEvent = function (evt) {
  16885. var yaw = evt.alpha / 180 * Math.PI;
  16886. var pitch = evt.beta / 180 * Math.PI;
  16887. var roll = evt.gamma / 180 * Math.PI;
  16888. if (!this._offsetOrientation) {
  16889. this._offsetOrientation = {
  16890. yaw: yaw,
  16891. pitch: pitch,
  16892. roll: roll
  16893. };
  16894. return;
  16895. } else {
  16896. this.rotation.y += yaw - this._offsetOrientation.yaw;
  16897. this.rotation.x += pitch - this._offsetOrientation.pitch;
  16898. this.rotation.z += this._offsetOrientation.roll - roll;
  16899. this._offsetOrientation.yaw = yaw;
  16900. this._offsetOrientation.pitch = pitch;
  16901. this._offsetOrientation.roll = roll;
  16902. }
  16903. };
  16904. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  16905. _super.prototype.attachControl.call(this, element, noPreventDefault);
  16906. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  16907. };
  16908. OculusCamera.prototype.detachControl = function (element) {
  16909. _super.prototype.detachControl.call(this, element);
  16910. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  16911. };
  16912. return OculusCamera;
  16913. })(BABYLON.FreeCamera);
  16914. BABYLON.OculusCamera = OculusCamera;
  16915. })(BABYLON || (BABYLON = {}));
  16916. var __extends = this.__extends || function (d, b) {
  16917. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16918. function __() { this.constructor = d; }
  16919. __.prototype = b.prototype;
  16920. d.prototype = new __();
  16921. };
  16922. var BABYLON;
  16923. (function (BABYLON) {
  16924. var VirtualJoysticksCamera = (function (_super) {
  16925. __extends(VirtualJoysticksCamera, _super);
  16926. function VirtualJoysticksCamera(name, position, scene) {
  16927. _super.call(this, name, position, scene);
  16928. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  16929. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  16930. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  16931. this._leftjoystick.setJoystickSensibility(0.15);
  16932. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  16933. this._rightjoystick.setAxisForUpDown(0 /* X */);
  16934. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  16935. this._rightjoystick.reverseUpDown = true;
  16936. this._rightjoystick.setJoystickSensibility(0.05);
  16937. this._rightjoystick.setJoystickColor("yellow");
  16938. }
  16939. VirtualJoysticksCamera.prototype._checkInputs = function () {
  16940. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  16941. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  16942. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  16943. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  16944. if (!this._leftjoystick.pressed) {
  16945. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  16946. }
  16947. if (!this._rightjoystick.pressed) {
  16948. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  16949. }
  16950. };
  16951. VirtualJoysticksCamera.prototype.dispose = function () {
  16952. this._leftjoystick.releaseCanvas();
  16953. _super.prototype.dispose.call(this);
  16954. };
  16955. return VirtualJoysticksCamera;
  16956. })(BABYLON.FreeCamera);
  16957. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  16958. })(BABYLON || (BABYLON = {}));
  16959. var __extends = this.__extends || function (d, b) {
  16960. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16961. function __() { this.constructor = d; }
  16962. __.prototype = b.prototype;
  16963. d.prototype = new __();
  16964. };
  16965. var BABYLON;
  16966. (function (BABYLON) {
  16967. var ShaderMaterial = (function (_super) {
  16968. __extends(ShaderMaterial, _super);
  16969. function ShaderMaterial(name, scene, shaderPath, options) {
  16970. _super.call(this, name, scene);
  16971. this._textures = new Array();
  16972. this._floats = new Array();
  16973. this._floatsArrays = {};
  16974. this._colors3 = new Array();
  16975. this._colors4 = new Array();
  16976. this._vectors2 = new Array();
  16977. this._vectors3 = new Array();
  16978. this._matrices = new Array();
  16979. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  16980. this._shaderPath = shaderPath;
  16981. options.needAlphaBlending = options.needAlphaBlending || false;
  16982. options.needAlphaTesting = options.needAlphaTesting || false;
  16983. options.attributes = options.attributes || ["position", "normal", "uv"];
  16984. options.uniforms = options.uniforms || ["worldViewProjection"];
  16985. options.samplers = options.samplers || [];
  16986. this._options = options;
  16987. }
  16988. ShaderMaterial.prototype.needAlphaBlending = function () {
  16989. return this._options.needAlphaBlending;
  16990. };
  16991. ShaderMaterial.prototype.needAlphaTesting = function () {
  16992. return this._options.needAlphaTesting;
  16993. };
  16994. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  16995. if (this._options.uniforms.indexOf(uniformName) === -1) {
  16996. this._options.uniforms.push(uniformName);
  16997. }
  16998. };
  16999. ShaderMaterial.prototype.setTexture = function (name, texture) {
  17000. if (this._options.samplers.indexOf(name) === -1) {
  17001. this._options.samplers.push(name);
  17002. }
  17003. this._textures[name] = texture;
  17004. return this;
  17005. };
  17006. ShaderMaterial.prototype.setFloat = function (name, value) {
  17007. this._checkUniform(name);
  17008. this._floats[name] = value;
  17009. return this;
  17010. };
  17011. ShaderMaterial.prototype.setFloats = function (name, value) {
  17012. this._checkUniform(name);
  17013. this._floatsArrays[name] = value;
  17014. return this;
  17015. };
  17016. ShaderMaterial.prototype.setColor3 = function (name, value) {
  17017. this._checkUniform(name);
  17018. this._colors3[name] = value;
  17019. return this;
  17020. };
  17021. ShaderMaterial.prototype.setColor4 = function (name, value) {
  17022. this._checkUniform(name);
  17023. this._colors4[name] = value;
  17024. return this;
  17025. };
  17026. ShaderMaterial.prototype.setVector2 = function (name, value) {
  17027. this._checkUniform(name);
  17028. this._vectors2[name] = value;
  17029. return this;
  17030. };
  17031. ShaderMaterial.prototype.setVector3 = function (name, value) {
  17032. this._checkUniform(name);
  17033. this._vectors3[name] = value;
  17034. return this;
  17035. };
  17036. ShaderMaterial.prototype.setMatrix = function (name, value) {
  17037. this._checkUniform(name);
  17038. this._matrices[name] = value;
  17039. return this;
  17040. };
  17041. ShaderMaterial.prototype.isReady = function () {
  17042. var engine = this.getScene().getEngine();
  17043. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  17044. if (!this._effect.isReady()) {
  17045. return false;
  17046. }
  17047. return true;
  17048. };
  17049. ShaderMaterial.prototype.bind = function (world) {
  17050. if (this._options.uniforms.indexOf("world") !== -1) {
  17051. this._effect.setMatrix("world", world);
  17052. }
  17053. if (this._options.uniforms.indexOf("view") !== -1) {
  17054. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  17055. }
  17056. if (this._options.uniforms.indexOf("worldView") !== -1) {
  17057. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  17058. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  17059. }
  17060. if (this._options.uniforms.indexOf("projection") !== -1) {
  17061. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  17062. }
  17063. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  17064. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  17065. }
  17066. for (var name in this._textures) {
  17067. this._effect.setTexture(name, this._textures[name]);
  17068. }
  17069. for (name in this._floats) {
  17070. this._effect.setFloat(name, this._floats[name]);
  17071. }
  17072. for (name in this._floatsArrays) {
  17073. this._effect.setArray(name, this._floatsArrays[name]);
  17074. }
  17075. for (name in this._colors3) {
  17076. this._effect.setColor3(name, this._colors3[name]);
  17077. }
  17078. for (name in this._colors4) {
  17079. var color = this._colors4[name];
  17080. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17081. }
  17082. for (name in this._vectors2) {
  17083. this._effect.setVector2(name, this._vectors2[name]);
  17084. }
  17085. for (name in this._vectors3) {
  17086. this._effect.setVector3(name, this._vectors3[name]);
  17087. }
  17088. for (name in this._matrices) {
  17089. this._effect.setMatrix(name, this._matrices[name]);
  17090. }
  17091. };
  17092. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  17093. for (var name in this._textures) {
  17094. this._textures[name].dispose();
  17095. }
  17096. this._textures = [];
  17097. _super.prototype.dispose.call(this, forceDisposeEffect);
  17098. };
  17099. return ShaderMaterial;
  17100. })(BABYLON.Material);
  17101. BABYLON.ShaderMaterial = ShaderMaterial;
  17102. })(BABYLON || (BABYLON = {}));
  17103. var BABYLON;
  17104. (function (BABYLON) {
  17105. var VertexData = (function () {
  17106. function VertexData() {
  17107. }
  17108. VertexData.prototype.set = function (data, kind) {
  17109. switch (kind) {
  17110. case BABYLON.VertexBuffer.PositionKind:
  17111. this.positions = data;
  17112. break;
  17113. case BABYLON.VertexBuffer.NormalKind:
  17114. this.normals = data;
  17115. break;
  17116. case BABYLON.VertexBuffer.UVKind:
  17117. this.uvs = data;
  17118. break;
  17119. case BABYLON.VertexBuffer.UV2Kind:
  17120. this.uv2s = data;
  17121. break;
  17122. case BABYLON.VertexBuffer.ColorKind:
  17123. this.colors = data;
  17124. break;
  17125. case BABYLON.VertexBuffer.MatricesIndicesKind:
  17126. this.matricesIndices = data;
  17127. break;
  17128. case BABYLON.VertexBuffer.MatricesWeightsKind:
  17129. this.matricesWeights = data;
  17130. break;
  17131. }
  17132. };
  17133. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  17134. this._applyTo(mesh, updatable);
  17135. };
  17136. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  17137. this._applyTo(geometry, updatable);
  17138. };
  17139. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  17140. this._update(mesh);
  17141. };
  17142. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  17143. this._update(geometry);
  17144. };
  17145. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  17146. if (this.positions) {
  17147. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  17148. }
  17149. if (this.normals) {
  17150. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  17151. }
  17152. if (this.uvs) {
  17153. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  17154. }
  17155. if (this.uv2s) {
  17156. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  17157. }
  17158. if (this.colors) {
  17159. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  17160. }
  17161. if (this.matricesIndices) {
  17162. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  17163. }
  17164. if (this.matricesWeights) {
  17165. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  17166. }
  17167. if (this.indices) {
  17168. meshOrGeometry.setIndices(this.indices);
  17169. }
  17170. };
  17171. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  17172. if (this.positions) {
  17173. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  17174. }
  17175. if (this.normals) {
  17176. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  17177. }
  17178. if (this.uvs) {
  17179. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  17180. }
  17181. if (this.uv2s) {
  17182. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  17183. }
  17184. if (this.colors) {
  17185. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  17186. }
  17187. if (this.matricesIndices) {
  17188. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  17189. }
  17190. if (this.matricesWeights) {
  17191. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  17192. }
  17193. if (this.indices) {
  17194. meshOrGeometry.setIndices(this.indices);
  17195. }
  17196. };
  17197. VertexData.prototype.transform = function (matrix) {
  17198. var transformed = BABYLON.Vector3.Zero();
  17199. if (this.positions) {
  17200. var position = BABYLON.Vector3.Zero();
  17201. for (var index = 0; index < this.positions.length; index += 3) {
  17202. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  17203. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  17204. this.positions[index] = transformed.x;
  17205. this.positions[index + 1] = transformed.y;
  17206. this.positions[index + 2] = transformed.z;
  17207. }
  17208. }
  17209. if (this.normals) {
  17210. var normal = BABYLON.Vector3.Zero();
  17211. for (index = 0; index < this.normals.length; index += 3) {
  17212. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  17213. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  17214. this.normals[index] = transformed.x;
  17215. this.normals[index + 1] = transformed.y;
  17216. this.normals[index + 2] = transformed.z;
  17217. }
  17218. }
  17219. };
  17220. VertexData.prototype.merge = function (other) {
  17221. if (other.indices) {
  17222. if (!this.indices) {
  17223. this.indices = [];
  17224. }
  17225. var offset = this.positions ? this.positions.length / 3 : 0;
  17226. for (var index = 0; index < other.indices.length; index++) {
  17227. this.indices.push(other.indices[index] + offset);
  17228. }
  17229. }
  17230. if (other.positions) {
  17231. if (!this.positions) {
  17232. this.positions = [];
  17233. }
  17234. for (index = 0; index < other.positions.length; index++) {
  17235. this.positions.push(other.positions[index]);
  17236. }
  17237. }
  17238. if (other.normals) {
  17239. if (!this.normals) {
  17240. this.normals = [];
  17241. }
  17242. for (index = 0; index < other.normals.length; index++) {
  17243. this.normals.push(other.normals[index]);
  17244. }
  17245. }
  17246. if (other.uvs) {
  17247. if (!this.uvs) {
  17248. this.uvs = [];
  17249. }
  17250. for (index = 0; index < other.uvs.length; index++) {
  17251. this.uvs.push(other.uvs[index]);
  17252. }
  17253. }
  17254. if (other.uv2s) {
  17255. if (!this.uv2s) {
  17256. this.uv2s = [];
  17257. }
  17258. for (index = 0; index < other.uv2s.length; index++) {
  17259. this.uv2s.push(other.uv2s[index]);
  17260. }
  17261. }
  17262. if (other.matricesIndices) {
  17263. if (!this.matricesIndices) {
  17264. this.matricesIndices = [];
  17265. }
  17266. for (index = 0; index < other.matricesIndices.length; index++) {
  17267. this.matricesIndices.push(other.matricesIndices[index]);
  17268. }
  17269. }
  17270. if (other.matricesWeights) {
  17271. if (!this.matricesWeights) {
  17272. this.matricesWeights = [];
  17273. }
  17274. for (index = 0; index < other.matricesWeights.length; index++) {
  17275. this.matricesWeights.push(other.matricesWeights[index]);
  17276. }
  17277. }
  17278. if (other.colors) {
  17279. if (!this.colors) {
  17280. this.colors = [];
  17281. }
  17282. for (index = 0; index < other.colors.length; index++) {
  17283. this.colors.push(other.colors[index]);
  17284. }
  17285. }
  17286. };
  17287. VertexData.ExtractFromMesh = function (mesh) {
  17288. return VertexData._ExtractFrom(mesh);
  17289. };
  17290. VertexData.ExtractFromGeometry = function (geometry) {
  17291. return VertexData._ExtractFrom(geometry);
  17292. };
  17293. VertexData._ExtractFrom = function (meshOrGeometry) {
  17294. var result = new BABYLON.VertexData();
  17295. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17296. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17297. }
  17298. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17299. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17300. }
  17301. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17302. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17303. }
  17304. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17305. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17306. }
  17307. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17308. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17309. }
  17310. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17311. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17312. }
  17313. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17314. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17315. }
  17316. result.indices = meshOrGeometry.getIndices();
  17317. return result;
  17318. };
  17319. VertexData.CreateBox = function (size) {
  17320. var normalsSource = [
  17321. new BABYLON.Vector3(0, 0, 1),
  17322. new BABYLON.Vector3(0, 0, -1),
  17323. new BABYLON.Vector3(1, 0, 0),
  17324. new BABYLON.Vector3(-1, 0, 0),
  17325. new BABYLON.Vector3(0, 1, 0),
  17326. new BABYLON.Vector3(0, -1, 0)
  17327. ];
  17328. var indices = [];
  17329. var positions = [];
  17330. var normals = [];
  17331. var uvs = [];
  17332. size = size || 1;
  17333. for (var index = 0; index < normalsSource.length; index++) {
  17334. var normal = normalsSource[index];
  17335. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  17336. var side2 = BABYLON.Vector3.Cross(normal, side1);
  17337. var verticesLength = positions.length / 3;
  17338. indices.push(verticesLength);
  17339. indices.push(verticesLength + 1);
  17340. indices.push(verticesLength + 2);
  17341. indices.push(verticesLength);
  17342. indices.push(verticesLength + 2);
  17343. indices.push(verticesLength + 3);
  17344. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  17345. positions.push(vertex.x, vertex.y, vertex.z);
  17346. normals.push(normal.x, normal.y, normal.z);
  17347. uvs.push(1.0, 1.0);
  17348. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  17349. positions.push(vertex.x, vertex.y, vertex.z);
  17350. normals.push(normal.x, normal.y, normal.z);
  17351. uvs.push(0.0, 1.0);
  17352. vertex = normal.add(side1).add(side2).scale(size / 2);
  17353. positions.push(vertex.x, vertex.y, vertex.z);
  17354. normals.push(normal.x, normal.y, normal.z);
  17355. uvs.push(0.0, 0.0);
  17356. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  17357. positions.push(vertex.x, vertex.y, vertex.z);
  17358. normals.push(normal.x, normal.y, normal.z);
  17359. uvs.push(1.0, 0.0);
  17360. }
  17361. var vertexData = new BABYLON.VertexData();
  17362. vertexData.indices = indices;
  17363. vertexData.positions = positions;
  17364. vertexData.normals = normals;
  17365. vertexData.uvs = uvs;
  17366. return vertexData;
  17367. };
  17368. VertexData.CreateSphere = function (segments, diameter) {
  17369. segments = segments || 32;
  17370. diameter = diameter || 1;
  17371. var radius = diameter / 2;
  17372. var totalZRotationSteps = 2 + segments;
  17373. var totalYRotationSteps = 2 * totalZRotationSteps;
  17374. var indices = [];
  17375. var positions = [];
  17376. var normals = [];
  17377. var uvs = [];
  17378. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  17379. var normalizedZ = zRotationStep / totalZRotationSteps;
  17380. var angleZ = (normalizedZ * Math.PI);
  17381. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  17382. var normalizedY = yRotationStep / totalYRotationSteps;
  17383. var angleY = normalizedY * Math.PI * 2;
  17384. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  17385. var rotationY = BABYLON.Matrix.RotationY(angleY);
  17386. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  17387. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  17388. var vertex = complete.scale(radius);
  17389. var normal = BABYLON.Vector3.Normalize(vertex);
  17390. positions.push(vertex.x, vertex.y, vertex.z);
  17391. normals.push(normal.x, normal.y, normal.z);
  17392. uvs.push(normalizedZ, normalizedY);
  17393. }
  17394. if (zRotationStep > 0) {
  17395. var verticesCount = positions.length / 3;
  17396. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  17397. indices.push((firstIndex));
  17398. indices.push((firstIndex + 1));
  17399. indices.push(firstIndex + totalYRotationSteps + 1);
  17400. indices.push((firstIndex + totalYRotationSteps + 1));
  17401. indices.push((firstIndex + 1));
  17402. indices.push((firstIndex + totalYRotationSteps + 2));
  17403. }
  17404. }
  17405. }
  17406. var vertexData = new BABYLON.VertexData();
  17407. vertexData.indices = indices;
  17408. vertexData.positions = positions;
  17409. vertexData.normals = normals;
  17410. vertexData.uvs = uvs;
  17411. return vertexData;
  17412. };
  17413. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  17414. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  17415. var radiusTop = diameterTop / 2;
  17416. var radiusBottom = diameterBottom / 2;
  17417. var indices = [];
  17418. var positions = [];
  17419. var normals = [];
  17420. var uvs = [];
  17421. height = height || 1;
  17422. diameterTop = diameterTop || 0.5;
  17423. diameterBottom = diameterBottom || 1;
  17424. tessellation = tessellation || 16;
  17425. subdivisions = subdivisions || 1;
  17426. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  17427. var getCircleVector = function (i) {
  17428. var angle = (i * 2.0 * Math.PI / tessellation);
  17429. var dx = Math.cos(angle);
  17430. var dz = Math.sin(angle);
  17431. return new BABYLON.Vector3(dx, 0, dz);
  17432. };
  17433. var createCylinderCap = function (isTop) {
  17434. var radius = isTop ? radiusTop : radiusBottom;
  17435. if (radius == 0) {
  17436. return;
  17437. }
  17438. var vbase = positions.length / 3;
  17439. var offset = new BABYLON.Vector3(0, height / 2, 0);
  17440. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  17441. if (!isTop) {
  17442. offset.scaleInPlace(-1);
  17443. textureScale.x = -textureScale.x;
  17444. }
  17445. for (i = 0; i < tessellation; i++) {
  17446. var circleVector = getCircleVector(i);
  17447. var position = circleVector.scale(radius).add(offset);
  17448. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  17449. positions.push(position.x, position.y, position.z);
  17450. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17451. }
  17452. for (var i = 0; i < tessellation - 2; i++) {
  17453. if (!isTop) {
  17454. indices.push(vbase);
  17455. indices.push(vbase + (i + 2) % tessellation);
  17456. indices.push(vbase + (i + 1) % tessellation);
  17457. } else {
  17458. indices.push(vbase);
  17459. indices.push(vbase + (i + 1) % tessellation);
  17460. indices.push(vbase + (i + 2) % tessellation);
  17461. }
  17462. }
  17463. };
  17464. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  17465. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  17466. var stride = tessellation + 1;
  17467. for (var i = 0; i <= tessellation; i++) {
  17468. var circleVector = getCircleVector(i);
  17469. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  17470. var position, radius = radiusBottom;
  17471. for (var s = 0; s <= subdivisions; s++) {
  17472. position = circleVector.scale(radius);
  17473. position.addInPlace(base.add(offset.scale(s)));
  17474. textureCoordinate.y += 1 / subdivisions;
  17475. radius += (radiusTop - radiusBottom) / subdivisions;
  17476. positions.push(position.x, position.y, position.z);
  17477. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17478. }
  17479. }
  17480. subdivisions += 1;
  17481. for (var s = 0; s < subdivisions - 1; s++) {
  17482. for (var i = 0; i <= tessellation; i++) {
  17483. indices.push(i * subdivisions + s);
  17484. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  17485. indices.push(i * subdivisions + (s + 1));
  17486. indices.push(i * subdivisions + (s + 1));
  17487. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  17488. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  17489. }
  17490. }
  17491. createCylinderCap(true);
  17492. createCylinderCap(false);
  17493. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17494. var vertexData = new BABYLON.VertexData();
  17495. vertexData.indices = indices;
  17496. vertexData.positions = positions;
  17497. vertexData.normals = normals;
  17498. vertexData.uvs = uvs;
  17499. return vertexData;
  17500. };
  17501. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  17502. var indices = [];
  17503. var positions = [];
  17504. var normals = [];
  17505. var uvs = [];
  17506. diameter = diameter || 1;
  17507. thickness = thickness || 0.5;
  17508. tessellation = tessellation || 16;
  17509. var stride = tessellation + 1;
  17510. for (var i = 0; i <= tessellation; i++) {
  17511. var u = i / tessellation;
  17512. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  17513. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  17514. for (var j = 0; j <= tessellation; j++) {
  17515. var v = 1 - j / tessellation;
  17516. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  17517. var dx = Math.cos(innerAngle);
  17518. var dy = Math.sin(innerAngle);
  17519. var normal = new BABYLON.Vector3(dx, dy, 0);
  17520. var position = normal.scale(thickness / 2);
  17521. var textureCoordinate = new BABYLON.Vector2(u, v);
  17522. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  17523. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  17524. positions.push(position.x, position.y, position.z);
  17525. normals.push(normal.x, normal.y, normal.z);
  17526. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17527. var nextI = (i + 1) % stride;
  17528. var nextJ = (j + 1) % stride;
  17529. indices.push(i * stride + j);
  17530. indices.push(i * stride + nextJ);
  17531. indices.push(nextI * stride + j);
  17532. indices.push(i * stride + nextJ);
  17533. indices.push(nextI * stride + nextJ);
  17534. indices.push(nextI * stride + j);
  17535. }
  17536. }
  17537. var vertexData = new BABYLON.VertexData();
  17538. vertexData.indices = indices;
  17539. vertexData.positions = positions;
  17540. vertexData.normals = normals;
  17541. vertexData.uvs = uvs;
  17542. return vertexData;
  17543. };
  17544. VertexData.CreateLines = function (points) {
  17545. var indices = [];
  17546. var positions = [];
  17547. for (var index = 0; index < points.length; index++) {
  17548. positions.push(points[index].x, points[index].y, points[index].z);
  17549. if (index > 0) {
  17550. indices.push(index - 1);
  17551. indices.push(index);
  17552. }
  17553. }
  17554. var vertexData = new BABYLON.VertexData();
  17555. vertexData.indices = indices;
  17556. vertexData.positions = positions;
  17557. return vertexData;
  17558. };
  17559. VertexData.CreateGround = function (width, height, subdivisions) {
  17560. var indices = [];
  17561. var positions = [];
  17562. var normals = [];
  17563. var uvs = [];
  17564. var row, col;
  17565. width = width || 1;
  17566. height = height || 1;
  17567. subdivisions = subdivisions || 1;
  17568. for (row = 0; row <= subdivisions; row++) {
  17569. for (col = 0; col <= subdivisions; col++) {
  17570. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  17571. var normal = new BABYLON.Vector3(0, 1.0, 0);
  17572. positions.push(position.x, position.y, position.z);
  17573. normals.push(normal.x, normal.y, normal.z);
  17574. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  17575. }
  17576. }
  17577. for (row = 0; row < subdivisions; row++) {
  17578. for (col = 0; col < subdivisions; col++) {
  17579. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17580. indices.push(col + 1 + row * (subdivisions + 1));
  17581. indices.push(col + row * (subdivisions + 1));
  17582. indices.push(col + (row + 1) * (subdivisions + 1));
  17583. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17584. indices.push(col + row * (subdivisions + 1));
  17585. }
  17586. }
  17587. var vertexData = new BABYLON.VertexData();
  17588. vertexData.indices = indices;
  17589. vertexData.positions = positions;
  17590. vertexData.normals = normals;
  17591. vertexData.uvs = uvs;
  17592. return vertexData;
  17593. };
  17594. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  17595. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  17596. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  17597. var indices = [];
  17598. var positions = [];
  17599. var normals = [];
  17600. var uvs = [];
  17601. var row, col, tileRow, tileCol;
  17602. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  17603. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  17604. precision.w = (precision.w < 1) ? 1 : precision.w;
  17605. precision.h = (precision.h < 1) ? 1 : precision.h;
  17606. var tileSize = {
  17607. 'w': (xmax - xmin) / subdivisions.w,
  17608. 'h': (zmax - zmin) / subdivisions.h
  17609. };
  17610. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  17611. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  17612. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  17613. }
  17614. }
  17615. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  17616. var base = positions.length / 3;
  17617. var rowLength = precision.w + 1;
  17618. for (row = 0; row < precision.h; row++) {
  17619. for (col = 0; col < precision.w; col++) {
  17620. var square = [
  17621. base + col + row * rowLength,
  17622. base + (col + 1) + row * rowLength,
  17623. base + (col + 1) + (row + 1) * rowLength,
  17624. base + col + (row + 1) * rowLength
  17625. ];
  17626. indices.push(square[1]);
  17627. indices.push(square[2]);
  17628. indices.push(square[3]);
  17629. indices.push(square[0]);
  17630. indices.push(square[1]);
  17631. indices.push(square[3]);
  17632. }
  17633. }
  17634. var position = BABYLON.Vector3.Zero();
  17635. var normal = new BABYLON.Vector3(0, 1.0, 0);
  17636. for (row = 0; row <= precision.h; row++) {
  17637. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  17638. for (col = 0; col <= precision.w; col++) {
  17639. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  17640. position.y = 0;
  17641. positions.push(position.x, position.y, position.z);
  17642. normals.push(normal.x, normal.y, normal.z);
  17643. uvs.push(col / precision.w, row / precision.h);
  17644. }
  17645. }
  17646. }
  17647. var vertexData = new BABYLON.VertexData();
  17648. vertexData.indices = indices;
  17649. vertexData.positions = positions;
  17650. vertexData.normals = normals;
  17651. vertexData.uvs = uvs;
  17652. return vertexData;
  17653. };
  17654. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  17655. var indices = [];
  17656. var positions = [];
  17657. var normals = [];
  17658. var uvs = [];
  17659. var row, col;
  17660. for (row = 0; row <= subdivisions; row++) {
  17661. for (col = 0; col <= subdivisions; col++) {
  17662. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  17663. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  17664. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  17665. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  17666. var r = buffer[pos] / 255.0;
  17667. var g = buffer[pos + 1] / 255.0;
  17668. var b = buffer[pos + 2] / 255.0;
  17669. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  17670. position.y = minHeight + (maxHeight - minHeight) * gradient;
  17671. positions.push(position.x, position.y, position.z);
  17672. normals.push(0, 0, 0);
  17673. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  17674. }
  17675. }
  17676. for (row = 0; row < subdivisions; row++) {
  17677. for (col = 0; col < subdivisions; col++) {
  17678. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17679. indices.push(col + 1 + row * (subdivisions + 1));
  17680. indices.push(col + row * (subdivisions + 1));
  17681. indices.push(col + (row + 1) * (subdivisions + 1));
  17682. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17683. indices.push(col + row * (subdivisions + 1));
  17684. }
  17685. }
  17686. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17687. var vertexData = new BABYLON.VertexData();
  17688. vertexData.indices = indices;
  17689. vertexData.positions = positions;
  17690. vertexData.normals = normals;
  17691. vertexData.uvs = uvs;
  17692. return vertexData;
  17693. };
  17694. VertexData.CreatePlane = function (size) {
  17695. var indices = [];
  17696. var positions = [];
  17697. var normals = [];
  17698. var uvs = [];
  17699. size = size || 1;
  17700. var halfSize = size / 2.0;
  17701. positions.push(-halfSize, -halfSize, 0);
  17702. normals.push(0, 0, -1.0);
  17703. uvs.push(0.0, 0.0);
  17704. positions.push(halfSize, -halfSize, 0);
  17705. normals.push(0, 0, -1.0);
  17706. uvs.push(1.0, 0.0);
  17707. positions.push(halfSize, halfSize, 0);
  17708. normals.push(0, 0, -1.0);
  17709. uvs.push(1.0, 1.0);
  17710. positions.push(-halfSize, halfSize, 0);
  17711. normals.push(0, 0, -1.0);
  17712. uvs.push(0.0, 1.0);
  17713. indices.push(0);
  17714. indices.push(1);
  17715. indices.push(2);
  17716. indices.push(0);
  17717. indices.push(2);
  17718. indices.push(3);
  17719. var vertexData = new BABYLON.VertexData();
  17720. vertexData.indices = indices;
  17721. vertexData.positions = positions;
  17722. vertexData.normals = normals;
  17723. vertexData.uvs = uvs;
  17724. return vertexData;
  17725. };
  17726. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  17727. var indices = [];
  17728. var positions = [];
  17729. var normals = [];
  17730. var uvs = [];
  17731. radius = radius || 2;
  17732. tube = tube || 0.5;
  17733. radialSegments = radialSegments || 32;
  17734. tubularSegments = tubularSegments || 32;
  17735. p = p || 2;
  17736. q = q || 3;
  17737. var getPos = function (angle) {
  17738. var cu = Math.cos(angle);
  17739. var su = Math.sin(angle);
  17740. var quOverP = q / p * angle;
  17741. var cs = Math.cos(quOverP);
  17742. var tx = radius * (2 + cs) * 0.5 * cu;
  17743. var ty = radius * (2 + cs) * su * 0.5;
  17744. var tz = radius * Math.sin(quOverP) * 0.5;
  17745. return new BABYLON.Vector3(tx, ty, tz);
  17746. };
  17747. for (var i = 0; i <= radialSegments; i++) {
  17748. var modI = i % radialSegments;
  17749. var u = modI / radialSegments * 2 * p * Math.PI;
  17750. var p1 = getPos(u);
  17751. var p2 = getPos(u + 0.01);
  17752. var tang = p2.subtract(p1);
  17753. var n = p2.add(p1);
  17754. var bitan = BABYLON.Vector3.Cross(tang, n);
  17755. n = BABYLON.Vector3.Cross(bitan, tang);
  17756. bitan.normalize();
  17757. n.normalize();
  17758. for (var j = 0; j < tubularSegments; j++) {
  17759. var modJ = j % tubularSegments;
  17760. var v = modJ / tubularSegments * 2 * Math.PI;
  17761. var cx = -tube * Math.cos(v);
  17762. var cy = tube * Math.sin(v);
  17763. positions.push(p1.x + cx * n.x + cy * bitan.x);
  17764. positions.push(p1.y + cx * n.y + cy * bitan.y);
  17765. positions.push(p1.z + cx * n.z + cy * bitan.z);
  17766. uvs.push(i / radialSegments);
  17767. uvs.push(j / tubularSegments);
  17768. }
  17769. }
  17770. for (i = 0; i < radialSegments; i++) {
  17771. for (j = 0; j < tubularSegments; j++) {
  17772. var jNext = (j + 1) % tubularSegments;
  17773. var a = i * tubularSegments + j;
  17774. var b = (i + 1) * tubularSegments + j;
  17775. var c = (i + 1) * tubularSegments + jNext;
  17776. var d = i * tubularSegments + jNext;
  17777. indices.push(d);
  17778. indices.push(b);
  17779. indices.push(a);
  17780. indices.push(d);
  17781. indices.push(c);
  17782. indices.push(b);
  17783. }
  17784. }
  17785. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17786. var vertexData = new BABYLON.VertexData();
  17787. vertexData.indices = indices;
  17788. vertexData.positions = positions;
  17789. vertexData.normals = normals;
  17790. vertexData.uvs = uvs;
  17791. return vertexData;
  17792. };
  17793. VertexData.ComputeNormals = function (positions, indices, normals) {
  17794. var positionVectors = [];
  17795. var facesOfVertices = [];
  17796. var index;
  17797. for (index = 0; index < positions.length; index += 3) {
  17798. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  17799. positionVectors.push(vector3);
  17800. facesOfVertices.push([]);
  17801. }
  17802. var facesNormals = [];
  17803. for (index = 0; index < indices.length / 3; index++) {
  17804. var i1 = indices[index * 3];
  17805. var i2 = indices[index * 3 + 1];
  17806. var i3 = indices[index * 3 + 2];
  17807. var p1 = positionVectors[i1];
  17808. var p2 = positionVectors[i2];
  17809. var p3 = positionVectors[i3];
  17810. var p1p2 = p1.subtract(p2);
  17811. var p3p2 = p3.subtract(p2);
  17812. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  17813. facesOfVertices[i1].push(index);
  17814. facesOfVertices[i2].push(index);
  17815. facesOfVertices[i3].push(index);
  17816. }
  17817. for (index = 0; index < positionVectors.length; index++) {
  17818. var faces = facesOfVertices[index];
  17819. var normal = BABYLON.Vector3.Zero();
  17820. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  17821. normal.addInPlace(facesNormals[faces[faceIndex]]);
  17822. }
  17823. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  17824. normals[index * 3] = normal.x;
  17825. normals[index * 3 + 1] = normal.y;
  17826. normals[index * 3 + 2] = normal.z;
  17827. }
  17828. };
  17829. return VertexData;
  17830. })();
  17831. BABYLON.VertexData = VertexData;
  17832. })(BABYLON || (BABYLON = {}));
  17833. var __extends = this.__extends || function (d, b) {
  17834. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17835. function __() { this.constructor = d; }
  17836. __.prototype = b.prototype;
  17837. d.prototype = new __();
  17838. };
  17839. var BABYLON;
  17840. (function (BABYLON) {
  17841. var buildCamera = function (that, name) {
  17842. that._leftCamera.isIntermediate = true;
  17843. that.subCameras.push(that._leftCamera);
  17844. that.subCameras.push(that._rightCamera);
  17845. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  17846. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  17847. that._anaglyphPostProcess.onApply = function (effect) {
  17848. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  17849. };
  17850. that._update();
  17851. };
  17852. var AnaglyphArcRotateCamera = (function (_super) {
  17853. __extends(AnaglyphArcRotateCamera, _super);
  17854. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  17855. _super.call(this, name, alpha, beta, radius, target, scene);
  17856. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  17857. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  17858. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  17859. buildCamera(this, name);
  17860. }
  17861. AnaglyphArcRotateCamera.prototype._update = function () {
  17862. this._updateCamera(this._leftCamera);
  17863. this._updateCamera(this._rightCamera);
  17864. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  17865. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  17866. _super.prototype._update.call(this);
  17867. };
  17868. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  17869. camera.beta = this.beta;
  17870. camera.radius = this.radius;
  17871. camera.minZ = this.minZ;
  17872. camera.maxZ = this.maxZ;
  17873. camera.fov = this.fov;
  17874. camera.target = this.target;
  17875. };
  17876. return AnaglyphArcRotateCamera;
  17877. })(BABYLON.ArcRotateCamera);
  17878. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  17879. var AnaglyphFreeCamera = (function (_super) {
  17880. __extends(AnaglyphFreeCamera, _super);
  17881. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  17882. _super.call(this, name, position, scene);
  17883. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  17884. this._transformMatrix = new BABYLON.Matrix();
  17885. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  17886. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  17887. buildCamera(this, name);
  17888. }
  17889. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  17890. var target = this.getTarget();
  17891. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  17892. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  17893. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  17894. };
  17895. AnaglyphFreeCamera.prototype._update = function () {
  17896. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  17897. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  17898. this._updateCamera(this._leftCamera);
  17899. this._updateCamera(this._rightCamera);
  17900. _super.prototype._update.call(this);
  17901. };
  17902. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  17903. camera.minZ = this.minZ;
  17904. camera.maxZ = this.maxZ;
  17905. camera.fov = this.fov;
  17906. camera.viewport = this.viewport;
  17907. camera.setTarget(this.getTarget());
  17908. };
  17909. return AnaglyphFreeCamera;
  17910. })(BABYLON.FreeCamera);
  17911. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  17912. })(BABYLON || (BABYLON = {}));
  17913. var __extends = this.__extends || function (d, b) {
  17914. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17915. function __() { this.constructor = d; }
  17916. __.prototype = b.prototype;
  17917. d.prototype = new __();
  17918. };
  17919. var BABYLON;
  17920. (function (BABYLON) {
  17921. var AnaglyphPostProcess = (function (_super) {
  17922. __extends(AnaglyphPostProcess, _super);
  17923. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17924. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  17925. }
  17926. return AnaglyphPostProcess;
  17927. })(BABYLON.PostProcess);
  17928. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  17929. })(BABYLON || (BABYLON = {}));
  17930. var BABYLON;
  17931. (function (BABYLON) {
  17932. var Tags = (function () {
  17933. function Tags() {
  17934. }
  17935. Tags.EnableFor = function (obj) {
  17936. obj._tags = obj._tags || {};
  17937. obj.hasTags = function () {
  17938. return Tags.HasTags(obj);
  17939. };
  17940. obj.addTags = function (tagsString) {
  17941. return Tags.AddTagsTo(obj, tagsString);
  17942. };
  17943. obj.removeTags = function (tagsString) {
  17944. return Tags.RemoveTagsFrom(obj, tagsString);
  17945. };
  17946. obj.matchesTagsQuery = function (tagsQuery) {
  17947. return Tags.MatchesQuery(obj, tagsQuery);
  17948. };
  17949. };
  17950. Tags.DisableFor = function (obj) {
  17951. delete obj._tags;
  17952. delete obj.hasTags;
  17953. delete obj.addTags;
  17954. delete obj.removeTags;
  17955. delete obj.matchesTagsQuery;
  17956. };
  17957. Tags.HasTags = function (obj) {
  17958. if (!obj._tags) {
  17959. return false;
  17960. }
  17961. return !BABYLON.Tools.IsEmpty(obj._tags);
  17962. };
  17963. Tags.GetTags = function (obj) {
  17964. if (!obj._tags) {
  17965. return null;
  17966. }
  17967. return obj._tags;
  17968. };
  17969. Tags.AddTagsTo = function (obj, tagsString) {
  17970. if (!tagsString) {
  17971. return;
  17972. }
  17973. var tags = tagsString.split(" ");
  17974. for (var t in tags) {
  17975. Tags._AddTagTo(obj, tags[t]);
  17976. }
  17977. };
  17978. Tags._AddTagTo = function (obj, tag) {
  17979. tag = tag.trim();
  17980. if (tag === "" || tag === "true" || tag === "false") {
  17981. return;
  17982. }
  17983. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  17984. return;
  17985. }
  17986. Tags.EnableFor(obj);
  17987. obj._tags[tag] = true;
  17988. };
  17989. Tags.RemoveTagsFrom = function (obj, tagsString) {
  17990. if (!Tags.HasTags(obj)) {
  17991. return;
  17992. }
  17993. var tags = tagsString.split(" ");
  17994. for (var t in tags) {
  17995. Tags._RemoveTagFrom(obj, tags[t]);
  17996. }
  17997. };
  17998. Tags._RemoveTagFrom = function (obj, tag) {
  17999. delete obj._tags[tag];
  18000. };
  18001. Tags.MatchesQuery = function (obj, tagsQuery) {
  18002. if (tagsQuery === undefined) {
  18003. return true;
  18004. }
  18005. if (tagsQuery === "") {
  18006. return Tags.HasTags(obj);
  18007. }
  18008. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  18009. return Tags.HasTags(obj) && obj._tags[r];
  18010. });
  18011. };
  18012. return Tags;
  18013. })();
  18014. BABYLON.Tags = Tags;
  18015. })(BABYLON || (BABYLON = {}));
  18016. var BABYLON;
  18017. (function (BABYLON) {
  18018. (function (Internals) {
  18019. var AndOrNotEvaluator = (function () {
  18020. function AndOrNotEvaluator() {
  18021. }
  18022. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  18023. if (!query.match(/\([^\(\)]*\)/g)) {
  18024. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  18025. } else {
  18026. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  18027. r = r.slice(1, r.length - 1);
  18028. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  18029. });
  18030. }
  18031. if (query === "true") {
  18032. return true;
  18033. }
  18034. if (query === "false") {
  18035. return false;
  18036. }
  18037. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  18038. };
  18039. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  18040. evaluateCallback = evaluateCallback || (function (r) {
  18041. return r === "true" ? true : false;
  18042. });
  18043. var result;
  18044. var or = parenthesisContent.split("||");
  18045. for (var i in or) {
  18046. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  18047. var and = ori.split("&&");
  18048. if (and.length > 1) {
  18049. for (var j = 0; j < and.length; ++j) {
  18050. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  18051. if (andj !== "true" && andj !== "false") {
  18052. if (andj[0] === "!") {
  18053. result = !evaluateCallback(andj.substring(1));
  18054. } else {
  18055. result = evaluateCallback(andj);
  18056. }
  18057. } else {
  18058. result = andj === "true" ? true : false;
  18059. }
  18060. if (!result) {
  18061. ori = "false";
  18062. break;
  18063. }
  18064. }
  18065. }
  18066. if (result || ori === "true") {
  18067. result = true;
  18068. break;
  18069. }
  18070. if (ori !== "true" && ori !== "false") {
  18071. if (ori[0] === "!") {
  18072. result = !evaluateCallback(ori.substring(1));
  18073. } else {
  18074. result = evaluateCallback(ori);
  18075. }
  18076. } else {
  18077. result = ori === "true" ? true : false;
  18078. }
  18079. }
  18080. return result ? "true" : "false";
  18081. };
  18082. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  18083. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  18084. r = r.replace(/[\s]/g, function () {
  18085. return "";
  18086. });
  18087. return r.length % 2 ? "!" : "";
  18088. });
  18089. booleanString = booleanString.trim();
  18090. if (booleanString === "!true") {
  18091. booleanString = "false";
  18092. } else if (booleanString === "!false") {
  18093. booleanString = "true";
  18094. }
  18095. return booleanString;
  18096. };
  18097. return AndOrNotEvaluator;
  18098. })();
  18099. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  18100. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18101. var Internals = BABYLON.Internals;
  18102. })(BABYLON || (BABYLON = {}));
  18103. var BABYLON;
  18104. (function (BABYLON) {
  18105. var PostProcessRenderPass = (function () {
  18106. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  18107. this._enabled = true;
  18108. this._refCount = 0;
  18109. this._name = name;
  18110. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  18111. this.setRenderList(renderList);
  18112. this._renderTexture.onBeforeRender = beforeRender;
  18113. this._renderTexture.onAfterRender = afterRender;
  18114. this._scene = scene;
  18115. }
  18116. PostProcessRenderPass.prototype._incRefCount = function () {
  18117. if (this._refCount === 0) {
  18118. this._scene.customRenderTargets.push(this._renderTexture);
  18119. }
  18120. return ++this._refCount;
  18121. };
  18122. PostProcessRenderPass.prototype._decRefCount = function () {
  18123. this._refCount--;
  18124. if (this._refCount <= 0) {
  18125. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  18126. }
  18127. return this._refCount;
  18128. };
  18129. PostProcessRenderPass.prototype._update = function () {
  18130. this.setRenderList(this._renderList);
  18131. };
  18132. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  18133. this._renderTexture.renderList = renderList;
  18134. };
  18135. PostProcessRenderPass.prototype.getRenderTexture = function () {
  18136. return this._renderTexture;
  18137. };
  18138. return PostProcessRenderPass;
  18139. })();
  18140. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  18141. })(BABYLON || (BABYLON = {}));
  18142. var BABYLON;
  18143. (function (BABYLON) {
  18144. var PostProcessRenderEffect = (function () {
  18145. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  18146. this._engine = engine;
  18147. this._name = name;
  18148. this._singleInstance = singleInstance || true;
  18149. this._getPostProcess = getPostProcess;
  18150. this._cameras = [];
  18151. this._postProcesses = [];
  18152. this._indicesForCamera = [];
  18153. this._renderPasses = [];
  18154. this._renderEffectAsPasses = [];
  18155. }
  18156. PostProcessRenderEffect.prototype._update = function () {
  18157. for (var renderPassName in this._renderPasses) {
  18158. this._renderPasses[renderPassName]._update();
  18159. }
  18160. };
  18161. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  18162. this._renderPasses[renderPass._name] = renderPass;
  18163. this._linkParameters();
  18164. };
  18165. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  18166. delete this._renderPasses[renderPass._name];
  18167. this._linkParameters();
  18168. };
  18169. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  18170. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  18171. this._linkParameters();
  18172. };
  18173. PostProcessRenderEffect.prototype.getPass = function (passName) {
  18174. for (var renderPassName in this._renderPasses) {
  18175. if (renderPassName === passName) {
  18176. return this._renderPasses[passName];
  18177. }
  18178. }
  18179. };
  18180. PostProcessRenderEffect.prototype.emptyPasses = function () {
  18181. this._renderPasses.length = 0;
  18182. this._linkParameters();
  18183. };
  18184. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  18185. var cameraKey;
  18186. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18187. for (var i = 0; i < _cam.length; i++) {
  18188. var camera = _cam[i];
  18189. var cameraName = camera.name;
  18190. if (this._singleInstance) {
  18191. cameraKey = 0;
  18192. } else {
  18193. cameraKey = cameraName;
  18194. }
  18195. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  18196. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  18197. if (!this._indicesForCamera[cameraName]) {
  18198. this._indicesForCamera[cameraName] = [];
  18199. }
  18200. this._indicesForCamera[cameraName].push(index);
  18201. if (this._cameras.indexOf(camera) === -1) {
  18202. this._cameras[cameraName] = camera;
  18203. }
  18204. for (var passName in this._renderPasses) {
  18205. this._renderPasses[passName]._incRefCount();
  18206. }
  18207. }
  18208. this._linkParameters();
  18209. };
  18210. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  18211. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18212. for (var i = 0; i < _cam.length; i++) {
  18213. var camera = _cam[i];
  18214. var cameraName = camera.name;
  18215. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  18216. var index = this._cameras.indexOf(cameraName);
  18217. this._indicesForCamera.splice(index, 1);
  18218. this._cameras.splice(index, 1);
  18219. for (var passName in this._renderPasses) {
  18220. this._renderPasses[passName]._decRefCount();
  18221. }
  18222. }
  18223. };
  18224. PostProcessRenderEffect.prototype._enable = function (cameras) {
  18225. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18226. for (var i = 0; i < _cam.length; i++) {
  18227. var camera = _cam[i];
  18228. var cameraName = camera.name;
  18229. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  18230. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  18231. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  18232. }
  18233. }
  18234. for (var passName in this._renderPasses) {
  18235. this._renderPasses[passName]._incRefCount();
  18236. }
  18237. }
  18238. };
  18239. PostProcessRenderEffect.prototype._disable = function (cameras) {
  18240. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18241. for (var i = 0; i < _cam.length; i++) {
  18242. var camera = _cam[i];
  18243. var cameraName = camera.Name;
  18244. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  18245. for (var passName in this._renderPasses) {
  18246. this._renderPasses[passName]._decRefCount();
  18247. }
  18248. }
  18249. };
  18250. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  18251. if (this._singleInstance) {
  18252. return this._postProcesses[0];
  18253. } else {
  18254. return this._postProcesses[camera.name];
  18255. }
  18256. };
  18257. PostProcessRenderEffect.prototype._linkParameters = function () {
  18258. var _this = this;
  18259. for (var index in this._postProcesses) {
  18260. if (this.applyParameters) {
  18261. this.applyParameters(this._postProcesses[index]);
  18262. }
  18263. this._postProcesses[index].onBeforeRender = function (effect) {
  18264. _this._linkTextures(effect);
  18265. };
  18266. }
  18267. };
  18268. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  18269. for (var renderPassName in this._renderPasses) {
  18270. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  18271. }
  18272. for (var renderEffectName in this._renderEffectAsPasses) {
  18273. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  18274. }
  18275. };
  18276. return PostProcessRenderEffect;
  18277. })();
  18278. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  18279. })(BABYLON || (BABYLON = {}));
  18280. var BABYLON;
  18281. (function (BABYLON) {
  18282. var PostProcessRenderPipeline = (function () {
  18283. function PostProcessRenderPipeline(engine, name) {
  18284. this._engine = engine;
  18285. this._name = name;
  18286. this._renderEffects = [];
  18287. this._renderEffectsForIsolatedPass = [];
  18288. this._cameras = [];
  18289. }
  18290. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  18291. this._renderEffects[renderEffect._name] = renderEffect;
  18292. };
  18293. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  18294. var renderEffects = this._renderEffects[renderEffectName];
  18295. if (!renderEffects) {
  18296. return;
  18297. }
  18298. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  18299. };
  18300. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  18301. var renderEffects = this._renderEffects[renderEffectName];
  18302. if (!renderEffects) {
  18303. return;
  18304. }
  18305. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  18306. };
  18307. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  18308. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18309. var indicesToDelete = [];
  18310. for (var i = 0; i < _cam.length; i++) {
  18311. var camera = _cam[i];
  18312. var cameraName = camera.name;
  18313. if (this._cameras.indexOf(camera) === -1) {
  18314. this._cameras[cameraName] = camera;
  18315. } else if (unique) {
  18316. indicesToDelete.push(i);
  18317. }
  18318. }
  18319. for (var i = 0; i < indicesToDelete.length; i++) {
  18320. cameras.splice(indicesToDelete[i], 1);
  18321. }
  18322. for (var renderEffectName in this._renderEffects) {
  18323. this._renderEffects[renderEffectName]._attachCameras(_cam);
  18324. }
  18325. };
  18326. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  18327. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18328. for (var renderEffectName in this._renderEffects) {
  18329. this._renderEffects[renderEffectName]._detachCameras(_cam);
  18330. }
  18331. for (var i = 0; i < _cam.length; i++) {
  18332. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  18333. }
  18334. };
  18335. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  18336. var _this = this;
  18337. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18338. var pass = null;
  18339. for (var renderEffectName in this._renderEffects) {
  18340. pass = this._renderEffects[renderEffectName].getPass(passName);
  18341. if (pass != null) {
  18342. break;
  18343. }
  18344. }
  18345. if (pass === null) {
  18346. return;
  18347. }
  18348. for (var renderEffectName in this._renderEffects) {
  18349. this._renderEffects[renderEffectName]._disable(_cam);
  18350. }
  18351. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  18352. for (var i = 0; i < _cam.length; i++) {
  18353. var camera = _cam[i];
  18354. var cameraName = camera.name;
  18355. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  18356. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  18357. });
  18358. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  18359. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  18360. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  18361. }
  18362. };
  18363. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  18364. var _this = this;
  18365. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18366. for (var i = 0; i < _cam.length; i++) {
  18367. var camera = _cam[i];
  18368. var cameraName = camera.name;
  18369. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  18370. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  18371. });
  18372. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  18373. }
  18374. for (var renderEffectName in this._renderEffects) {
  18375. this._renderEffects[renderEffectName]._enable(_cam);
  18376. }
  18377. };
  18378. PostProcessRenderPipeline.prototype._update = function () {
  18379. for (var renderEffectName in this._renderEffects) {
  18380. this._renderEffects[renderEffectName]._update();
  18381. }
  18382. for (var i = 0; i < this._cameras.length; i++) {
  18383. var cameraName = this._cameras[i].name;
  18384. if (this._renderEffectsForIsolatedPass[cameraName]) {
  18385. this._renderEffectsForIsolatedPass[cameraName]._update();
  18386. }
  18387. }
  18388. };
  18389. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  18390. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  18391. return PostProcessRenderPipeline;
  18392. })();
  18393. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  18394. })(BABYLON || (BABYLON = {}));
  18395. var BABYLON;
  18396. (function (BABYLON) {
  18397. var PostProcessRenderPipelineManager = (function () {
  18398. function PostProcessRenderPipelineManager() {
  18399. this._renderPipelines = new Array();
  18400. }
  18401. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  18402. this._renderPipelines[renderPipeline._name] = renderPipeline;
  18403. };
  18404. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  18405. var renderPipeline = this._renderPipelines[renderPipelineName];
  18406. if (!renderPipeline) {
  18407. return;
  18408. }
  18409. renderPipeline._attachCameras(cameras, unique);
  18410. };
  18411. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  18412. var renderPipeline = this._renderPipelines[renderPipelineName];
  18413. if (!renderPipeline) {
  18414. return;
  18415. }
  18416. renderPipeline._detachCameras(cameras);
  18417. };
  18418. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  18419. var renderPipeline = this._renderPipelines[renderPipelineName];
  18420. if (!renderPipeline) {
  18421. return;
  18422. }
  18423. renderPipeline._enableEffect(renderEffectName, cameras);
  18424. };
  18425. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  18426. var renderPipeline = this._renderPipelines[renderPipelineName];
  18427. if (!renderPipeline) {
  18428. return;
  18429. }
  18430. renderPipeline._disableEffect(renderEffectName, cameras);
  18431. };
  18432. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  18433. var renderPipeline = this._renderPipelines[renderPipelineName];
  18434. if (!renderPipeline) {
  18435. return;
  18436. }
  18437. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  18438. };
  18439. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  18440. var renderPipeline = this._renderPipelines[renderPipelineName];
  18441. if (!renderPipeline) {
  18442. return;
  18443. }
  18444. renderPipeline._disableDisplayOnlyPass(cameras);
  18445. };
  18446. PostProcessRenderPipelineManager.prototype.update = function () {
  18447. for (var renderPipelineName in this._renderPipelines) {
  18448. this._renderPipelines[renderPipelineName]._update();
  18449. }
  18450. };
  18451. return PostProcessRenderPipelineManager;
  18452. })();
  18453. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  18454. })(BABYLON || (BABYLON = {}));
  18455. var __extends = this.__extends || function (d, b) {
  18456. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18457. function __() { this.constructor = d; }
  18458. __.prototype = b.prototype;
  18459. d.prototype = new __();
  18460. };
  18461. var BABYLON;
  18462. (function (BABYLON) {
  18463. var DisplayPassPostProcess = (function (_super) {
  18464. __extends(DisplayPassPostProcess, _super);
  18465. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18466. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  18467. }
  18468. return DisplayPassPostProcess;
  18469. })(BABYLON.PostProcess);
  18470. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  18471. })(BABYLON || (BABYLON = {}));
  18472. var BABYLON;
  18473. (function (BABYLON) {
  18474. var BoundingBoxRenderer = (function () {
  18475. function BoundingBoxRenderer(scene) {
  18476. this.frontColor = new BABYLON.Color3(1, 1, 1);
  18477. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  18478. this.showBackLines = true;
  18479. this.renderList = new BABYLON.SmartArray(32);
  18480. this._scene = scene;
  18481. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  18482. attributes: ["position"],
  18483. uniforms: ["worldViewProjection", "color"]
  18484. });
  18485. var engine = this._scene.getEngine();
  18486. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  18487. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  18488. 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]);
  18489. }
  18490. BoundingBoxRenderer.prototype.reset = function () {
  18491. this.renderList.reset();
  18492. };
  18493. BoundingBoxRenderer.prototype.render = function () {
  18494. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  18495. return;
  18496. }
  18497. var engine = this._scene.getEngine();
  18498. engine.setDepthWrite(false);
  18499. this._colorShader._preBind();
  18500. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  18501. var boundingBox = this.renderList.data[boundingBoxIndex];
  18502. var min = boundingBox.minimum;
  18503. var max = boundingBox.maximum;
  18504. var diff = max.subtract(min);
  18505. var median = min.add(diff.scale(0.5));
  18506. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  18507. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  18508. if (this.showBackLines) {
  18509. engine.setDepthFunctionToGreaterOrEqual();
  18510. this._colorShader.setColor4("color", this.backColor.toColor4());
  18511. this._colorShader.bind(worldMatrix);
  18512. engine.draw(WebGLRenderingContext.LINES, 0, 24);
  18513. }
  18514. engine.setDepthFunctionToLess();
  18515. this._colorShader.setColor4("color", this.frontColor.toColor4());
  18516. this._colorShader.bind(worldMatrix);
  18517. engine.draw(WebGLRenderingContext.LINES, 0, 24);
  18518. }
  18519. this._colorShader.unbind();
  18520. engine.setDepthFunctionToLessOrEqual();
  18521. engine.setDepthWrite(true);
  18522. };
  18523. BoundingBoxRenderer.prototype.dispose = function () {
  18524. this._colorShader.dispose();
  18525. this._vb.dispose();
  18526. this._scene.getEngine()._releaseBuffer(this._ib);
  18527. };
  18528. return BoundingBoxRenderer;
  18529. })();
  18530. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  18531. })(BABYLON || (BABYLON = {}));
  18532. var __extends = this.__extends || function (d, b) {
  18533. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18534. function __() { this.constructor = d; }
  18535. __.prototype = b.prototype;
  18536. d.prototype = new __();
  18537. };
  18538. var BABYLON;
  18539. (function (BABYLON) {
  18540. var Condition = (function () {
  18541. function Condition(actionManager) {
  18542. this._actionManager = actionManager;
  18543. }
  18544. Condition.prototype.isValid = function () {
  18545. return true;
  18546. };
  18547. Condition.prototype._getProperty = function (propertyPath) {
  18548. return this._actionManager._getProperty(propertyPath);
  18549. };
  18550. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  18551. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18552. };
  18553. return Condition;
  18554. })();
  18555. BABYLON.Condition = Condition;
  18556. var ValueCondition = (function (_super) {
  18557. __extends(ValueCondition, _super);
  18558. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  18559. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  18560. _super.call(this, actionManager);
  18561. this.propertyPath = propertyPath;
  18562. this.value = value;
  18563. this.operator = operator;
  18564. this._target = this._getEffectiveTarget(target, this.propertyPath);
  18565. this._property = this._getProperty(this.propertyPath);
  18566. }
  18567. Object.defineProperty(ValueCondition, "IsEqual", {
  18568. get: function () {
  18569. return ValueCondition._IsEqual;
  18570. },
  18571. enumerable: true,
  18572. configurable: true
  18573. });
  18574. Object.defineProperty(ValueCondition, "IsDifferent", {
  18575. get: function () {
  18576. return ValueCondition._IsDifferent;
  18577. },
  18578. enumerable: true,
  18579. configurable: true
  18580. });
  18581. Object.defineProperty(ValueCondition, "IsGreater", {
  18582. get: function () {
  18583. return ValueCondition._IsGreater;
  18584. },
  18585. enumerable: true,
  18586. configurable: true
  18587. });
  18588. Object.defineProperty(ValueCondition, "IsLesser", {
  18589. get: function () {
  18590. return ValueCondition._IsLesser;
  18591. },
  18592. enumerable: true,
  18593. configurable: true
  18594. });
  18595. ValueCondition.prototype.isValid = function () {
  18596. switch (this.operator) {
  18597. case ValueCondition.IsGreater:
  18598. return this._target[this._property] > this.value;
  18599. case ValueCondition.IsLesser:
  18600. return this._target[this._property] < this.value;
  18601. case ValueCondition.IsEqual:
  18602. case ValueCondition.IsDifferent:
  18603. var check;
  18604. if (this.value.equals) {
  18605. check = this.value.equals(this._target[this._property]);
  18606. } else {
  18607. check = this.value === this._target[this._property];
  18608. }
  18609. return this.operator === ValueCondition.IsEqual ? check : !check;
  18610. }
  18611. return false;
  18612. };
  18613. ValueCondition._IsEqual = 0;
  18614. ValueCondition._IsDifferent = 1;
  18615. ValueCondition._IsGreater = 2;
  18616. ValueCondition._IsLesser = 3;
  18617. return ValueCondition;
  18618. })(Condition);
  18619. BABYLON.ValueCondition = ValueCondition;
  18620. var PredicateCondition = (function (_super) {
  18621. __extends(PredicateCondition, _super);
  18622. function PredicateCondition(actionManager, predicate) {
  18623. _super.call(this, actionManager);
  18624. this.predicate = predicate;
  18625. }
  18626. PredicateCondition.prototype.isValid = function () {
  18627. return this.predicate();
  18628. };
  18629. return PredicateCondition;
  18630. })(Condition);
  18631. BABYLON.PredicateCondition = PredicateCondition;
  18632. var StateCondition = (function (_super) {
  18633. __extends(StateCondition, _super);
  18634. function StateCondition(actionManager, target, value) {
  18635. _super.call(this, actionManager);
  18636. this.value = value;
  18637. this._target = target;
  18638. }
  18639. StateCondition.prototype.isValid = function () {
  18640. return this._target.state === this.value;
  18641. };
  18642. return StateCondition;
  18643. })(Condition);
  18644. BABYLON.StateCondition = StateCondition;
  18645. })(BABYLON || (BABYLON = {}));
  18646. var BABYLON;
  18647. (function (BABYLON) {
  18648. var Action = (function () {
  18649. function Action(triggerOptions, condition) {
  18650. this.triggerOptions = triggerOptions;
  18651. if (triggerOptions.parameter) {
  18652. this.trigger = triggerOptions.trigger;
  18653. this._triggerParameter = triggerOptions.parameter;
  18654. } else {
  18655. this.trigger = triggerOptions;
  18656. }
  18657. this._nextActiveAction = this;
  18658. this._condition = condition;
  18659. }
  18660. Action.prototype._prepare = function () {
  18661. };
  18662. Action.prototype.getTriggerParameter = function () {
  18663. return this._triggerParameter;
  18664. };
  18665. Action.prototype._executeCurrent = function (evt) {
  18666. if (this._condition) {
  18667. var currentRenderId = this._actionManager.getScene().getRenderId();
  18668. if (this._condition._evaluationId === currentRenderId) {
  18669. if (!this._condition._currentResult) {
  18670. return;
  18671. }
  18672. } else {
  18673. this._condition._evaluationId = currentRenderId;
  18674. if (!this._condition.isValid()) {
  18675. this._condition._currentResult = false;
  18676. return;
  18677. }
  18678. this._condition._currentResult = true;
  18679. }
  18680. }
  18681. this._nextActiveAction.execute(evt);
  18682. if (this._nextActiveAction._child) {
  18683. if (!this._nextActiveAction._child._actionManager) {
  18684. this._nextActiveAction._child._actionManager = this._actionManager;
  18685. }
  18686. this._nextActiveAction = this._nextActiveAction._child;
  18687. } else {
  18688. this._nextActiveAction = this;
  18689. }
  18690. };
  18691. Action.prototype.execute = function (evt) {
  18692. };
  18693. Action.prototype.then = function (action) {
  18694. this._child = action;
  18695. action._actionManager = this._actionManager;
  18696. action._prepare();
  18697. return action;
  18698. };
  18699. Action.prototype._getProperty = function (propertyPath) {
  18700. return this._actionManager._getProperty(propertyPath);
  18701. };
  18702. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  18703. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18704. };
  18705. return Action;
  18706. })();
  18707. BABYLON.Action = Action;
  18708. })(BABYLON || (BABYLON = {}));
  18709. var BABYLON;
  18710. (function (BABYLON) {
  18711. var ActionEvent = (function () {
  18712. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  18713. this.source = source;
  18714. this.pointerX = pointerX;
  18715. this.pointerY = pointerY;
  18716. this.meshUnderPointer = meshUnderPointer;
  18717. this.sourceEvent = sourceEvent;
  18718. }
  18719. ActionEvent.CreateNew = function (source) {
  18720. var scene = source.getScene();
  18721. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  18722. };
  18723. ActionEvent.CreateNewFromScene = function (scene, evt) {
  18724. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  18725. };
  18726. return ActionEvent;
  18727. })();
  18728. BABYLON.ActionEvent = ActionEvent;
  18729. var ActionManager = (function () {
  18730. function ActionManager(scene) {
  18731. this.actions = new Array();
  18732. this._scene = scene;
  18733. scene._actionManagers.push(this);
  18734. }
  18735. Object.defineProperty(ActionManager, "NothingTrigger", {
  18736. get: function () {
  18737. return ActionManager._NothingTrigger;
  18738. },
  18739. enumerable: true,
  18740. configurable: true
  18741. });
  18742. Object.defineProperty(ActionManager, "OnPickTrigger", {
  18743. get: function () {
  18744. return ActionManager._OnPickTrigger;
  18745. },
  18746. enumerable: true,
  18747. configurable: true
  18748. });
  18749. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  18750. get: function () {
  18751. return ActionManager._OnLeftPickTrigger;
  18752. },
  18753. enumerable: true,
  18754. configurable: true
  18755. });
  18756. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  18757. get: function () {
  18758. return ActionManager._OnRightPickTrigger;
  18759. },
  18760. enumerable: true,
  18761. configurable: true
  18762. });
  18763. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  18764. get: function () {
  18765. return ActionManager._OnCenterPickTrigger;
  18766. },
  18767. enumerable: true,
  18768. configurable: true
  18769. });
  18770. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  18771. get: function () {
  18772. return ActionManager._OnPointerOverTrigger;
  18773. },
  18774. enumerable: true,
  18775. configurable: true
  18776. });
  18777. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  18778. get: function () {
  18779. return ActionManager._OnPointerOutTrigger;
  18780. },
  18781. enumerable: true,
  18782. configurable: true
  18783. });
  18784. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  18785. get: function () {
  18786. return ActionManager._OnEveryFrameTrigger;
  18787. },
  18788. enumerable: true,
  18789. configurable: true
  18790. });
  18791. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  18792. get: function () {
  18793. return ActionManager._OnIntersectionEnterTrigger;
  18794. },
  18795. enumerable: true,
  18796. configurable: true
  18797. });
  18798. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  18799. get: function () {
  18800. return ActionManager._OnIntersectionExitTrigger;
  18801. },
  18802. enumerable: true,
  18803. configurable: true
  18804. });
  18805. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  18806. get: function () {
  18807. return ActionManager._OnKeyDownTrigger;
  18808. },
  18809. enumerable: true,
  18810. configurable: true
  18811. });
  18812. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  18813. get: function () {
  18814. return ActionManager._OnKeyUpTrigger;
  18815. },
  18816. enumerable: true,
  18817. configurable: true
  18818. });
  18819. ActionManager.prototype.dispose = function () {
  18820. var index = this._scene._actionManagers.indexOf(this);
  18821. if (index > -1) {
  18822. this._scene._actionManagers.splice(index, 1);
  18823. }
  18824. };
  18825. ActionManager.prototype.getScene = function () {
  18826. return this._scene;
  18827. };
  18828. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  18829. for (var index = 0; index < this.actions.length; index++) {
  18830. var action = this.actions[index];
  18831. if (triggers.indexOf(action.trigger) > -1) {
  18832. return true;
  18833. }
  18834. }
  18835. return false;
  18836. };
  18837. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  18838. get: function () {
  18839. for (var index = 0; index < this.actions.length; index++) {
  18840. var action = this.actions[index];
  18841. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  18842. return true;
  18843. }
  18844. }
  18845. return false;
  18846. },
  18847. enumerable: true,
  18848. configurable: true
  18849. });
  18850. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  18851. get: function () {
  18852. for (var index = 0; index < this.actions.length; index++) {
  18853. var action = this.actions[index];
  18854. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  18855. return true;
  18856. }
  18857. }
  18858. return false;
  18859. },
  18860. enumerable: true,
  18861. configurable: true
  18862. });
  18863. ActionManager.prototype.registerAction = function (action) {
  18864. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  18865. if (this.getScene().actionManager !== this) {
  18866. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  18867. return null;
  18868. }
  18869. }
  18870. this.actions.push(action);
  18871. action._actionManager = this;
  18872. action._prepare();
  18873. return action;
  18874. };
  18875. ActionManager.prototype.processTrigger = function (trigger, evt) {
  18876. for (var index = 0; index < this.actions.length; index++) {
  18877. var action = this.actions[index];
  18878. if (action.trigger === trigger) {
  18879. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  18880. var parameter = action.getTriggerParameter();
  18881. if (parameter) {
  18882. if (evt.sourceEvent.key !== parameter) {
  18883. continue;
  18884. }
  18885. }
  18886. }
  18887. action._executeCurrent(evt);
  18888. }
  18889. }
  18890. };
  18891. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  18892. var properties = propertyPath.split(".");
  18893. for (var index = 0; index < properties.length - 1; index++) {
  18894. target = target[properties[index]];
  18895. }
  18896. return target;
  18897. };
  18898. ActionManager.prototype._getProperty = function (propertyPath) {
  18899. var properties = propertyPath.split(".");
  18900. return properties[properties.length - 1];
  18901. };
  18902. ActionManager._NothingTrigger = 0;
  18903. ActionManager._OnPickTrigger = 1;
  18904. ActionManager._OnLeftPickTrigger = 2;
  18905. ActionManager._OnRightPickTrigger = 3;
  18906. ActionManager._OnCenterPickTrigger = 4;
  18907. ActionManager._OnPointerOverTrigger = 5;
  18908. ActionManager._OnPointerOutTrigger = 6;
  18909. ActionManager._OnEveryFrameTrigger = 7;
  18910. ActionManager._OnIntersectionEnterTrigger = 8;
  18911. ActionManager._OnIntersectionExitTrigger = 9;
  18912. ActionManager._OnKeyDownTrigger = 10;
  18913. ActionManager._OnKeyUpTrigger = 11;
  18914. return ActionManager;
  18915. })();
  18916. BABYLON.ActionManager = ActionManager;
  18917. })(BABYLON || (BABYLON = {}));
  18918. var __extends = this.__extends || function (d, b) {
  18919. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18920. function __() { this.constructor = d; }
  18921. __.prototype = b.prototype;
  18922. d.prototype = new __();
  18923. };
  18924. var BABYLON;
  18925. (function (BABYLON) {
  18926. var InterpolateValueAction = (function (_super) {
  18927. __extends(InterpolateValueAction, _super);
  18928. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  18929. if (typeof duration === "undefined") { duration = 1000; }
  18930. _super.call(this, triggerOptions, condition);
  18931. this.propertyPath = propertyPath;
  18932. this.value = value;
  18933. this.duration = duration;
  18934. this.stopOtherAnimations = stopOtherAnimations;
  18935. this._target = target;
  18936. }
  18937. InterpolateValueAction.prototype._prepare = function () {
  18938. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18939. this._property = this._getProperty(this.propertyPath);
  18940. };
  18941. InterpolateValueAction.prototype.execute = function () {
  18942. var scene = this._actionManager.getScene();
  18943. var keys = [
  18944. {
  18945. frame: 0,
  18946. value: this._target[this._property]
  18947. }, {
  18948. frame: 100,
  18949. value: this.value
  18950. }
  18951. ];
  18952. var dataType;
  18953. if (typeof this.value === "number") {
  18954. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  18955. } else if (this.value instanceof BABYLON.Color3) {
  18956. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  18957. } else if (this.value instanceof BABYLON.Vector3) {
  18958. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  18959. } else if (this.value instanceof BABYLON.Matrix) {
  18960. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  18961. } else if (this.value instanceof BABYLON.Quaternion) {
  18962. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  18963. } else {
  18964. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  18965. return;
  18966. }
  18967. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  18968. animation.setKeys(keys);
  18969. if (this.stopOtherAnimations) {
  18970. scene.stopAnimation(this._target);
  18971. }
  18972. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  18973. };
  18974. return InterpolateValueAction;
  18975. })(BABYLON.Action);
  18976. BABYLON.InterpolateValueAction = InterpolateValueAction;
  18977. })(BABYLON || (BABYLON = {}));
  18978. var __extends = this.__extends || function (d, b) {
  18979. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18980. function __() { this.constructor = d; }
  18981. __.prototype = b.prototype;
  18982. d.prototype = new __();
  18983. };
  18984. var BABYLON;
  18985. (function (BABYLON) {
  18986. var SwitchBooleanAction = (function (_super) {
  18987. __extends(SwitchBooleanAction, _super);
  18988. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  18989. _super.call(this, triggerOptions, condition);
  18990. this.propertyPath = propertyPath;
  18991. this._target = target;
  18992. }
  18993. SwitchBooleanAction.prototype._prepare = function () {
  18994. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18995. this._property = this._getProperty(this.propertyPath);
  18996. };
  18997. SwitchBooleanAction.prototype.execute = function () {
  18998. this._target[this._property] = !this._target[this._property];
  18999. };
  19000. return SwitchBooleanAction;
  19001. })(BABYLON.Action);
  19002. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  19003. var SetStateAction = (function (_super) {
  19004. __extends(SetStateAction, _super);
  19005. function SetStateAction(triggerOptions, target, value, condition) {
  19006. _super.call(this, triggerOptions, condition);
  19007. this.value = value;
  19008. this._target = target;
  19009. }
  19010. SetStateAction.prototype.execute = function () {
  19011. this._target.state = this.value;
  19012. };
  19013. return SetStateAction;
  19014. })(BABYLON.Action);
  19015. BABYLON.SetStateAction = SetStateAction;
  19016. var SetValueAction = (function (_super) {
  19017. __extends(SetValueAction, _super);
  19018. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  19019. _super.call(this, triggerOptions, condition);
  19020. this.propertyPath = propertyPath;
  19021. this.value = value;
  19022. this._target = target;
  19023. }
  19024. SetValueAction.prototype._prepare = function () {
  19025. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19026. this._property = this._getProperty(this.propertyPath);
  19027. };
  19028. SetValueAction.prototype.execute = function () {
  19029. this._target[this._property] = this.value;
  19030. };
  19031. return SetValueAction;
  19032. })(BABYLON.Action);
  19033. BABYLON.SetValueAction = SetValueAction;
  19034. var IncrementValueAction = (function (_super) {
  19035. __extends(IncrementValueAction, _super);
  19036. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  19037. _super.call(this, triggerOptions, condition);
  19038. this.propertyPath = propertyPath;
  19039. this.value = value;
  19040. this._target = target;
  19041. }
  19042. IncrementValueAction.prototype._prepare = function () {
  19043. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19044. this._property = this._getProperty(this.propertyPath);
  19045. if (typeof this._target[this._property] !== "number") {
  19046. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  19047. }
  19048. };
  19049. IncrementValueAction.prototype.execute = function () {
  19050. this._target[this._property] += this.value;
  19051. };
  19052. return IncrementValueAction;
  19053. })(BABYLON.Action);
  19054. BABYLON.IncrementValueAction = IncrementValueAction;
  19055. var PlayAnimationAction = (function (_super) {
  19056. __extends(PlayAnimationAction, _super);
  19057. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  19058. _super.call(this, triggerOptions, condition);
  19059. this.from = from;
  19060. this.to = to;
  19061. this.loop = loop;
  19062. this._target = target;
  19063. }
  19064. PlayAnimationAction.prototype._prepare = function () {
  19065. };
  19066. PlayAnimationAction.prototype.execute = function () {
  19067. var scene = this._actionManager.getScene();
  19068. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  19069. };
  19070. return PlayAnimationAction;
  19071. })(BABYLON.Action);
  19072. BABYLON.PlayAnimationAction = PlayAnimationAction;
  19073. var StopAnimationAction = (function (_super) {
  19074. __extends(StopAnimationAction, _super);
  19075. function StopAnimationAction(triggerOptions, target, condition) {
  19076. _super.call(this, triggerOptions, condition);
  19077. this._target = target;
  19078. }
  19079. StopAnimationAction.prototype._prepare = function () {
  19080. };
  19081. StopAnimationAction.prototype.execute = function () {
  19082. var scene = this._actionManager.getScene();
  19083. scene.stopAnimation(this._target);
  19084. };
  19085. return StopAnimationAction;
  19086. })(BABYLON.Action);
  19087. BABYLON.StopAnimationAction = StopAnimationAction;
  19088. var DoNothingAction = (function (_super) {
  19089. __extends(DoNothingAction, _super);
  19090. function DoNothingAction(triggerOptions, condition) {
  19091. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  19092. _super.call(this, triggerOptions, condition);
  19093. }
  19094. DoNothingAction.prototype.execute = function () {
  19095. };
  19096. return DoNothingAction;
  19097. })(BABYLON.Action);
  19098. BABYLON.DoNothingAction = DoNothingAction;
  19099. var CombineAction = (function (_super) {
  19100. __extends(CombineAction, _super);
  19101. function CombineAction(triggerOptions, children, condition) {
  19102. _super.call(this, triggerOptions, condition);
  19103. this.children = children;
  19104. }
  19105. CombineAction.prototype._prepare = function () {
  19106. for (var index = 0; index < this.children.length; index++) {
  19107. this.children[index]._actionManager = this._actionManager;
  19108. this.children[index]._prepare();
  19109. }
  19110. };
  19111. CombineAction.prototype.execute = function (evt) {
  19112. for (var index = 0; index < this.children.length; index++) {
  19113. this.children[index].execute(evt);
  19114. }
  19115. };
  19116. return CombineAction;
  19117. })(BABYLON.Action);
  19118. BABYLON.CombineAction = CombineAction;
  19119. var ExecuteCodeAction = (function (_super) {
  19120. __extends(ExecuteCodeAction, _super);
  19121. function ExecuteCodeAction(triggerOptions, func, condition) {
  19122. _super.call(this, triggerOptions, condition);
  19123. this.func = func;
  19124. }
  19125. ExecuteCodeAction.prototype.execute = function (evt) {
  19126. this.func(evt);
  19127. };
  19128. return ExecuteCodeAction;
  19129. })(BABYLON.Action);
  19130. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  19131. var SetParentAction = (function (_super) {
  19132. __extends(SetParentAction, _super);
  19133. function SetParentAction(triggerOptions, target, parent, condition) {
  19134. _super.call(this, triggerOptions, condition);
  19135. this._target = target;
  19136. this._parent = parent;
  19137. }
  19138. SetParentAction.prototype._prepare = function () {
  19139. };
  19140. SetParentAction.prototype.execute = function () {
  19141. if (this._target.parent === this._parent) {
  19142. return;
  19143. }
  19144. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  19145. invertParentWorldMatrix.invert();
  19146. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  19147. this._target.parent = this._parent;
  19148. };
  19149. return SetParentAction;
  19150. })(BABYLON.Action);
  19151. BABYLON.SetParentAction = SetParentAction;
  19152. })(BABYLON || (BABYLON = {}));
  19153. var __extends = this.__extends || function (d, b) {
  19154. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19155. function __() { this.constructor = d; }
  19156. __.prototype = b.prototype;
  19157. d.prototype = new __();
  19158. };
  19159. var BABYLON;
  19160. (function (BABYLON) {
  19161. var Geometry = (function () {
  19162. function Geometry(id, scene, vertexData, updatable, mesh) {
  19163. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19164. this._totalVertices = 0;
  19165. this._indices = [];
  19166. this.id = id;
  19167. this._engine = scene.getEngine();
  19168. this._meshes = [];
  19169. this._scene = scene;
  19170. if (vertexData) {
  19171. this.setAllVerticesData(vertexData, updatable);
  19172. } else {
  19173. this._totalVertices = 0;
  19174. this._indices = [];
  19175. }
  19176. if (mesh) {
  19177. this.applyToMesh(mesh);
  19178. }
  19179. }
  19180. Geometry.prototype.getScene = function () {
  19181. return this._scene;
  19182. };
  19183. Geometry.prototype.getEngine = function () {
  19184. return this._engine;
  19185. };
  19186. Geometry.prototype.isReady = function () {
  19187. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  19188. };
  19189. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  19190. vertexData.applyToGeometry(this, updatable);
  19191. };
  19192. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  19193. this._vertexBuffers = this._vertexBuffers || {};
  19194. if (this._vertexBuffers[kind]) {
  19195. this._vertexBuffers[kind].dispose();
  19196. }
  19197. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  19198. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19199. var stride = this._vertexBuffers[kind].getStrideSize();
  19200. this._totalVertices = data.length / stride;
  19201. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  19202. var meshes = this._meshes;
  19203. var numOfMeshes = meshes.length;
  19204. for (var index = 0; index < numOfMeshes; index++) {
  19205. var mesh = meshes[index];
  19206. mesh._resetPointsArrayCache();
  19207. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19208. mesh._createGlobalSubMesh();
  19209. mesh.computeWorldMatrix(true);
  19210. }
  19211. }
  19212. };
  19213. Geometry.prototype.updateVerticesDataDirectly = function (kind, data) {
  19214. var vertexBuffer = this.getVertexBuffer(kind);
  19215. if (!vertexBuffer) {
  19216. return;
  19217. }
  19218. vertexBuffer.updateDirectly(data);
  19219. };
  19220. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  19221. var vertexBuffer = this.getVertexBuffer(kind);
  19222. if (!vertexBuffer) {
  19223. return;
  19224. }
  19225. vertexBuffer.update(data);
  19226. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19227. var extend;
  19228. if (updateExtends) {
  19229. var stride = vertexBuffer.getStrideSize();
  19230. this._totalVertices = data.length / stride;
  19231. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  19232. }
  19233. var meshes = this._meshes;
  19234. var numOfMeshes = meshes.length;
  19235. for (var index = 0; index < numOfMeshes; index++) {
  19236. var mesh = meshes[index];
  19237. mesh._resetPointsArrayCache();
  19238. if (updateExtends) {
  19239. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19240. }
  19241. }
  19242. }
  19243. };
  19244. Geometry.prototype.getTotalVertices = function () {
  19245. if (!this.isReady()) {
  19246. return 0;
  19247. }
  19248. return this._totalVertices;
  19249. };
  19250. Geometry.prototype.getVerticesData = function (kind) {
  19251. var vertexBuffer = this.getVertexBuffer(kind);
  19252. if (!vertexBuffer) {
  19253. return null;
  19254. }
  19255. return vertexBuffer.getData();
  19256. };
  19257. Geometry.prototype.getVertexBuffer = function (kind) {
  19258. if (!this.isReady()) {
  19259. return null;
  19260. }
  19261. return this._vertexBuffers[kind];
  19262. };
  19263. Geometry.prototype.getVertexBuffers = function () {
  19264. if (!this.isReady()) {
  19265. return null;
  19266. }
  19267. return this._vertexBuffers;
  19268. };
  19269. Geometry.prototype.isVerticesDataPresent = function (kind) {
  19270. if (!this._vertexBuffers) {
  19271. if (this._delayInfo) {
  19272. return this._delayInfo.indexOf(kind) !== -1;
  19273. }
  19274. return false;
  19275. }
  19276. return this._vertexBuffers[kind] !== undefined;
  19277. };
  19278. Geometry.prototype.getVerticesDataKinds = function () {
  19279. var result = [];
  19280. if (!this._vertexBuffers && this._delayInfo) {
  19281. for (var kind in this._delayInfo) {
  19282. result.push(kind);
  19283. }
  19284. } else {
  19285. for (kind in this._vertexBuffers) {
  19286. result.push(kind);
  19287. }
  19288. }
  19289. return result;
  19290. };
  19291. Geometry.prototype.setIndices = function (indices) {
  19292. if (this._indexBuffer) {
  19293. this._engine._releaseBuffer(this._indexBuffer);
  19294. }
  19295. this._indices = indices;
  19296. if (this._meshes.length !== 0 && this._indices) {
  19297. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  19298. }
  19299. var meshes = this._meshes;
  19300. var numOfMeshes = meshes.length;
  19301. for (var index = 0; index < numOfMeshes; index++) {
  19302. meshes[index]._createGlobalSubMesh();
  19303. }
  19304. };
  19305. Geometry.prototype.getTotalIndices = function () {
  19306. if (!this.isReady()) {
  19307. return 0;
  19308. }
  19309. return this._indices.length;
  19310. };
  19311. Geometry.prototype.getIndices = function () {
  19312. if (!this.isReady()) {
  19313. return null;
  19314. }
  19315. return this._indices;
  19316. };
  19317. Geometry.prototype.getIndexBuffer = function () {
  19318. if (!this.isReady()) {
  19319. return null;
  19320. }
  19321. return this._indexBuffer;
  19322. };
  19323. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  19324. var meshes = this._meshes;
  19325. var index = meshes.indexOf(mesh);
  19326. if (index === -1) {
  19327. return;
  19328. }
  19329. for (var kind in this._vertexBuffers) {
  19330. this._vertexBuffers[kind].dispose();
  19331. }
  19332. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  19333. this._indexBuffer = null;
  19334. }
  19335. meshes.splice(index, 1);
  19336. mesh._geometry = null;
  19337. if (meshes.length == 0 && shouldDispose) {
  19338. this.dispose();
  19339. }
  19340. };
  19341. Geometry.prototype.applyToMesh = function (mesh) {
  19342. if (mesh._geometry === this) {
  19343. return;
  19344. }
  19345. var previousGeometry = mesh._geometry;
  19346. if (previousGeometry) {
  19347. previousGeometry.releaseForMesh(mesh);
  19348. }
  19349. var meshes = this._meshes;
  19350. mesh._geometry = this;
  19351. this._scene.pushGeometry(this);
  19352. meshes.push(mesh);
  19353. if (this.isReady()) {
  19354. this._applyToMesh(mesh);
  19355. } else {
  19356. mesh._boundingInfo = this._boundingInfo;
  19357. }
  19358. };
  19359. Geometry.prototype._applyToMesh = function (mesh) {
  19360. var numOfMeshes = this._meshes.length;
  19361. for (var kind in this._vertexBuffers) {
  19362. if (numOfMeshes === 1) {
  19363. this._vertexBuffers[kind].create();
  19364. }
  19365. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  19366. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19367. mesh._resetPointsArrayCache();
  19368. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  19369. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19370. mesh._createGlobalSubMesh();
  19371. }
  19372. }
  19373. if (numOfMeshes === 1 && this._indices) {
  19374. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  19375. }
  19376. if (this._indexBuffer) {
  19377. this._indexBuffer.references = numOfMeshes;
  19378. }
  19379. };
  19380. Geometry.prototype.load = function (scene, onLoaded) {
  19381. var _this = this;
  19382. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19383. return;
  19384. }
  19385. if (this.isReady()) {
  19386. if (onLoaded) {
  19387. onLoaded();
  19388. }
  19389. return;
  19390. }
  19391. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19392. scene._addPendingData(this);
  19393. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19394. _this._delayLoadingFunction(JSON.parse(data), _this);
  19395. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19396. _this._delayInfo = [];
  19397. scene._removePendingData(_this);
  19398. var meshes = _this._meshes;
  19399. var numOfMeshes = meshes.length;
  19400. for (var index = 0; index < numOfMeshes; index++) {
  19401. _this._applyToMesh(meshes[index]);
  19402. }
  19403. if (onLoaded) {
  19404. onLoaded();
  19405. }
  19406. }, function () {
  19407. }, scene.database);
  19408. };
  19409. Geometry.prototype.dispose = function () {
  19410. var meshes = this._meshes;
  19411. var numOfMeshes = meshes.length;
  19412. for (var index = 0; index < numOfMeshes; index++) {
  19413. this.releaseForMesh(meshes[index]);
  19414. }
  19415. this._meshes = [];
  19416. for (var kind in this._vertexBuffers) {
  19417. this._vertexBuffers[kind].dispose();
  19418. }
  19419. this._vertexBuffers = [];
  19420. this._totalVertices = 0;
  19421. if (this._indexBuffer) {
  19422. this._engine._releaseBuffer(this._indexBuffer);
  19423. }
  19424. this._indexBuffer = null;
  19425. this._indices = [];
  19426. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19427. this.delayLoadingFile = null;
  19428. this._delayLoadingFunction = null;
  19429. this._delayInfo = [];
  19430. this._boundingInfo = null;
  19431. var geometries = this._scene.getGeometries();
  19432. index = geometries.indexOf(this);
  19433. if (index > -1) {
  19434. geometries.splice(index, 1);
  19435. }
  19436. };
  19437. Geometry.prototype.copy = function (id) {
  19438. var vertexData = new BABYLON.VertexData();
  19439. vertexData.indices = [];
  19440. var indices = this.getIndices();
  19441. for (var index = 0; index < indices.length; index++) {
  19442. vertexData.indices.push(indices[index]);
  19443. }
  19444. var updatable = false;
  19445. var stopChecking = false;
  19446. for (var kind in this._vertexBuffers) {
  19447. vertexData.set(this.getVerticesData(kind), kind);
  19448. if (!stopChecking) {
  19449. updatable = this.getVertexBuffer(kind).isUpdatable();
  19450. stopChecking = !updatable;
  19451. }
  19452. }
  19453. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  19454. geometry.delayLoadState = this.delayLoadState;
  19455. geometry.delayLoadingFile = this.delayLoadingFile;
  19456. geometry._delayLoadingFunction = this._delayLoadingFunction;
  19457. for (kind in this._delayInfo) {
  19458. geometry._delayInfo = geometry._delayInfo || [];
  19459. geometry._delayInfo.push(kind);
  19460. }
  19461. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  19462. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19463. return geometry;
  19464. };
  19465. Geometry.ExtractFromMesh = function (mesh, id) {
  19466. var geometry = mesh._geometry;
  19467. if (!geometry) {
  19468. return null;
  19469. }
  19470. return geometry.copy(id);
  19471. };
  19472. Geometry.RandomId = function () {
  19473. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  19474. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  19475. return v.toString(16);
  19476. });
  19477. };
  19478. return Geometry;
  19479. })();
  19480. BABYLON.Geometry = Geometry;
  19481. (function (Geometry) {
  19482. (function (Primitives) {
  19483. var _Primitive = (function (_super) {
  19484. __extends(_Primitive, _super);
  19485. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  19486. this._beingRegenerated = true;
  19487. this._canBeRegenerated = canBeRegenerated;
  19488. _super.call(this, id, scene, vertexData, false, mesh);
  19489. this._beingRegenerated = false;
  19490. }
  19491. _Primitive.prototype.canBeRegenerated = function () {
  19492. return this._canBeRegenerated;
  19493. };
  19494. _Primitive.prototype.regenerate = function () {
  19495. if (!this._canBeRegenerated) {
  19496. return;
  19497. }
  19498. this._beingRegenerated = true;
  19499. this.setAllVerticesData(this._regenerateVertexData(), false);
  19500. this._beingRegenerated = false;
  19501. };
  19502. _Primitive.prototype.asNewGeometry = function (id) {
  19503. return _super.prototype.copy.call(this, id);
  19504. };
  19505. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  19506. if (!this._beingRegenerated) {
  19507. return;
  19508. }
  19509. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  19510. };
  19511. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  19512. if (!this._beingRegenerated) {
  19513. return;
  19514. }
  19515. _super.prototype.setVerticesData.call(this, kind, data, false);
  19516. };
  19517. _Primitive.prototype._regenerateVertexData = function () {
  19518. throw new Error("Abstract method");
  19519. };
  19520. _Primitive.prototype.copy = function (id) {
  19521. throw new Error("Must be overriden in sub-classes.");
  19522. };
  19523. return _Primitive;
  19524. })(Geometry);
  19525. Primitives._Primitive = _Primitive;
  19526. var Box = (function (_super) {
  19527. __extends(Box, _super);
  19528. function Box(id, scene, size, canBeRegenerated, mesh) {
  19529. this.size = size;
  19530. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19531. }
  19532. Box.prototype._regenerateVertexData = function () {
  19533. return BABYLON.VertexData.CreateBox(this.size);
  19534. };
  19535. Box.prototype.copy = function (id) {
  19536. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19537. };
  19538. return Box;
  19539. })(_Primitive);
  19540. Primitives.Box = Box;
  19541. var Sphere = (function (_super) {
  19542. __extends(Sphere, _super);
  19543. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  19544. this.segments = segments;
  19545. this.diameter = diameter;
  19546. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19547. }
  19548. Sphere.prototype._regenerateVertexData = function () {
  19549. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  19550. };
  19551. Sphere.prototype.copy = function (id) {
  19552. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  19553. };
  19554. return Sphere;
  19555. })(_Primitive);
  19556. Primitives.Sphere = Sphere;
  19557. var Cylinder = (function (_super) {
  19558. __extends(Cylinder, _super);
  19559. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  19560. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19561. this.height = height;
  19562. this.diameterTop = diameterTop;
  19563. this.diameterBottom = diameterBottom;
  19564. this.tessellation = tessellation;
  19565. this.subdivisions = subdivisions;
  19566. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19567. }
  19568. Cylinder.prototype._regenerateVertexData = function () {
  19569. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  19570. };
  19571. Cylinder.prototype.copy = function (id) {
  19572. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  19573. };
  19574. return Cylinder;
  19575. })(_Primitive);
  19576. Primitives.Cylinder = Cylinder;
  19577. var Torus = (function (_super) {
  19578. __extends(Torus, _super);
  19579. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  19580. this.diameter = diameter;
  19581. this.thickness = thickness;
  19582. this.tessellation = tessellation;
  19583. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19584. }
  19585. Torus.prototype._regenerateVertexData = function () {
  19586. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  19587. };
  19588. Torus.prototype.copy = function (id) {
  19589. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  19590. };
  19591. return Torus;
  19592. })(_Primitive);
  19593. Primitives.Torus = Torus;
  19594. var Ground = (function (_super) {
  19595. __extends(Ground, _super);
  19596. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  19597. this.width = width;
  19598. this.height = height;
  19599. this.subdivisions = subdivisions;
  19600. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19601. }
  19602. Ground.prototype._regenerateVertexData = function () {
  19603. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  19604. };
  19605. Ground.prototype.copy = function (id) {
  19606. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  19607. };
  19608. return Ground;
  19609. })(_Primitive);
  19610. Primitives.Ground = Ground;
  19611. var TiledGround = (function (_super) {
  19612. __extends(TiledGround, _super);
  19613. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  19614. this.xmin = xmin;
  19615. this.zmin = zmin;
  19616. this.xmax = xmax;
  19617. this.zmax = zmax;
  19618. this.subdivisions = subdivisions;
  19619. this.precision = precision;
  19620. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19621. }
  19622. TiledGround.prototype._regenerateVertexData = function () {
  19623. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  19624. };
  19625. TiledGround.prototype.copy = function (id) {
  19626. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  19627. };
  19628. return TiledGround;
  19629. })(_Primitive);
  19630. Primitives.TiledGround = TiledGround;
  19631. var Plane = (function (_super) {
  19632. __extends(Plane, _super);
  19633. function Plane(id, scene, size, canBeRegenerated, mesh) {
  19634. this.size = size;
  19635. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19636. }
  19637. Plane.prototype._regenerateVertexData = function () {
  19638. return BABYLON.VertexData.CreatePlane(this.size);
  19639. };
  19640. Plane.prototype.copy = function (id) {
  19641. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19642. };
  19643. return Plane;
  19644. })(_Primitive);
  19645. Primitives.Plane = Plane;
  19646. var TorusKnot = (function (_super) {
  19647. __extends(TorusKnot, _super);
  19648. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  19649. this.radius = radius;
  19650. this.tube = tube;
  19651. this.radialSegments = radialSegments;
  19652. this.tubularSegments = tubularSegments;
  19653. this.p = p;
  19654. this.q = q;
  19655. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19656. }
  19657. TorusKnot.prototype._regenerateVertexData = function () {
  19658. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  19659. };
  19660. TorusKnot.prototype.copy = function (id) {
  19661. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  19662. };
  19663. return TorusKnot;
  19664. })(_Primitive);
  19665. Primitives.TorusKnot = TorusKnot;
  19666. })(Geometry.Primitives || (Geometry.Primitives = {}));
  19667. var Primitives = Geometry.Primitives;
  19668. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  19669. var Geometry = BABYLON.Geometry;
  19670. })(BABYLON || (BABYLON = {}));
  19671. var __extends = this.__extends || function (d, b) {
  19672. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19673. function __() { this.constructor = d; }
  19674. __.prototype = b.prototype;
  19675. d.prototype = new __();
  19676. };
  19677. var BABYLON;
  19678. (function (BABYLON) {
  19679. var GroundMesh = (function (_super) {
  19680. __extends(GroundMesh, _super);
  19681. function GroundMesh(name, scene) {
  19682. _super.call(this, name, scene);
  19683. this.generateOctree = false;
  19684. this._worldInverse = new BABYLON.Matrix();
  19685. }
  19686. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  19687. get: function () {
  19688. return this._subdivisions;
  19689. },
  19690. enumerable: true,
  19691. configurable: true
  19692. });
  19693. GroundMesh.prototype.optimize = function (chunksCount) {
  19694. this.subdivide(this._subdivisions);
  19695. this.createOrUpdateSubmeshesOctree(32);
  19696. };
  19697. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  19698. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  19699. this.getWorldMatrix().invertToRef(this._worldInverse);
  19700. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  19701. var pickInfo = this.intersects(ray);
  19702. if (pickInfo.hit) {
  19703. return pickInfo.pickedPoint.y;
  19704. }
  19705. return 0;
  19706. };
  19707. return GroundMesh;
  19708. })(BABYLON.Mesh);
  19709. BABYLON.GroundMesh = GroundMesh;
  19710. })(BABYLON || (BABYLON = {}));
  19711. var __extends = this.__extends || function (d, b) {
  19712. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19713. function __() { this.constructor = d; }
  19714. __.prototype = b.prototype;
  19715. d.prototype = new __();
  19716. };
  19717. var BABYLON;
  19718. (function (BABYLON) {
  19719. var GamepadCamera = (function (_super) {
  19720. __extends(GamepadCamera, _super);
  19721. function GamepadCamera(name, position, scene) {
  19722. var _this = this;
  19723. _super.call(this, name, position, scene);
  19724. this.angularSensibility = 200;
  19725. this.moveSensibility = 75;
  19726. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19727. _this._onNewGameConnected(gamepad);
  19728. });
  19729. }
  19730. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19731. if (gamepad.index === 0) {
  19732. this._gamepad = gamepad;
  19733. }
  19734. };
  19735. GamepadCamera.prototype._checkInputs = function () {
  19736. if (!this._gamepad) {
  19737. return;
  19738. }
  19739. var LSValues = this._gamepad.leftStick;
  19740. var normalizedLX = LSValues.x / this.moveSensibility;
  19741. var normalizedLY = LSValues.y / this.moveSensibility;
  19742. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19743. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19744. var RSValues = this._gamepad.rightStick;
  19745. var normalizedRX = RSValues.x / this.angularSensibility;
  19746. var normalizedRY = RSValues.y / this.angularSensibility;
  19747. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  19748. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  19749. ;
  19750. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19751. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19752. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19753. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  19754. };
  19755. GamepadCamera.prototype.dispose = function () {
  19756. this._gamepads.dispose();
  19757. _super.prototype.dispose.call(this);
  19758. };
  19759. return GamepadCamera;
  19760. })(BABYLON.FreeCamera);
  19761. BABYLON.GamepadCamera = GamepadCamera;
  19762. })(BABYLON || (BABYLON = {}));
  19763. var __extends = this.__extends || function (d, b) {
  19764. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19765. function __() { this.constructor = d; }
  19766. __.prototype = b.prototype;
  19767. d.prototype = new __();
  19768. };
  19769. var BABYLON;
  19770. (function (BABYLON) {
  19771. var Gamepads = (function () {
  19772. function Gamepads(ongamedpadconnected) {
  19773. var _this = this;
  19774. this.babylonGamepads = [];
  19775. this.oneGamepadConnected = false;
  19776. this.isMonitoring = false;
  19777. this.gamepadEventSupported = 'GamepadEvent' in window;
  19778. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  19779. 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=";
  19780. this._callbackGamepadConnected = ongamedpadconnected;
  19781. if (this.gamepadSupportAvailable) {
  19782. if (this.gamepadEventSupported) {
  19783. window.addEventListener('gamepadconnected', function (evt) {
  19784. _this._onGamepadConnected(evt);
  19785. }, false);
  19786. window.addEventListener('gamepaddisconnected', function (evt) {
  19787. _this._onGamepadDisconnected(evt);
  19788. }, false);
  19789. } else {
  19790. this._startMonitoringGamepads();
  19791. }
  19792. if (!this.oneGamepadConnected) {
  19793. this._insertGamepadDOMInstructions();
  19794. }
  19795. } else {
  19796. this._insertGamepadDOMNotSupported();
  19797. }
  19798. }
  19799. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  19800. Gamepads.gamepadDOMInfo = document.createElement("div");
  19801. var buttonAImage = document.createElement("img");
  19802. buttonAImage.src = this.buttonADataURL;
  19803. var spanMessage = document.createElement("span");
  19804. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  19805. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  19806. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19807. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19808. Gamepads.gamepadDOMInfo.style.width = "100%";
  19809. Gamepads.gamepadDOMInfo.style.height = "48px";
  19810. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19811. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19812. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19813. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19814. buttonAImage.style.position = "relative";
  19815. buttonAImage.style.bottom = "8px";
  19816. spanMessage.style.position = "relative";
  19817. spanMessage.style.fontSize = "32px";
  19818. spanMessage.style.bottom = "32px";
  19819. spanMessage.style.color = "green";
  19820. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19821. };
  19822. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  19823. Gamepads.gamepadDOMInfo = document.createElement("div");
  19824. var spanMessage = document.createElement("span");
  19825. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  19826. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19827. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19828. Gamepads.gamepadDOMInfo.style.width = "100%";
  19829. Gamepads.gamepadDOMInfo.style.height = "40px";
  19830. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19831. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19832. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19833. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19834. spanMessage.style.position = "relative";
  19835. spanMessage.style.fontSize = "32px";
  19836. spanMessage.style.color = "red";
  19837. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19838. };
  19839. Gamepads.prototype.dispose = function () {
  19840. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19841. };
  19842. Gamepads.prototype._onGamepadConnected = function (evt) {
  19843. var newGamepad = this._addNewGamepad(evt.gamepad);
  19844. if (this._callbackGamepadConnected)
  19845. this._callbackGamepadConnected(newGamepad);
  19846. this._startMonitoringGamepads();
  19847. };
  19848. Gamepads.prototype._addNewGamepad = function (gamepad) {
  19849. if (!this.oneGamepadConnected) {
  19850. this.oneGamepadConnected = true;
  19851. if (Gamepads.gamepadDOMInfo) {
  19852. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19853. Gamepads.gamepadDOMInfo = null;
  19854. }
  19855. }
  19856. var newGamepad;
  19857. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  19858. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  19859. } else {
  19860. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  19861. }
  19862. this.babylonGamepads.push(newGamepad);
  19863. return newGamepad;
  19864. };
  19865. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  19866. for (var i in this.babylonGamepads) {
  19867. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  19868. this.babylonGamepads.splice(i, 1);
  19869. break;
  19870. }
  19871. }
  19872. if (this.babylonGamepads.length == 0) {
  19873. this._stopMonitoringGamepads();
  19874. }
  19875. };
  19876. Gamepads.prototype._startMonitoringGamepads = function () {
  19877. if (!this.isMonitoring) {
  19878. this.isMonitoring = true;
  19879. this._checkGamepadsStatus();
  19880. }
  19881. };
  19882. Gamepads.prototype._stopMonitoringGamepads = function () {
  19883. this.isMonitoring = false;
  19884. };
  19885. Gamepads.prototype._checkGamepadsStatus = function () {
  19886. var _this = this;
  19887. this._updateGamepadObjects();
  19888. for (var i in this.babylonGamepads) {
  19889. this.babylonGamepads[i].update();
  19890. }
  19891. if (this.isMonitoring) {
  19892. if (window.requestAnimationFrame) {
  19893. window.requestAnimationFrame(function () {
  19894. _this._checkGamepadsStatus();
  19895. });
  19896. } else if (window.mozRequestAnimationFrame) {
  19897. window.mozRequestAnimationFrame(function () {
  19898. _this._checkGamepadsStatus();
  19899. });
  19900. } else if (window.webkitRequestAnimationFrame) {
  19901. window.webkitRequestAnimationFrame(function () {
  19902. _this._checkGamepadsStatus();
  19903. });
  19904. }
  19905. }
  19906. };
  19907. Gamepads.prototype._updateGamepadObjects = function () {
  19908. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  19909. for (var i = 0; i < gamepads.length; i++) {
  19910. if (gamepads[i]) {
  19911. if (!(gamepads[i].index in this.babylonGamepads)) {
  19912. var newGamepad = this._addNewGamepad(gamepads[i]);
  19913. if (this._callbackGamepadConnected) {
  19914. this._callbackGamepadConnected(newGamepad);
  19915. }
  19916. } else {
  19917. this.babylonGamepads[i].browserGamepad = gamepads[i];
  19918. }
  19919. }
  19920. }
  19921. };
  19922. return Gamepads;
  19923. })();
  19924. BABYLON.Gamepads = Gamepads;
  19925. var StickValues = (function () {
  19926. function StickValues(x, y) {
  19927. this.x = x;
  19928. this.y = y;
  19929. }
  19930. return StickValues;
  19931. })();
  19932. BABYLON.StickValues = StickValues;
  19933. var Gamepad = (function () {
  19934. function Gamepad(id, index, browserGamepad) {
  19935. this.id = id;
  19936. this.index = index;
  19937. this.browserGamepad = browserGamepad;
  19938. if (this.browserGamepad.axes.length >= 2) {
  19939. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19940. }
  19941. if (this.browserGamepad.axes.length >= 4) {
  19942. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19943. }
  19944. }
  19945. Gamepad.prototype.onleftstickchanged = function (callback) {
  19946. this._onleftstickchanged = callback;
  19947. };
  19948. Gamepad.prototype.onrightstickchanged = function (callback) {
  19949. this._onrightstickchanged = callback;
  19950. };
  19951. Object.defineProperty(Gamepad.prototype, "leftStick", {
  19952. get: function () {
  19953. return this._leftStick;
  19954. },
  19955. set: function (newValues) {
  19956. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  19957. this._onleftstickchanged(newValues);
  19958. }
  19959. this._leftStick = newValues;
  19960. },
  19961. enumerable: true,
  19962. configurable: true
  19963. });
  19964. Object.defineProperty(Gamepad.prototype, "rightStick", {
  19965. get: function () {
  19966. return this._rightStick;
  19967. },
  19968. set: function (newValues) {
  19969. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  19970. this._onrightstickchanged(newValues);
  19971. }
  19972. this._rightStick = newValues;
  19973. },
  19974. enumerable: true,
  19975. configurable: true
  19976. });
  19977. Gamepad.prototype.update = function () {
  19978. if (this._leftStick) {
  19979. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19980. }
  19981. if (this._rightStick) {
  19982. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19983. }
  19984. };
  19985. return Gamepad;
  19986. })();
  19987. BABYLON.Gamepad = Gamepad;
  19988. var GenericPad = (function (_super) {
  19989. __extends(GenericPad, _super);
  19990. function GenericPad(id, index, gamepad) {
  19991. _super.call(this, id, index, gamepad);
  19992. this.id = id;
  19993. this.index = index;
  19994. this.gamepad = gamepad;
  19995. this._buttons = new Array(gamepad.buttons.length);
  19996. }
  19997. GenericPad.prototype.onbuttondown = function (callback) {
  19998. this._onbuttondown = callback;
  19999. };
  20000. GenericPad.prototype.onbuttonup = function (callback) {
  20001. this._onbuttonup = callback;
  20002. };
  20003. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  20004. if (newValue !== currentValue) {
  20005. if (this._onbuttondown && newValue === 1) {
  20006. this._onbuttondown(buttonIndex);
  20007. }
  20008. if (this._onbuttonup && newValue === 0) {
  20009. this._onbuttonup(buttonIndex);
  20010. }
  20011. }
  20012. return newValue;
  20013. };
  20014. GenericPad.prototype.update = function () {
  20015. _super.prototype.update.call(this);
  20016. for (var index = 0; index < this._buttons.length; index++) {
  20017. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  20018. }
  20019. };
  20020. return GenericPad;
  20021. })(Gamepad);
  20022. BABYLON.GenericPad = GenericPad;
  20023. (function (Xbox360Button) {
  20024. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  20025. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  20026. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  20027. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  20028. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  20029. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  20030. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  20031. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  20032. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  20033. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  20034. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  20035. var Xbox360Button = BABYLON.Xbox360Button;
  20036. (function (Xbox360Dpad) {
  20037. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  20038. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  20039. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  20040. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  20041. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  20042. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  20043. var Xbox360Pad = (function (_super) {
  20044. __extends(Xbox360Pad, _super);
  20045. function Xbox360Pad() {
  20046. _super.apply(this, arguments);
  20047. this._leftTrigger = 0;
  20048. this._rightTrigger = 0;
  20049. this._buttonA = 0;
  20050. this._buttonB = 0;
  20051. this._buttonX = 0;
  20052. this._buttonY = 0;
  20053. this._buttonBack = 0;
  20054. this._buttonStart = 0;
  20055. this._buttonLB = 0;
  20056. this._buttonRB = 0;
  20057. this._buttonLeftStick = 0;
  20058. this._buttonRightStick = 0;
  20059. this._dPadUp = 0;
  20060. this._dPadDown = 0;
  20061. this._dPadLeft = 0;
  20062. this._dPadRight = 0;
  20063. }
  20064. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  20065. this._onlefttriggerchanged = callback;
  20066. };
  20067. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  20068. this._onrighttriggerchanged = callback;
  20069. };
  20070. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  20071. get: function () {
  20072. return this._leftTrigger;
  20073. },
  20074. set: function (newValue) {
  20075. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  20076. this._onlefttriggerchanged(newValue);
  20077. }
  20078. this._leftTrigger = newValue;
  20079. },
  20080. enumerable: true,
  20081. configurable: true
  20082. });
  20083. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  20084. get: function () {
  20085. return this._rightTrigger;
  20086. },
  20087. set: function (newValue) {
  20088. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  20089. this._onrighttriggerchanged(newValue);
  20090. }
  20091. this._rightTrigger = newValue;
  20092. },
  20093. enumerable: true,
  20094. configurable: true
  20095. });
  20096. Xbox360Pad.prototype.onbuttondown = function (callback) {
  20097. this._onbuttondown = callback;
  20098. };
  20099. Xbox360Pad.prototype.onbuttonup = function (callback) {
  20100. this._onbuttonup = callback;
  20101. };
  20102. Xbox360Pad.prototype.ondpaddown = function (callback) {
  20103. this._ondpaddown = callback;
  20104. };
  20105. Xbox360Pad.prototype.ondpadup = function (callback) {
  20106. this._ondpadup = callback;
  20107. };
  20108. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  20109. if (newValue !== currentValue) {
  20110. if (this._onbuttondown && newValue === 1) {
  20111. this._onbuttondown(buttonType);
  20112. }
  20113. if (this._onbuttonup && newValue === 0) {
  20114. this._onbuttonup(buttonType);
  20115. }
  20116. }
  20117. return newValue;
  20118. };
  20119. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  20120. if (newValue !== currentValue) {
  20121. if (this._ondpaddown && newValue === 1) {
  20122. this._ondpaddown(buttonType);
  20123. }
  20124. if (this._ondpadup && newValue === 0) {
  20125. this._ondpadup(buttonType);
  20126. }
  20127. }
  20128. return newValue;
  20129. };
  20130. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  20131. get: function () {
  20132. return this._buttonA;
  20133. },
  20134. set: function (value) {
  20135. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  20136. },
  20137. enumerable: true,
  20138. configurable: true
  20139. });
  20140. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  20141. get: function () {
  20142. return this._buttonB;
  20143. },
  20144. set: function (value) {
  20145. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  20146. },
  20147. enumerable: true,
  20148. configurable: true
  20149. });
  20150. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  20151. get: function () {
  20152. return this._buttonX;
  20153. },
  20154. set: function (value) {
  20155. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  20156. },
  20157. enumerable: true,
  20158. configurable: true
  20159. });
  20160. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  20161. get: function () {
  20162. return this._buttonY;
  20163. },
  20164. set: function (value) {
  20165. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  20166. },
  20167. enumerable: true,
  20168. configurable: true
  20169. });
  20170. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  20171. get: function () {
  20172. return this._buttonStart;
  20173. },
  20174. set: function (value) {
  20175. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  20176. },
  20177. enumerable: true,
  20178. configurable: true
  20179. });
  20180. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  20181. get: function () {
  20182. return this._buttonBack;
  20183. },
  20184. set: function (value) {
  20185. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  20186. },
  20187. enumerable: true,
  20188. configurable: true
  20189. });
  20190. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  20191. get: function () {
  20192. return this._buttonLB;
  20193. },
  20194. set: function (value) {
  20195. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  20196. },
  20197. enumerable: true,
  20198. configurable: true
  20199. });
  20200. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  20201. get: function () {
  20202. return this._buttonRB;
  20203. },
  20204. set: function (value) {
  20205. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  20206. },
  20207. enumerable: true,
  20208. configurable: true
  20209. });
  20210. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  20211. get: function () {
  20212. return this._buttonLeftStick;
  20213. },
  20214. set: function (value) {
  20215. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  20216. },
  20217. enumerable: true,
  20218. configurable: true
  20219. });
  20220. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  20221. get: function () {
  20222. return this._buttonRightStick;
  20223. },
  20224. set: function (value) {
  20225. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  20226. },
  20227. enumerable: true,
  20228. configurable: true
  20229. });
  20230. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  20231. get: function () {
  20232. return this._dPadUp;
  20233. },
  20234. set: function (value) {
  20235. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  20236. },
  20237. enumerable: true,
  20238. configurable: true
  20239. });
  20240. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  20241. get: function () {
  20242. return this._dPadDown;
  20243. },
  20244. set: function (value) {
  20245. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  20246. },
  20247. enumerable: true,
  20248. configurable: true
  20249. });
  20250. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  20251. get: function () {
  20252. return this._dPadLeft;
  20253. },
  20254. set: function (value) {
  20255. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  20256. },
  20257. enumerable: true,
  20258. configurable: true
  20259. });
  20260. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  20261. get: function () {
  20262. return this._dPadRight;
  20263. },
  20264. set: function (value) {
  20265. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  20266. },
  20267. enumerable: true,
  20268. configurable: true
  20269. });
  20270. Xbox360Pad.prototype.update = function () {
  20271. _super.prototype.update.call(this);
  20272. this.buttonA = this.browserGamepad.buttons[0].value;
  20273. this.buttonB = this.browserGamepad.buttons[1].value;
  20274. this.buttonX = this.browserGamepad.buttons[2].value;
  20275. this.buttonY = this.browserGamepad.buttons[3].value;
  20276. this.buttonLB = this.browserGamepad.buttons[4].value;
  20277. this.buttonRB = this.browserGamepad.buttons[5].value;
  20278. this.leftTrigger = this.browserGamepad.buttons[6].value;
  20279. this.rightTrigger = this.browserGamepad.buttons[7].value;
  20280. this.buttonBack = this.browserGamepad.buttons[8].value;
  20281. this.buttonStart = this.browserGamepad.buttons[9].value;
  20282. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  20283. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  20284. this.dPadUp = this.browserGamepad.buttons[12].value;
  20285. this.dPadDown = this.browserGamepad.buttons[13].value;
  20286. this.dPadLeft = this.browserGamepad.buttons[14].value;
  20287. this.dPadRight = this.browserGamepad.buttons[15].value;
  20288. };
  20289. return Xbox360Pad;
  20290. })(Gamepad);
  20291. BABYLON.Xbox360Pad = Xbox360Pad;
  20292. })(BABYLON || (BABYLON = {}));
  20293. var __extends = this.__extends || function (d, b) {
  20294. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20295. function __() { this.constructor = d; }
  20296. __.prototype = b.prototype;
  20297. d.prototype = new __();
  20298. };
  20299. var BABYLON;
  20300. (function (BABYLON) {
  20301. var LinesMesh = (function (_super) {
  20302. __extends(LinesMesh, _super);
  20303. function LinesMesh(name, scene, updatable) {
  20304. if (typeof updatable === "undefined") { updatable = false; }
  20305. _super.call(this, name, scene);
  20306. this.color = new BABYLON.Color3(1, 1, 1);
  20307. this.alpha = 1;
  20308. this._indices = new Array();
  20309. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  20310. attributes: ["position"],
  20311. uniforms: ["worldViewProjection", "color"],
  20312. needAlphaBlending: true
  20313. });
  20314. }
  20315. Object.defineProperty(LinesMesh.prototype, "material", {
  20316. get: function () {
  20317. return this._colorShader;
  20318. },
  20319. enumerable: true,
  20320. configurable: true
  20321. });
  20322. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  20323. get: function () {
  20324. return false;
  20325. },
  20326. enumerable: true,
  20327. configurable: true
  20328. });
  20329. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  20330. get: function () {
  20331. return false;
  20332. },
  20333. enumerable: true,
  20334. configurable: true
  20335. });
  20336. LinesMesh.prototype._bind = function (subMesh, effect, drawAs) {
  20337. var engine = this.getScene().getEngine();
  20338. var indexToBind = this._geometry.getIndexBuffer();
  20339. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  20340. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  20341. };
  20342. LinesMesh.prototype._draw = function (subMesh, drawAs, instancesCount) {
  20343. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20344. return;
  20345. }
  20346. var engine = this.getScene().getEngine();
  20347. engine.draw(WebGLRenderingContext.LINES, subMesh.indexStart, subMesh.indexCount);
  20348. };
  20349. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  20350. return null;
  20351. };
  20352. LinesMesh.prototype.dispose = function (doNotRecurse) {
  20353. this._colorShader.dispose();
  20354. _super.prototype.dispose.call(this, doNotRecurse);
  20355. };
  20356. return LinesMesh;
  20357. })(BABYLON.Mesh);
  20358. BABYLON.LinesMesh = LinesMesh;
  20359. })(BABYLON || (BABYLON = {}));
  20360. var BABYLON;
  20361. (function (BABYLON) {
  20362. var OutlineRenderer = (function () {
  20363. function OutlineRenderer(scene) {
  20364. this._scene = scene;
  20365. }
  20366. OutlineRenderer.prototype.render = function (subMesh, batch) {
  20367. var scene = this._scene;
  20368. var engine = this._scene.getEngine();
  20369. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  20370. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  20371. return;
  20372. }
  20373. var mesh = subMesh.getRenderingMesh();
  20374. var material = subMesh.getMaterial();
  20375. engine.enableEffect(this._effect);
  20376. this._effect.setFloat("offset", mesh.outlineWidth);
  20377. this._effect.setColor3("color", mesh.outlineColor);
  20378. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20379. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  20380. if (useBones) {
  20381. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  20382. }
  20383. mesh._bind(subMesh, this._effect, WebGLRenderingContext.TRIANGLES);
  20384. if (material && material.needAlphaTesting()) {
  20385. var alphaTexture = material.getAlphaTestTexture();
  20386. this._effect.setTexture("diffuseSampler", alphaTexture);
  20387. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  20388. }
  20389. if (hardwareInstancedRendering) {
  20390. mesh._renderWithInstances(subMesh, WebGLRenderingContext.TRIANGLES, batch, this._effect, engine);
  20391. } else {
  20392. if (batch.renderSelf[subMesh._id]) {
  20393. this._effect.setMatrix("world", mesh.getWorldMatrix());
  20394. mesh._draw(subMesh, WebGLRenderingContext.TRIANGLES);
  20395. }
  20396. if (batch.visibleInstances[subMesh._id]) {
  20397. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20398. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20399. this._effect.setMatrix("world", instance.getWorldMatrix());
  20400. mesh._draw(subMesh, WebGLRenderingContext.TRIANGLES);
  20401. }
  20402. }
  20403. }
  20404. };
  20405. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  20406. var defines = [];
  20407. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  20408. var mesh = subMesh.getMesh();
  20409. var material = subMesh.getMaterial();
  20410. if (material && material.needAlphaTesting()) {
  20411. defines.push("#define ALPHATEST");
  20412. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20413. attribs.push(BABYLON.VertexBuffer.UVKind);
  20414. defines.push("#define UV1");
  20415. }
  20416. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20417. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20418. defines.push("#define UV2");
  20419. }
  20420. }
  20421. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20422. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20423. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20424. defines.push("#define BONES");
  20425. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  20426. }
  20427. if (useInstances) {
  20428. defines.push("#define INSTANCES");
  20429. attribs.push("world0");
  20430. attribs.push("world1");
  20431. attribs.push("world2");
  20432. attribs.push("world3");
  20433. }
  20434. var join = defines.join("\n");
  20435. if (this._cachedDefines != join) {
  20436. this._cachedDefines = join;
  20437. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  20438. }
  20439. return this._effect.isReady();
  20440. };
  20441. return OutlineRenderer;
  20442. })();
  20443. BABYLON.OutlineRenderer = OutlineRenderer;
  20444. })(BABYLON || (BABYLON = {}));
  20445. var BABYLON;
  20446. (function (BABYLON) {
  20447. var MeshAssetTask = (function () {
  20448. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  20449. this.name = name;
  20450. this.meshesNames = meshesNames;
  20451. this.rootUrl = rootUrl;
  20452. this.sceneFilename = sceneFilename;
  20453. this.isCompleted = false;
  20454. }
  20455. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20456. var _this = this;
  20457. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  20458. _this.loadedMeshes = meshes;
  20459. _this.loadedParticleSystems = particleSystems;
  20460. _this.loadedSkeletons = skeletons;
  20461. _this.isCompleted = true;
  20462. if (_this.onSuccess) {
  20463. _this.onSuccess(_this);
  20464. }
  20465. onSuccess();
  20466. }, null, function () {
  20467. if (_this.onError) {
  20468. _this.onError(_this);
  20469. }
  20470. onError();
  20471. });
  20472. };
  20473. return MeshAssetTask;
  20474. })();
  20475. BABYLON.MeshAssetTask = MeshAssetTask;
  20476. var TextFileAssetTask = (function () {
  20477. function TextFileAssetTask(name, url) {
  20478. this.name = name;
  20479. this.url = url;
  20480. this.isCompleted = false;
  20481. }
  20482. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20483. var _this = this;
  20484. BABYLON.Tools.LoadFile(this.url, function (data) {
  20485. _this.text = data;
  20486. _this.isCompleted = true;
  20487. if (_this.onSuccess) {
  20488. _this.onSuccess(_this);
  20489. }
  20490. onSuccess();
  20491. }, null, scene.database, false, function () {
  20492. if (_this.onError) {
  20493. _this.onError(_this);
  20494. }
  20495. onError();
  20496. });
  20497. };
  20498. return TextFileAssetTask;
  20499. })();
  20500. BABYLON.TextFileAssetTask = TextFileAssetTask;
  20501. var BinaryFileAssetTask = (function () {
  20502. function BinaryFileAssetTask(name, url) {
  20503. this.name = name;
  20504. this.url = url;
  20505. this.isCompleted = false;
  20506. }
  20507. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20508. var _this = this;
  20509. BABYLON.Tools.LoadFile(this.url, function (data) {
  20510. _this.data = data;
  20511. _this.isCompleted = true;
  20512. if (_this.onSuccess) {
  20513. _this.onSuccess(_this);
  20514. }
  20515. onSuccess();
  20516. }, null, scene.database, true, function () {
  20517. if (_this.onError) {
  20518. _this.onError(_this);
  20519. }
  20520. onError();
  20521. });
  20522. };
  20523. return BinaryFileAssetTask;
  20524. })();
  20525. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  20526. var ImageAssetTask = (function () {
  20527. function ImageAssetTask(name, url) {
  20528. this.name = name;
  20529. this.url = url;
  20530. this.isCompleted = false;
  20531. }
  20532. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20533. var _this = this;
  20534. var img = new Image();
  20535. img.onload = function () {
  20536. _this.image = img;
  20537. _this.isCompleted = true;
  20538. if (_this.onSuccess) {
  20539. _this.onSuccess(_this);
  20540. }
  20541. onSuccess();
  20542. };
  20543. img.onerror = function () {
  20544. if (_this.onError) {
  20545. _this.onError(_this);
  20546. }
  20547. onError();
  20548. };
  20549. img.src = this.url;
  20550. };
  20551. return ImageAssetTask;
  20552. })();
  20553. BABYLON.ImageAssetTask = ImageAssetTask;
  20554. var TextureAssetTask = (function () {
  20555. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  20556. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20557. this.name = name;
  20558. this.url = url;
  20559. this.noMipmap = noMipmap;
  20560. this.invertY = invertY;
  20561. this.samplingMode = samplingMode;
  20562. this.isCompleted = false;
  20563. }
  20564. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20565. var _this = this;
  20566. var onload = function () {
  20567. _this.isCompleted = true;
  20568. if (_this.onSuccess) {
  20569. _this.onSuccess(_this);
  20570. }
  20571. onSuccess();
  20572. };
  20573. var onerror = function () {
  20574. if (_this.onError) {
  20575. _this.onError(_this);
  20576. }
  20577. onError();
  20578. };
  20579. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  20580. };
  20581. return TextureAssetTask;
  20582. })();
  20583. BABYLON.TextureAssetTask = TextureAssetTask;
  20584. var AssetsManager = (function () {
  20585. function AssetsManager(scene) {
  20586. this._tasks = new Array();
  20587. this._waitingTasksCount = 0;
  20588. this.useDefaultLoadingScreen = true;
  20589. this._scene = scene;
  20590. }
  20591. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  20592. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  20593. this._tasks.push(task);
  20594. return task;
  20595. };
  20596. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  20597. var task = new TextFileAssetTask(taskName, url);
  20598. this._tasks.push(task);
  20599. return task;
  20600. };
  20601. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  20602. var task = new BinaryFileAssetTask(taskName, url);
  20603. this._tasks.push(task);
  20604. return task;
  20605. };
  20606. AssetsManager.prototype.addImageTask = function (taskName, url) {
  20607. var task = new ImageAssetTask(taskName, url);
  20608. this._tasks.push(task);
  20609. return task;
  20610. };
  20611. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  20612. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20613. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  20614. this._tasks.push(task);
  20615. return task;
  20616. };
  20617. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  20618. this._waitingTasksCount--;
  20619. if (this._waitingTasksCount === 0) {
  20620. if (this.onFinish) {
  20621. this.onFinish(this._tasks);
  20622. }
  20623. this._scene.getEngine().hideLoadingUI();
  20624. }
  20625. };
  20626. AssetsManager.prototype._runTask = function (task) {
  20627. var _this = this;
  20628. task.run(this._scene, function () {
  20629. if (_this.onTaskSuccess) {
  20630. _this.onTaskSuccess(task);
  20631. }
  20632. _this._decreaseWaitingTasksCount();
  20633. }, function () {
  20634. if (_this.onTaskError) {
  20635. _this.onTaskError(task);
  20636. }
  20637. _this._decreaseWaitingTasksCount();
  20638. });
  20639. };
  20640. AssetsManager.prototype.reset = function () {
  20641. this._tasks = new Array();
  20642. return this;
  20643. };
  20644. AssetsManager.prototype.load = function () {
  20645. this._waitingTasksCount = this._tasks.length;
  20646. if (this._waitingTasksCount === 0) {
  20647. if (this.onFinish) {
  20648. this.onFinish(this._tasks);
  20649. }
  20650. return this;
  20651. }
  20652. if (this.useDefaultLoadingScreen) {
  20653. this._scene.getEngine().displayLoadingUI();
  20654. }
  20655. for (var index = 0; index < this._tasks.length; index++) {
  20656. var task = this._tasks[index];
  20657. this._runTask(task);
  20658. }
  20659. return this;
  20660. };
  20661. return AssetsManager;
  20662. })();
  20663. BABYLON.AssetsManager = AssetsManager;
  20664. })(BABYLON || (BABYLON = {}));
  20665. var __extends = this.__extends || function (d, b) {
  20666. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20667. function __() { this.constructor = d; }
  20668. __.prototype = b.prototype;
  20669. d.prototype = new __();
  20670. };
  20671. var BABYLON;
  20672. (function (BABYLON) {
  20673. var WebVRCamera = (function (_super) {
  20674. __extends(WebVRCamera, _super);
  20675. function WebVRCamera(name, position, scene) {
  20676. _super.call(this, name, position, scene);
  20677. this._hmdDevice = null;
  20678. this._sensorDevice = null;
  20679. this._cacheState = null;
  20680. this._cacheQuaternion = new BABYLON.Quaternion();
  20681. this._cacheRotation = BABYLON.Vector3.Zero();
  20682. this._vrEnabled = false;
  20683. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  20684. }
  20685. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  20686. var size = devices.length;
  20687. var i = 0;
  20688. this._sensorDevice = null;
  20689. this._hmdDevice = null;
  20690. while (i < size && this._hmdDevice === null) {
  20691. if (devices[i] instanceof HMDVRDevice) {
  20692. this._hmdDevice = devices[i];
  20693. }
  20694. i++;
  20695. }
  20696. i = 0;
  20697. while (i < size && this._sensorDevice === null) {
  20698. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  20699. this._sensorDevice = devices[i];
  20700. }
  20701. i++;
  20702. }
  20703. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  20704. };
  20705. WebVRCamera.prototype._update = function () {
  20706. if (this._vrEnabled) {
  20707. this._cacheState = this._sensorDevice.getState();
  20708. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  20709. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  20710. this.rotation.x = -this._cacheRotation.z;
  20711. this.rotation.y = -this._cacheRotation.y;
  20712. this.rotation.z = this._cacheRotation.x;
  20713. }
  20714. _super.prototype._update.call(this);
  20715. };
  20716. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  20717. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20718. if (navigator.getVRDevices) {
  20719. navigator.getVRDevices().then(this._getWebVRDevices);
  20720. } else if (navigator.mozGetVRDevices) {
  20721. navigator.mozGetVRDevices(this._getWebVRDevices);
  20722. }
  20723. };
  20724. WebVRCamera.prototype.detachControl = function (element) {
  20725. _super.prototype.detachControl.call(this, element);
  20726. this._vrEnabled = false;
  20727. };
  20728. return WebVRCamera;
  20729. })(BABYLON.OculusCamera);
  20730. BABYLON.WebVRCamera = WebVRCamera;
  20731. })(BABYLON || (BABYLON = {}));
  20732. var __extends = this.__extends || function (d, b) {
  20733. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20734. function __() { this.constructor = d; }
  20735. __.prototype = b.prototype;
  20736. d.prototype = new __();
  20737. };
  20738. var BABYLON;
  20739. (function (BABYLON) {
  20740. var VRDeviceOrientationCamera = (function (_super) {
  20741. __extends(VRDeviceOrientationCamera, _super);
  20742. function VRDeviceOrientationCamera(name, position, scene) {
  20743. _super.call(this, name, position, scene);
  20744. this._alpha = 0;
  20745. this._beta = 0;
  20746. this._gamma = 0;
  20747. }
  20748. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  20749. this._alpha = +evt.alpha | 0;
  20750. this._beta = +evt.beta | 0;
  20751. this._gamma = +evt.gamma | 0;
  20752. if (this._gamma < 0) {
  20753. this._gamma = 90 + this._gamma;
  20754. } else {
  20755. this._gamma = 270 - this._gamma;
  20756. }
  20757. this.rotation.x = this._gamma / 180.0 * Math.PI;
  20758. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  20759. this.rotation.z = this._beta / 180.0 * Math.PI;
  20760. };
  20761. return VRDeviceOrientationCamera;
  20762. })(BABYLON.OculusCamera);
  20763. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  20764. })(BABYLON || (BABYLON = {}));