babylon.2.0-beta.debug.js 1.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. };
  29. Color3.prototype.toColor4 = function (alpha) {
  30. if (alpha === void 0) { alpha = 1; }
  31. return new Color4(this.r, this.g, this.b, alpha);
  32. };
  33. Color3.prototype.asArray = function () {
  34. var result = [];
  35. this.toArray(result, 0);
  36. return result;
  37. };
  38. Color3.prototype.toLuminance = function () {
  39. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  40. };
  41. Color3.prototype.multiply = function (otherColor) {
  42. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  43. };
  44. Color3.prototype.multiplyToRef = function (otherColor, result) {
  45. result.r = this.r * otherColor.r;
  46. result.g = this.g * otherColor.g;
  47. result.b = this.b * otherColor.b;
  48. };
  49. Color3.prototype.equals = function (otherColor) {
  50. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  51. };
  52. Color3.prototype.scale = function (scale) {
  53. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  54. };
  55. Color3.prototype.scaleToRef = function (scale, result) {
  56. result.r = this.r * scale;
  57. result.g = this.g * scale;
  58. result.b = this.b * scale;
  59. };
  60. Color3.prototype.add = function (otherColor) {
  61. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  62. };
  63. Color3.prototype.addToRef = function (otherColor, result) {
  64. result.r = this.r + otherColor.r;
  65. result.g = this.g + otherColor.g;
  66. result.b = this.b + otherColor.b;
  67. };
  68. Color3.prototype.subtract = function (otherColor) {
  69. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  70. };
  71. Color3.prototype.subtractToRef = function (otherColor, result) {
  72. result.r = this.r - otherColor.r;
  73. result.g = this.g - otherColor.g;
  74. result.b = this.b - otherColor.b;
  75. };
  76. Color3.prototype.clone = function () {
  77. return new Color3(this.r, this.g, this.b);
  78. };
  79. Color3.prototype.copyFrom = function (source) {
  80. this.r = source.r;
  81. this.g = source.g;
  82. this.b = source.b;
  83. };
  84. Color3.prototype.copyFromFloats = function (r, g, b) {
  85. this.r = r;
  86. this.g = g;
  87. this.b = b;
  88. };
  89. // Statics
  90. Color3.FromArray = function (array, offset) {
  91. if (offset === void 0) { offset = 0; }
  92. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  93. };
  94. Color3.FromInts = function (r, g, b) {
  95. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  96. };
  97. Color3.Lerp = function (start, end, amount) {
  98. var r = start.r + ((end.r - start.r) * amount);
  99. var g = start.g + ((end.g - start.g) * amount);
  100. var b = start.b + ((end.b - start.b) * amount);
  101. return new Color3(r, g, b);
  102. };
  103. Color3.Red = function () {
  104. return new Color3(1, 0, 0);
  105. };
  106. Color3.Green = function () {
  107. return new Color3(0, 1, 0);
  108. };
  109. Color3.Blue = function () {
  110. return new Color3(0, 0, 1);
  111. };
  112. Color3.Black = function () {
  113. return new Color3(0, 0, 0);
  114. };
  115. Color3.White = function () {
  116. return new Color3(1, 1, 1);
  117. };
  118. Color3.Purple = function () {
  119. return new Color3(0.5, 0, 0.5);
  120. };
  121. Color3.Magenta = function () {
  122. return new Color3(1, 0, 1);
  123. };
  124. Color3.Yellow = function () {
  125. return new Color3(1, 1, 0);
  126. };
  127. Color3.Gray = function () {
  128. return new Color3(0.5, 0.5, 0.5);
  129. };
  130. return Color3;
  131. })();
  132. BABYLON.Color3 = Color3;
  133. var Color4 = (function () {
  134. function Color4(r, g, b, a) {
  135. this.r = r;
  136. this.g = g;
  137. this.b = b;
  138. this.a = a;
  139. }
  140. // Operators
  141. Color4.prototype.addInPlace = function (right) {
  142. this.r += right.r;
  143. this.g += right.g;
  144. this.b += right.b;
  145. this.a += right.a;
  146. };
  147. Color4.prototype.asArray = function () {
  148. var result = [];
  149. this.toArray(result, 0);
  150. return result;
  151. };
  152. Color4.prototype.toArray = function (array, index) {
  153. if (index === undefined) {
  154. index = 0;
  155. }
  156. array[index] = this.r;
  157. array[index + 1] = this.g;
  158. array[index + 2] = this.b;
  159. array[index + 3] = this.a;
  160. };
  161. Color4.prototype.add = function (right) {
  162. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  163. };
  164. Color4.prototype.subtract = function (right) {
  165. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  166. };
  167. Color4.prototype.subtractToRef = function (right, result) {
  168. result.r = this.r - right.r;
  169. result.g = this.g - right.g;
  170. result.b = this.b - right.b;
  171. result.a = this.a - right.a;
  172. };
  173. Color4.prototype.scale = function (scale) {
  174. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  175. };
  176. Color4.prototype.scaleToRef = function (scale, result) {
  177. result.r = this.r * scale;
  178. result.g = this.g * scale;
  179. result.b = this.b * scale;
  180. result.a = this.a * scale;
  181. };
  182. Color4.prototype.toString = function () {
  183. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  184. };
  185. Color4.prototype.clone = function () {
  186. return new Color4(this.r, this.g, this.b, this.a);
  187. };
  188. Color4.prototype.copyFrom = function (source) {
  189. this.r = source.r;
  190. this.g = source.g;
  191. this.b = source.b;
  192. this.a = source.a;
  193. };
  194. // Statics
  195. Color4.Lerp = function (left, right, amount) {
  196. var result = new Color4(0, 0, 0, 0);
  197. Color4.LerpToRef(left, right, amount, result);
  198. return result;
  199. };
  200. Color4.LerpToRef = function (left, right, amount, result) {
  201. result.r = left.r + (right.r - left.r) * amount;
  202. result.g = left.g + (right.g - left.g) * amount;
  203. result.b = left.b + (right.b - left.b) * amount;
  204. result.a = left.a + (right.a - left.a) * amount;
  205. };
  206. Color4.FromArray = function (array, offset) {
  207. if (offset === void 0) { offset = 0; }
  208. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  209. };
  210. Color4.FromInts = function (r, g, b, a) {
  211. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  212. };
  213. return Color4;
  214. })();
  215. BABYLON.Color4 = Color4;
  216. var Vector2 = (function () {
  217. function Vector2(x, y) {
  218. this.x = x;
  219. this.y = y;
  220. }
  221. Vector2.prototype.toString = function () {
  222. return "{X: " + this.x + " Y:" + this.y + "}";
  223. };
  224. // Operators
  225. Vector2.prototype.toArray = function (array, index) {
  226. if (index === undefined) {
  227. index = 0;
  228. }
  229. array[index] = this.x;
  230. array[index + 1] = this.y;
  231. };
  232. Vector2.prototype.asArray = function () {
  233. var result = [];
  234. this.toArray(result, 0);
  235. return result;
  236. };
  237. Vector2.prototype.copyFrom = function (source) {
  238. this.x = source.x;
  239. this.y = source.y;
  240. };
  241. Vector2.prototype.copyFromFloats = function (x, y) {
  242. this.x = x;
  243. this.y = y;
  244. };
  245. Vector2.prototype.add = function (otherVector) {
  246. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  247. };
  248. Vector2.prototype.addVector3 = function (otherVector) {
  249. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  250. };
  251. Vector2.prototype.subtract = function (otherVector) {
  252. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  253. };
  254. Vector2.prototype.subtractInPlace = function (otherVector) {
  255. this.x -= otherVector.x;
  256. this.y -= otherVector.y;
  257. };
  258. Vector2.prototype.multiplyInPlace = function (otherVector) {
  259. this.x *= otherVector.x;
  260. this.y *= otherVector.y;
  261. };
  262. Vector2.prototype.multiply = function (otherVector) {
  263. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  264. };
  265. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  266. result.x = this.x * otherVector.x;
  267. result.y = this.y * otherVector.y;
  268. };
  269. Vector2.prototype.multiplyByFloats = function (x, y) {
  270. return new Vector2(this.x * x, this.y * y);
  271. };
  272. Vector2.prototype.divide = function (otherVector) {
  273. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  274. };
  275. Vector2.prototype.divideToRef = function (otherVector, result) {
  276. result.x = this.x / otherVector.x;
  277. result.y = this.y / otherVector.y;
  278. };
  279. Vector2.prototype.negate = function () {
  280. return new Vector2(-this.x, -this.y);
  281. };
  282. Vector2.prototype.scaleInPlace = function (scale) {
  283. this.x *= scale;
  284. this.y *= scale;
  285. return this;
  286. };
  287. Vector2.prototype.scale = function (scale) {
  288. return new Vector2(this.x * scale, this.y * scale);
  289. };
  290. Vector2.prototype.equals = function (otherVector) {
  291. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  292. };
  293. // Properties
  294. Vector2.prototype.length = function () {
  295. return Math.sqrt(this.x * this.x + this.y * this.y);
  296. };
  297. Vector2.prototype.lengthSquared = function () {
  298. return (this.x * this.x + this.y * this.y);
  299. };
  300. // Methods
  301. Vector2.prototype.normalize = function () {
  302. var len = this.length();
  303. if (len === 0)
  304. return this;
  305. var num = 1.0 / len;
  306. this.x *= num;
  307. this.y *= num;
  308. return this;
  309. };
  310. Vector2.prototype.clone = function () {
  311. return new Vector2(this.x, this.y);
  312. };
  313. // Statics
  314. Vector2.Zero = function () {
  315. return new Vector2(0, 0);
  316. };
  317. Vector2.FromArray = function (array, offset) {
  318. if (offset === void 0) { offset = 0; }
  319. return new Vector2(array[offset], array[offset + 1]);
  320. };
  321. Vector2.FromArrayToRef = function (array, offset, result) {
  322. result.x = array[offset];
  323. result.y = array[offset + 1];
  324. };
  325. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  326. var squared = amount * amount;
  327. var cubed = amount * squared;
  328. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  329. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  330. return new Vector2(x, y);
  331. };
  332. Vector2.Clamp = function (value, min, max) {
  333. var x = value.x;
  334. x = (x > max.x) ? max.x : x;
  335. x = (x < min.x) ? min.x : x;
  336. var y = value.y;
  337. y = (y > max.y) ? max.y : y;
  338. y = (y < min.y) ? min.y : y;
  339. return new Vector2(x, y);
  340. };
  341. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  342. var squared = amount * amount;
  343. var cubed = amount * squared;
  344. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  345. var part2 = (-2.0 * cubed) + (3.0 * squared);
  346. var part3 = (cubed - (2.0 * squared)) + amount;
  347. var part4 = cubed - squared;
  348. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  349. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  350. return new Vector2(x, y);
  351. };
  352. Vector2.Lerp = function (start, end, amount) {
  353. var x = start.x + ((end.x - start.x) * amount);
  354. var y = start.y + ((end.y - start.y) * amount);
  355. return new Vector2(x, y);
  356. };
  357. Vector2.Dot = function (left, right) {
  358. return left.x * right.x + left.y * right.y;
  359. };
  360. Vector2.Normalize = function (vector) {
  361. var newVector = vector.clone();
  362. newVector.normalize();
  363. return newVector;
  364. };
  365. Vector2.Minimize = function (left, right) {
  366. var x = (left.x < right.x) ? left.x : right.x;
  367. var y = (left.y < right.y) ? left.y : right.y;
  368. return new Vector2(x, y);
  369. };
  370. Vector2.Maximize = function (left, right) {
  371. var x = (left.x > right.x) ? left.x : right.x;
  372. var y = (left.y > right.y) ? left.y : right.y;
  373. return new Vector2(x, y);
  374. };
  375. Vector2.Transform = function (vector, transformation) {
  376. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  377. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  378. return new Vector2(x, y);
  379. };
  380. Vector2.Distance = function (value1, value2) {
  381. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  382. };
  383. Vector2.DistanceSquared = function (value1, value2) {
  384. var x = value1.x - value2.x;
  385. var y = value1.y - value2.y;
  386. return (x * x) + (y * y);
  387. };
  388. return Vector2;
  389. })();
  390. BABYLON.Vector2 = Vector2;
  391. var Vector3 = (function () {
  392. function Vector3(x, y, z) {
  393. this.x = x;
  394. this.y = y;
  395. this.z = z;
  396. }
  397. Vector3.prototype.toString = function () {
  398. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  399. };
  400. // Operators
  401. Vector3.prototype.asArray = function () {
  402. var result = [];
  403. this.toArray(result, 0);
  404. return result;
  405. };
  406. Vector3.prototype.toArray = function (array, index) {
  407. if (index === undefined) {
  408. index = 0;
  409. }
  410. array[index] = this.x;
  411. array[index + 1] = this.y;
  412. array[index + 2] = this.z;
  413. };
  414. Vector3.prototype.addInPlace = function (otherVector) {
  415. this.x += otherVector.x;
  416. this.y += otherVector.y;
  417. this.z += otherVector.z;
  418. };
  419. Vector3.prototype.add = function (otherVector) {
  420. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  421. };
  422. Vector3.prototype.addToRef = function (otherVector, result) {
  423. result.x = this.x + otherVector.x;
  424. result.y = this.y + otherVector.y;
  425. result.z = this.z + otherVector.z;
  426. };
  427. Vector3.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. this.z -= otherVector.z;
  431. };
  432. Vector3.prototype.subtract = function (otherVector) {
  433. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  434. };
  435. Vector3.prototype.subtractToRef = function (otherVector, result) {
  436. result.x = this.x - otherVector.x;
  437. result.y = this.y - otherVector.y;
  438. result.z = this.z - otherVector.z;
  439. };
  440. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  441. return new Vector3(this.x - x, this.y - y, this.z - z);
  442. };
  443. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  444. result.x = this.x - x;
  445. result.y = this.y - y;
  446. result.z = this.z - z;
  447. };
  448. Vector3.prototype.negate = function () {
  449. return new Vector3(-this.x, -this.y, -this.z);
  450. };
  451. Vector3.prototype.scaleInPlace = function (scale) {
  452. this.x *= scale;
  453. this.y *= scale;
  454. this.z *= scale;
  455. return this;
  456. };
  457. Vector3.prototype.scale = function (scale) {
  458. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  459. };
  460. Vector3.prototype.scaleToRef = function (scale, result) {
  461. result.x = this.x * scale;
  462. result.y = this.y * scale;
  463. result.z = this.z * scale;
  464. };
  465. Vector3.prototype.equals = function (otherVector) {
  466. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  467. };
  468. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  469. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  470. };
  471. Vector3.prototype.equalsToFloats = function (x, y, z) {
  472. return this.x === x && this.y === y && this.z === z;
  473. };
  474. Vector3.prototype.multiplyInPlace = function (otherVector) {
  475. this.x *= otherVector.x;
  476. this.y *= otherVector.y;
  477. this.z *= otherVector.z;
  478. };
  479. Vector3.prototype.multiply = function (otherVector) {
  480. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  481. };
  482. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  483. result.x = this.x * otherVector.x;
  484. result.y = this.y * otherVector.y;
  485. result.z = this.z * otherVector.z;
  486. };
  487. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  488. return new Vector3(this.x * x, this.y * y, this.z * z);
  489. };
  490. Vector3.prototype.divide = function (otherVector) {
  491. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  492. };
  493. Vector3.prototype.divideToRef = function (otherVector, result) {
  494. result.x = this.x / otherVector.x;
  495. result.y = this.y / otherVector.y;
  496. result.z = this.z / otherVector.z;
  497. };
  498. Vector3.prototype.MinimizeInPlace = function (other) {
  499. if (other.x < this.x)
  500. this.x = other.x;
  501. if (other.y < this.y)
  502. this.y = other.y;
  503. if (other.z < this.z)
  504. this.z = other.z;
  505. };
  506. Vector3.prototype.MaximizeInPlace = function (other) {
  507. if (other.x > this.x)
  508. this.x = other.x;
  509. if (other.y > this.y)
  510. this.y = other.y;
  511. if (other.z > this.z)
  512. this.z = other.z;
  513. };
  514. // Properties
  515. Vector3.prototype.length = function () {
  516. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  517. };
  518. Vector3.prototype.lengthSquared = function () {
  519. return (this.x * this.x + this.y * this.y + this.z * this.z);
  520. };
  521. // Methods
  522. Vector3.prototype.normalize = function () {
  523. var len = this.length();
  524. if (len === 0)
  525. return this;
  526. var num = 1.0 / len;
  527. this.x *= num;
  528. this.y *= num;
  529. this.z *= num;
  530. return this;
  531. };
  532. Vector3.prototype.clone = function () {
  533. return new Vector3(this.x, this.y, this.z);
  534. };
  535. Vector3.prototype.copyFrom = function (source) {
  536. this.x = source.x;
  537. this.y = source.y;
  538. this.z = source.z;
  539. };
  540. Vector3.prototype.copyFromFloats = function (x, y, z) {
  541. this.x = x;
  542. this.y = y;
  543. this.z = z;
  544. };
  545. // Statics
  546. Vector3.FromArray = function (array, offset) {
  547. if (!offset) {
  548. offset = 0;
  549. }
  550. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  551. };
  552. Vector3.FromArrayToRef = function (array, offset, result) {
  553. result.x = array[offset];
  554. result.y = array[offset + 1];
  555. result.z = array[offset + 2];
  556. };
  557. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  558. result.x = array[offset];
  559. result.y = array[offset + 1];
  560. result.z = array[offset + 2];
  561. };
  562. Vector3.FromFloatsToRef = function (x, y, z, result) {
  563. result.x = x;
  564. result.y = y;
  565. result.z = z;
  566. };
  567. Vector3.Zero = function () {
  568. return new Vector3(0, 0, 0);
  569. };
  570. Vector3.Up = function () {
  571. return new Vector3(0, 1.0, 0);
  572. };
  573. Vector3.TransformCoordinates = function (vector, transformation) {
  574. var result = Vector3.Zero();
  575. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  576. return result;
  577. };
  578. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  579. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  580. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  581. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  582. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  583. result.x = x / w;
  584. result.y = y / w;
  585. result.z = z / w;
  586. };
  587. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  588. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  589. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  590. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  591. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  592. result.x = rx / rw;
  593. result.y = ry / rw;
  594. result.z = rz / rw;
  595. };
  596. Vector3.TransformNormal = function (vector, transformation) {
  597. var result = Vector3.Zero();
  598. Vector3.TransformNormalToRef(vector, transformation, result);
  599. return result;
  600. };
  601. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  602. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  603. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  604. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  605. };
  606. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  607. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  608. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  609. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  610. };
  611. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  612. var squared = amount * amount;
  613. var cubed = amount * squared;
  614. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  615. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  616. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  617. return new Vector3(x, y, z);
  618. };
  619. Vector3.Clamp = function (value, min, max) {
  620. var x = value.x;
  621. x = (x > max.x) ? max.x : x;
  622. x = (x < min.x) ? min.x : x;
  623. var y = value.y;
  624. y = (y > max.y) ? max.y : y;
  625. y = (y < min.y) ? min.y : y;
  626. var z = value.z;
  627. z = (z > max.z) ? max.z : z;
  628. z = (z < min.z) ? min.z : z;
  629. return new Vector3(x, y, z);
  630. };
  631. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  632. var squared = amount * amount;
  633. var cubed = amount * squared;
  634. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  635. var part2 = (-2.0 * cubed) + (3.0 * squared);
  636. var part3 = (cubed - (2.0 * squared)) + amount;
  637. var part4 = cubed - squared;
  638. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  639. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  640. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  641. return new Vector3(x, y, z);
  642. };
  643. Vector3.Lerp = function (start, end, amount) {
  644. var x = start.x + ((end.x - start.x) * amount);
  645. var y = start.y + ((end.y - start.y) * amount);
  646. var z = start.z + ((end.z - start.z) * amount);
  647. return new Vector3(x, y, z);
  648. };
  649. Vector3.Dot = function (left, right) {
  650. return (left.x * right.x + left.y * right.y + left.z * right.z);
  651. };
  652. Vector3.Cross = function (left, right) {
  653. var result = Vector3.Zero();
  654. Vector3.CrossToRef(left, right, result);
  655. return result;
  656. };
  657. Vector3.CrossToRef = function (left, right, result) {
  658. result.x = left.y * right.z - left.z * right.y;
  659. result.y = left.z * right.x - left.x * right.z;
  660. result.z = left.x * right.y - left.y * right.x;
  661. };
  662. Vector3.Normalize = function (vector) {
  663. var result = Vector3.Zero();
  664. Vector3.NormalizeToRef(vector, result);
  665. return result;
  666. };
  667. Vector3.NormalizeToRef = function (vector, result) {
  668. result.copyFrom(vector);
  669. result.normalize();
  670. };
  671. Vector3.Project = function (vector, world, transform, viewport) {
  672. var cw = viewport.width;
  673. var ch = viewport.height;
  674. var cx = viewport.x;
  675. var cy = viewport.y;
  676. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  677. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  678. return Vector3.TransformCoordinates(vector, finalMatrix);
  679. };
  680. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  681. var matrix = world.multiply(transform);
  682. matrix.invert();
  683. source.x = source.x / viewportWidth * 2 - 1;
  684. source.y = -(source.y / viewportHeight * 2 - 1);
  685. var vector = Vector3.TransformCoordinates(source, matrix);
  686. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  687. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  688. vector = vector.scale(1.0 / num);
  689. }
  690. return vector;
  691. };
  692. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  693. var matrix = world.multiply(view).multiply(projection);
  694. matrix.invert();
  695. source.x = source.x / viewportWidth * 2 - 1;
  696. source.y = -(source.y / viewportHeight * 2 - 1);
  697. var vector = Vector3.TransformCoordinates(source, matrix);
  698. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  699. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  700. vector = vector.scale(1.0 / num);
  701. }
  702. return vector;
  703. };
  704. Vector3.Minimize = function (left, right) {
  705. var min = left.clone();
  706. min.MinimizeInPlace(right);
  707. return min;
  708. };
  709. Vector3.Maximize = function (left, right) {
  710. var max = left.clone();
  711. max.MaximizeInPlace(right);
  712. return max;
  713. };
  714. Vector3.Distance = function (value1, value2) {
  715. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  716. };
  717. Vector3.DistanceSquared = function (value1, value2) {
  718. var x = value1.x - value2.x;
  719. var y = value1.y - value2.y;
  720. var z = value1.z - value2.z;
  721. return (x * x) + (y * y) + (z * z);
  722. };
  723. Vector3.Center = function (value1, value2) {
  724. var center = value1.add(value2);
  725. center.scaleInPlace(0.5);
  726. return center;
  727. };
  728. return Vector3;
  729. })();
  730. BABYLON.Vector3 = Vector3;
  731. //Vector4 class created for EulerAngle class conversion to Quaternion
  732. var Vector4 = (function () {
  733. function Vector4(x, y, z, w) {
  734. this.x = x;
  735. this.y = y;
  736. this.z = z;
  737. this.w = w;
  738. }
  739. Vector4.prototype.toString = function () {
  740. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  741. };
  742. // Operators
  743. Vector4.prototype.asArray = function () {
  744. var result = [];
  745. this.toArray(result, 0);
  746. return result;
  747. };
  748. Vector4.prototype.toArray = function (array, index) {
  749. if (index === undefined) {
  750. index = 0;
  751. }
  752. array[index] = this.x;
  753. array[index + 1] = this.y;
  754. array[index + 2] = this.z;
  755. array[index + 3] = this.w;
  756. };
  757. Vector4.prototype.addInPlace = function (otherVector) {
  758. this.x += otherVector.x;
  759. this.y += otherVector.y;
  760. this.z += otherVector.z;
  761. this.w += otherVector.w;
  762. };
  763. Vector4.prototype.add = function (otherVector) {
  764. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  765. };
  766. Vector4.prototype.addToRef = function (otherVector, result) {
  767. result.x = this.x + otherVector.x;
  768. result.y = this.y + otherVector.y;
  769. result.z = this.z + otherVector.z;
  770. result.w = this.w + otherVector.w;
  771. };
  772. Vector4.prototype.subtractInPlace = function (otherVector) {
  773. this.x -= otherVector.x;
  774. this.y -= otherVector.y;
  775. this.z -= otherVector.z;
  776. this.w -= otherVector.w;
  777. };
  778. Vector4.prototype.subtract = function (otherVector) {
  779. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  780. };
  781. Vector4.prototype.subtractToRef = function (otherVector, result) {
  782. result.x = this.x - otherVector.x;
  783. result.y = this.y - otherVector.y;
  784. result.z = this.z - otherVector.z;
  785. result.w = this.w - otherVector.w;
  786. };
  787. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  788. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  789. };
  790. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  791. result.x = this.x - x;
  792. result.y = this.y - y;
  793. result.z = this.z - z;
  794. result.w = this.w - w;
  795. };
  796. Vector4.prototype.negate = function () {
  797. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  798. };
  799. Vector4.prototype.scaleInPlace = function (scale) {
  800. this.x *= scale;
  801. this.y *= scale;
  802. this.z *= scale;
  803. this.w *= scale;
  804. return this;
  805. };
  806. Vector4.prototype.scale = function (scale) {
  807. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  808. };
  809. Vector4.prototype.scaleToRef = function (scale, result) {
  810. result.x = this.x * scale;
  811. result.y = this.y * scale;
  812. result.z = this.z * scale;
  813. result.w = this.w * scale;
  814. };
  815. Vector4.prototype.equals = function (otherVector) {
  816. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  817. };
  818. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  819. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  820. };
  821. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  822. return this.x === x && this.y === y && this.z === z && this.w === w;
  823. };
  824. Vector4.prototype.multiplyInPlace = function (otherVector) {
  825. this.x *= otherVector.x;
  826. this.y *= otherVector.y;
  827. this.z *= otherVector.z;
  828. this.w *= otherVector.w;
  829. };
  830. Vector4.prototype.multiply = function (otherVector) {
  831. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  832. };
  833. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  834. result.x = this.x * otherVector.x;
  835. result.y = this.y * otherVector.y;
  836. result.z = this.z * otherVector.z;
  837. result.w = this.w * otherVector.w;
  838. };
  839. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  840. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  841. };
  842. Vector4.prototype.divide = function (otherVector) {
  843. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  844. };
  845. Vector4.prototype.divideToRef = function (otherVector, result) {
  846. result.x = this.x / otherVector.x;
  847. result.y = this.y / otherVector.y;
  848. result.z = this.z / otherVector.z;
  849. result.w = this.w / otherVector.w;
  850. };
  851. Vector4.prototype.MinimizeInPlace = function (other) {
  852. if (other.x < this.x)
  853. this.x = other.x;
  854. if (other.y < this.y)
  855. this.y = other.y;
  856. if (other.z < this.z)
  857. this.z = other.z;
  858. if (other.w < this.w)
  859. this.w = other.w;
  860. };
  861. Vector4.prototype.MaximizeInPlace = function (other) {
  862. if (other.x > this.x)
  863. this.x = other.x;
  864. if (other.y > this.y)
  865. this.y = other.y;
  866. if (other.z > this.z)
  867. this.z = other.z;
  868. if (other.w > this.w)
  869. this.w = other.w;
  870. };
  871. // Properties
  872. Vector4.prototype.length = function () {
  873. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  874. };
  875. Vector4.prototype.lengthSquared = function () {
  876. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  877. };
  878. // Methods
  879. Vector4.prototype.normalize = function () {
  880. var len = this.length();
  881. if (len === 0)
  882. return this;
  883. var num = 1.0 / len;
  884. this.x *= num;
  885. this.y *= num;
  886. this.z *= num;
  887. this.w *= num;
  888. return this;
  889. };
  890. Vector4.prototype.clone = function () {
  891. return new Vector4(this.x, this.y, this.z, this.w);
  892. };
  893. Vector4.prototype.copyFrom = function (source) {
  894. this.x = source.x;
  895. this.y = source.y;
  896. this.z = source.z;
  897. this.w = source.w;
  898. };
  899. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  900. this.x = x;
  901. this.y = y;
  902. this.z = z;
  903. this.w = w;
  904. };
  905. // Statics
  906. Vector4.FromArray = function (array, offset) {
  907. if (!offset) {
  908. offset = 0;
  909. }
  910. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  911. };
  912. Vector4.FromArrayToRef = function (array, offset, result) {
  913. result.x = array[offset];
  914. result.y = array[offset + 1];
  915. result.z = array[offset + 2];
  916. result.w = array[offset + 3];
  917. };
  918. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  919. result.x = array[offset];
  920. result.y = array[offset + 1];
  921. result.z = array[offset + 2];
  922. result.w = array[offset + 3];
  923. };
  924. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  925. result.x = x;
  926. result.y = y;
  927. result.z = z;
  928. result.w = w;
  929. };
  930. Vector4.Zero = function () {
  931. return new Vector4(0, 0, 0, 0);
  932. };
  933. Vector4.Normalize = function (vector) {
  934. var result = Vector4.Zero();
  935. Vector4.NormalizeToRef(vector, result);
  936. return result;
  937. };
  938. Vector4.NormalizeToRef = function (vector, result) {
  939. result.copyFrom(vector);
  940. result.normalize();
  941. };
  942. Vector4.Minimize = function (left, right) {
  943. var min = left.clone();
  944. min.MinimizeInPlace(right);
  945. return min;
  946. };
  947. Vector4.Maximize = function (left, right) {
  948. var max = left.clone();
  949. max.MaximizeInPlace(right);
  950. return max;
  951. };
  952. Vector4.Distance = function (value1, value2) {
  953. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  954. };
  955. Vector4.DistanceSquared = function (value1, value2) {
  956. var x = value1.x - value2.x;
  957. var y = value1.y - value2.y;
  958. var z = value1.z - value2.z;
  959. var w = value1.w - value2.w;
  960. return (x * x) + (y * y) + (z * z) + (w * w);
  961. };
  962. Vector4.Center = function (value1, value2) {
  963. var center = value1.add(value2);
  964. center.scaleInPlace(0.5);
  965. return center;
  966. };
  967. return Vector4;
  968. })();
  969. BABYLON.Vector4 = Vector4;
  970. var Quaternion = (function () {
  971. function Quaternion(x, y, z, w) {
  972. if (x === void 0) { x = 0; }
  973. if (y === void 0) { y = 0; }
  974. if (z === void 0) { z = 0; }
  975. if (w === void 0) { w = 1; }
  976. this.x = x;
  977. this.y = y;
  978. this.z = z;
  979. this.w = w;
  980. }
  981. Quaternion.prototype.toString = function () {
  982. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  983. };
  984. Quaternion.prototype.asArray = function () {
  985. return [this.x, this.y, this.z, this.w];
  986. };
  987. Quaternion.prototype.equals = function (otherQuaternion) {
  988. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  989. };
  990. Quaternion.prototype.clone = function () {
  991. return new Quaternion(this.x, this.y, this.z, this.w);
  992. };
  993. Quaternion.prototype.copyFrom = function (other) {
  994. this.x = other.x;
  995. this.y = other.y;
  996. this.z = other.z;
  997. this.w = other.w;
  998. };
  999. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1000. this.x = x;
  1001. this.y = y;
  1002. this.z = z;
  1003. this.w = w;
  1004. };
  1005. Quaternion.prototype.add = function (other) {
  1006. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1007. };
  1008. Quaternion.prototype.subtract = function (other) {
  1009. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1010. };
  1011. Quaternion.prototype.scale = function (value) {
  1012. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1013. };
  1014. Quaternion.prototype.multiply = function (q1) {
  1015. var result = new Quaternion(0, 0, 0, 1.0);
  1016. this.multiplyToRef(q1, result);
  1017. return result;
  1018. };
  1019. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1020. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1021. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1022. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1023. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1024. };
  1025. Quaternion.prototype.length = function () {
  1026. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1027. };
  1028. Quaternion.prototype.normalize = function () {
  1029. var length = 1.0 / this.length();
  1030. this.x *= length;
  1031. this.y *= length;
  1032. this.z *= length;
  1033. this.w *= length;
  1034. };
  1035. Quaternion.prototype.toEulerAngles = function () {
  1036. var result = Vector3.Zero();
  1037. this.toEulerAnglesToRef(result);
  1038. return result;
  1039. };
  1040. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1041. //result is an EulerAngles in the in the z-x-z convention
  1042. var qx = this.x;
  1043. var qy = this.y;
  1044. var qz = this.z;
  1045. var qw = this.w;
  1046. var qxy = qx * qy;
  1047. var qxz = qx * qz;
  1048. var qwy = qw * qy;
  1049. var qwz = qw * qz;
  1050. var qwx = qw * qx;
  1051. var qyz = qy * qz;
  1052. var sqx = qx * qx;
  1053. var sqy = qy * qy;
  1054. var determinant = sqx + sqy;
  1055. if (determinant !== 0.000 && determinant !== 1.000) {
  1056. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1057. result.y = Math.acos(1 - 2 * determinant);
  1058. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1059. }
  1060. else {
  1061. if (determinant === 0.0) {
  1062. result.x = 0.0;
  1063. result.y = 0.0;
  1064. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1065. }
  1066. else {
  1067. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1068. result.y = Math.PI;
  1069. result.z = 0.0;
  1070. }
  1071. }
  1072. };
  1073. Quaternion.prototype.toRotationMatrix = function (result) {
  1074. var xx = this.x * this.x;
  1075. var yy = this.y * this.y;
  1076. var zz = this.z * this.z;
  1077. var xy = this.x * this.y;
  1078. var zw = this.z * this.w;
  1079. var zx = this.z * this.x;
  1080. var yw = this.y * this.w;
  1081. var yz = this.y * this.z;
  1082. var xw = this.x * this.w;
  1083. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1084. result.m[1] = 2.0 * (xy + zw);
  1085. result.m[2] = 2.0 * (zx - yw);
  1086. result.m[3] = 0;
  1087. result.m[4] = 2.0 * (xy - zw);
  1088. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1089. result.m[6] = 2.0 * (yz + xw);
  1090. result.m[7] = 0;
  1091. result.m[8] = 2.0 * (zx + yw);
  1092. result.m[9] = 2.0 * (yz - xw);
  1093. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1094. result.m[11] = 0;
  1095. result.m[12] = 0;
  1096. result.m[13] = 0;
  1097. result.m[14] = 0;
  1098. result.m[15] = 1.0;
  1099. };
  1100. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1101. var data = matrix.m;
  1102. var m11 = data[0], m12 = data[4], m13 = data[8];
  1103. var m21 = data[1], m22 = data[5], m23 = data[9];
  1104. var m31 = data[2], m32 = data[6], m33 = data[10];
  1105. var trace = m11 + m22 + m33;
  1106. var s;
  1107. if (trace > 0) {
  1108. s = 0.5 / Math.sqrt(trace + 1.0);
  1109. this.w = 0.25 / s;
  1110. this.x = (m32 - m23) * s;
  1111. this.y = (m13 - m31) * s;
  1112. this.z = (m21 - m12) * s;
  1113. return;
  1114. }
  1115. if (m11 > m22 && m11 > m33) {
  1116. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1117. this.w = (m32 - m23) / s;
  1118. this.x = 0.25 * s;
  1119. this.y = (m12 + m21) / s;
  1120. this.z = (m13 + m31) / s;
  1121. return;
  1122. }
  1123. if (m22 > m33) {
  1124. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1125. this.w = (m13 - m31) / s;
  1126. this.x = (m12 + m21) / s;
  1127. this.y = 0.25 * s;
  1128. this.z = (m23 + m32) / s;
  1129. return;
  1130. }
  1131. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1132. this.w = (m21 - m12) / s;
  1133. this.x = (m13 + m31) / s;
  1134. this.y = (m23 + m32) / s;
  1135. this.z = 0.25 * s;
  1136. };
  1137. // Statics
  1138. Quaternion.Inverse = function (q) {
  1139. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1140. };
  1141. Quaternion.Identity = function () {
  1142. return new Quaternion(0, 0, 0, 1);
  1143. };
  1144. Quaternion.RotationAxis = function (axis, angle) {
  1145. var result = new Quaternion();
  1146. var sin = Math.sin(angle / 2);
  1147. result.w = Math.cos(angle / 2);
  1148. result.x = axis.x * sin;
  1149. result.y = axis.y * sin;
  1150. result.z = axis.z * sin;
  1151. return result;
  1152. };
  1153. Quaternion.FromArray = function (array, offset) {
  1154. if (!offset) {
  1155. offset = 0;
  1156. }
  1157. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1158. };
  1159. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1160. var result = new Quaternion();
  1161. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1162. return result;
  1163. };
  1164. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1165. var halfRoll = roll * 0.5;
  1166. var halfPitch = pitch * 0.5;
  1167. var halfYaw = yaw * 0.5;
  1168. var sinRoll = Math.sin(halfRoll);
  1169. var cosRoll = Math.cos(halfRoll);
  1170. var sinPitch = Math.sin(halfPitch);
  1171. var cosPitch = Math.cos(halfPitch);
  1172. var sinYaw = Math.sin(halfYaw);
  1173. var cosYaw = Math.cos(halfYaw);
  1174. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1175. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1176. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1177. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1178. };
  1179. Quaternion.Slerp = function (left, right, amount) {
  1180. var num2;
  1181. var num3;
  1182. var num = amount;
  1183. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1184. var flag = false;
  1185. if (num4 < 0) {
  1186. flag = true;
  1187. num4 = -num4;
  1188. }
  1189. if (num4 > 0.999999) {
  1190. num3 = 1 - num;
  1191. num2 = flag ? -num : num;
  1192. }
  1193. else {
  1194. var num5 = Math.acos(num4);
  1195. var num6 = (1.0 / Math.sin(num5));
  1196. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1197. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1198. }
  1199. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1200. };
  1201. return Quaternion;
  1202. })();
  1203. BABYLON.Quaternion = Quaternion;
  1204. var Matrix = (function () {
  1205. function Matrix() {
  1206. this.m = new Float32Array(16);
  1207. }
  1208. // Properties
  1209. Matrix.prototype.isIdentity = function () {
  1210. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1211. return false;
  1212. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1213. return false;
  1214. return true;
  1215. };
  1216. Matrix.prototype.determinant = function () {
  1217. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1218. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1219. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1220. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1221. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1222. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1223. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1224. };
  1225. // Methods
  1226. Matrix.prototype.toArray = function () {
  1227. return this.m;
  1228. };
  1229. Matrix.prototype.asArray = function () {
  1230. return this.toArray();
  1231. };
  1232. Matrix.prototype.invert = function () {
  1233. this.invertToRef(this);
  1234. };
  1235. Matrix.prototype.invertToRef = function (other) {
  1236. var l1 = this.m[0];
  1237. var l2 = this.m[1];
  1238. var l3 = this.m[2];
  1239. var l4 = this.m[3];
  1240. var l5 = this.m[4];
  1241. var l6 = this.m[5];
  1242. var l7 = this.m[6];
  1243. var l8 = this.m[7];
  1244. var l9 = this.m[8];
  1245. var l10 = this.m[9];
  1246. var l11 = this.m[10];
  1247. var l12 = this.m[11];
  1248. var l13 = this.m[12];
  1249. var l14 = this.m[13];
  1250. var l15 = this.m[14];
  1251. var l16 = this.m[15];
  1252. var l17 = (l11 * l16) - (l12 * l15);
  1253. var l18 = (l10 * l16) - (l12 * l14);
  1254. var l19 = (l10 * l15) - (l11 * l14);
  1255. var l20 = (l9 * l16) - (l12 * l13);
  1256. var l21 = (l9 * l15) - (l11 * l13);
  1257. var l22 = (l9 * l14) - (l10 * l13);
  1258. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1259. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1260. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1261. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1262. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1263. var l28 = (l7 * l16) - (l8 * l15);
  1264. var l29 = (l6 * l16) - (l8 * l14);
  1265. var l30 = (l6 * l15) - (l7 * l14);
  1266. var l31 = (l5 * l16) - (l8 * l13);
  1267. var l32 = (l5 * l15) - (l7 * l13);
  1268. var l33 = (l5 * l14) - (l6 * l13);
  1269. var l34 = (l7 * l12) - (l8 * l11);
  1270. var l35 = (l6 * l12) - (l8 * l10);
  1271. var l36 = (l6 * l11) - (l7 * l10);
  1272. var l37 = (l5 * l12) - (l8 * l9);
  1273. var l38 = (l5 * l11) - (l7 * l9);
  1274. var l39 = (l5 * l10) - (l6 * l9);
  1275. other.m[0] = l23 * l27;
  1276. other.m[4] = l24 * l27;
  1277. other.m[8] = l25 * l27;
  1278. other.m[12] = l26 * l27;
  1279. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1280. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1281. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1282. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1283. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1284. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1285. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1286. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1287. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1288. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1289. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1290. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1291. };
  1292. Matrix.prototype.setTranslation = function (vector3) {
  1293. this.m[12] = vector3.x;
  1294. this.m[13] = vector3.y;
  1295. this.m[14] = vector3.z;
  1296. };
  1297. Matrix.prototype.multiply = function (other) {
  1298. var result = new Matrix();
  1299. this.multiplyToRef(other, result);
  1300. return result;
  1301. };
  1302. Matrix.prototype.copyFrom = function (other) {
  1303. for (var index = 0; index < 16; index++) {
  1304. this.m[index] = other.m[index];
  1305. }
  1306. };
  1307. Matrix.prototype.copyToArray = function (array, offset) {
  1308. if (offset === void 0) { offset = 0; }
  1309. for (var index = 0; index < 16; index++) {
  1310. array[offset + index] = this.m[index];
  1311. }
  1312. };
  1313. Matrix.prototype.multiplyToRef = function (other, result) {
  1314. this.multiplyToArray(other, result.m, 0);
  1315. };
  1316. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1317. var tm0 = this.m[0];
  1318. var tm1 = this.m[1];
  1319. var tm2 = this.m[2];
  1320. var tm3 = this.m[3];
  1321. var tm4 = this.m[4];
  1322. var tm5 = this.m[5];
  1323. var tm6 = this.m[6];
  1324. var tm7 = this.m[7];
  1325. var tm8 = this.m[8];
  1326. var tm9 = this.m[9];
  1327. var tm10 = this.m[10];
  1328. var tm11 = this.m[11];
  1329. var tm12 = this.m[12];
  1330. var tm13 = this.m[13];
  1331. var tm14 = this.m[14];
  1332. var tm15 = this.m[15];
  1333. var om0 = other.m[0];
  1334. var om1 = other.m[1];
  1335. var om2 = other.m[2];
  1336. var om3 = other.m[3];
  1337. var om4 = other.m[4];
  1338. var om5 = other.m[5];
  1339. var om6 = other.m[6];
  1340. var om7 = other.m[7];
  1341. var om8 = other.m[8];
  1342. var om9 = other.m[9];
  1343. var om10 = other.m[10];
  1344. var om11 = other.m[11];
  1345. var om12 = other.m[12];
  1346. var om13 = other.m[13];
  1347. var om14 = other.m[14];
  1348. var om15 = other.m[15];
  1349. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1350. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1351. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1352. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1353. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1354. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1355. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1356. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1357. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1358. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1359. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1360. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1361. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1362. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1363. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1364. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1365. };
  1366. Matrix.prototype.equals = function (value) {
  1367. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1368. };
  1369. Matrix.prototype.clone = function () {
  1370. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1371. };
  1372. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1373. translation.x = this.m[12];
  1374. translation.y = this.m[13];
  1375. translation.z = this.m[14];
  1376. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1377. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1378. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1379. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1380. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1381. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1382. if (scale.x == 0 || scale.y == 0 || scale.z == 0) {
  1383. rotation.x = 0;
  1384. rotation.y = 0;
  1385. rotation.z = 0;
  1386. rotation.w = 1;
  1387. return false;
  1388. }
  1389. var rotationMatrix = BABYLON.Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1390. rotation.fromRotationMatrix(rotationMatrix);
  1391. return true;
  1392. };
  1393. // Statics
  1394. Matrix.FromArray = function (array, offset) {
  1395. var result = new Matrix();
  1396. if (!offset) {
  1397. offset = 0;
  1398. }
  1399. Matrix.FromArrayToRef(array, offset, result);
  1400. return result;
  1401. };
  1402. Matrix.FromArrayToRef = function (array, offset, result) {
  1403. for (var index = 0; index < 16; index++) {
  1404. result.m[index] = array[index + offset];
  1405. }
  1406. };
  1407. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1408. result.m[0] = initialM11;
  1409. result.m[1] = initialM12;
  1410. result.m[2] = initialM13;
  1411. result.m[3] = initialM14;
  1412. result.m[4] = initialM21;
  1413. result.m[5] = initialM22;
  1414. result.m[6] = initialM23;
  1415. result.m[7] = initialM24;
  1416. result.m[8] = initialM31;
  1417. result.m[9] = initialM32;
  1418. result.m[10] = initialM33;
  1419. result.m[11] = initialM34;
  1420. result.m[12] = initialM41;
  1421. result.m[13] = initialM42;
  1422. result.m[14] = initialM43;
  1423. result.m[15] = initialM44;
  1424. };
  1425. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1426. var result = new Matrix();
  1427. result.m[0] = initialM11;
  1428. result.m[1] = initialM12;
  1429. result.m[2] = initialM13;
  1430. result.m[3] = initialM14;
  1431. result.m[4] = initialM21;
  1432. result.m[5] = initialM22;
  1433. result.m[6] = initialM23;
  1434. result.m[7] = initialM24;
  1435. result.m[8] = initialM31;
  1436. result.m[9] = initialM32;
  1437. result.m[10] = initialM33;
  1438. result.m[11] = initialM34;
  1439. result.m[12] = initialM41;
  1440. result.m[13] = initialM42;
  1441. result.m[14] = initialM43;
  1442. result.m[15] = initialM44;
  1443. return result;
  1444. };
  1445. Matrix.Compose = function (scale, rotation, translation) {
  1446. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1447. var rotationMatrix = Matrix.Identity();
  1448. rotation.toRotationMatrix(rotationMatrix);
  1449. result = result.multiply(rotationMatrix);
  1450. result.setTranslation(translation);
  1451. return result;
  1452. };
  1453. Matrix.Identity = function () {
  1454. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1455. };
  1456. Matrix.IdentityToRef = function (result) {
  1457. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1458. };
  1459. Matrix.Zero = function () {
  1460. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1461. };
  1462. Matrix.RotationX = function (angle) {
  1463. var result = new Matrix();
  1464. Matrix.RotationXToRef(angle, result);
  1465. return result;
  1466. };
  1467. Matrix.Invert = function (source) {
  1468. var result = new Matrix();
  1469. source.invertToRef(result);
  1470. return result;
  1471. };
  1472. Matrix.RotationXToRef = function (angle, result) {
  1473. var s = Math.sin(angle);
  1474. var c = Math.cos(angle);
  1475. result.m[0] = 1.0;
  1476. result.m[15] = 1.0;
  1477. result.m[5] = c;
  1478. result.m[10] = c;
  1479. result.m[9] = -s;
  1480. result.m[6] = s;
  1481. result.m[1] = 0;
  1482. result.m[2] = 0;
  1483. result.m[3] = 0;
  1484. result.m[4] = 0;
  1485. result.m[7] = 0;
  1486. result.m[8] = 0;
  1487. result.m[11] = 0;
  1488. result.m[12] = 0;
  1489. result.m[13] = 0;
  1490. result.m[14] = 0;
  1491. };
  1492. Matrix.RotationY = function (angle) {
  1493. var result = new Matrix();
  1494. Matrix.RotationYToRef(angle, result);
  1495. return result;
  1496. };
  1497. Matrix.RotationYToRef = function (angle, result) {
  1498. var s = Math.sin(angle);
  1499. var c = Math.cos(angle);
  1500. result.m[5] = 1.0;
  1501. result.m[15] = 1.0;
  1502. result.m[0] = c;
  1503. result.m[2] = -s;
  1504. result.m[8] = s;
  1505. result.m[10] = c;
  1506. result.m[1] = 0;
  1507. result.m[3] = 0;
  1508. result.m[4] = 0;
  1509. result.m[6] = 0;
  1510. result.m[7] = 0;
  1511. result.m[9] = 0;
  1512. result.m[11] = 0;
  1513. result.m[12] = 0;
  1514. result.m[13] = 0;
  1515. result.m[14] = 0;
  1516. };
  1517. Matrix.RotationZ = function (angle) {
  1518. var result = new Matrix();
  1519. Matrix.RotationZToRef(angle, result);
  1520. return result;
  1521. };
  1522. Matrix.RotationZToRef = function (angle, result) {
  1523. var s = Math.sin(angle);
  1524. var c = Math.cos(angle);
  1525. result.m[10] = 1.0;
  1526. result.m[15] = 1.0;
  1527. result.m[0] = c;
  1528. result.m[1] = s;
  1529. result.m[4] = -s;
  1530. result.m[5] = c;
  1531. result.m[2] = 0;
  1532. result.m[3] = 0;
  1533. result.m[6] = 0;
  1534. result.m[7] = 0;
  1535. result.m[8] = 0;
  1536. result.m[9] = 0;
  1537. result.m[11] = 0;
  1538. result.m[12] = 0;
  1539. result.m[13] = 0;
  1540. result.m[14] = 0;
  1541. };
  1542. Matrix.RotationAxis = function (axis, angle) {
  1543. var s = Math.sin(-angle);
  1544. var c = Math.cos(-angle);
  1545. var c1 = 1 - c;
  1546. axis.normalize();
  1547. var result = Matrix.Zero();
  1548. result.m[0] = (axis.x * axis.x) * c1 + c;
  1549. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1550. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1551. result.m[3] = 0.0;
  1552. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1553. result.m[5] = (axis.y * axis.y) * c1 + c;
  1554. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1555. result.m[7] = 0.0;
  1556. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1557. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1558. result.m[10] = (axis.z * axis.z) * c1 + c;
  1559. result.m[11] = 0.0;
  1560. result.m[15] = 1.0;
  1561. return result;
  1562. };
  1563. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1564. var result = new Matrix();
  1565. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1566. return result;
  1567. };
  1568. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1569. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1570. this._tempQuaternion.toRotationMatrix(result);
  1571. };
  1572. Matrix.Scaling = function (x, y, z) {
  1573. var result = Matrix.Zero();
  1574. Matrix.ScalingToRef(x, y, z, result);
  1575. return result;
  1576. };
  1577. Matrix.ScalingToRef = function (x, y, z, result) {
  1578. result.m[0] = x;
  1579. result.m[1] = 0;
  1580. result.m[2] = 0;
  1581. result.m[3] = 0;
  1582. result.m[4] = 0;
  1583. result.m[5] = y;
  1584. result.m[6] = 0;
  1585. result.m[7] = 0;
  1586. result.m[8] = 0;
  1587. result.m[9] = 0;
  1588. result.m[10] = z;
  1589. result.m[11] = 0;
  1590. result.m[12] = 0;
  1591. result.m[13] = 0;
  1592. result.m[14] = 0;
  1593. result.m[15] = 1.0;
  1594. };
  1595. Matrix.Translation = function (x, y, z) {
  1596. var result = Matrix.Identity();
  1597. Matrix.TranslationToRef(x, y, z, result);
  1598. return result;
  1599. };
  1600. Matrix.TranslationToRef = function (x, y, z, result) {
  1601. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1602. };
  1603. Matrix.LookAtLH = function (eye, target, up) {
  1604. var result = Matrix.Zero();
  1605. Matrix.LookAtLHToRef(eye, target, up, result);
  1606. return result;
  1607. };
  1608. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1609. // Z axis
  1610. target.subtractToRef(eye, this._zAxis);
  1611. this._zAxis.normalize();
  1612. // X axis
  1613. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1614. this._xAxis.normalize();
  1615. // Y axis
  1616. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1617. this._yAxis.normalize();
  1618. // Eye angles
  1619. var ex = -Vector3.Dot(this._xAxis, eye);
  1620. var ey = -Vector3.Dot(this._yAxis, eye);
  1621. var ez = -Vector3.Dot(this._zAxis, eye);
  1622. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1623. };
  1624. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1625. var hw = 2.0 / width;
  1626. var hh = 2.0 / height;
  1627. var id = 1.0 / (zfar - znear);
  1628. var nid = znear / (znear - zfar);
  1629. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1630. };
  1631. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1632. var matrix = Matrix.Zero();
  1633. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1634. return matrix;
  1635. };
  1636. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1637. result.m[0] = 2.0 / (right - left);
  1638. result.m[1] = result.m[2] = result.m[3] = 0;
  1639. result.m[5] = 2.0 / (top - bottom);
  1640. result.m[4] = result.m[6] = result.m[7] = 0;
  1641. result.m[10] = -1.0 / (znear - zfar);
  1642. result.m[8] = result.m[9] = result.m[11] = 0;
  1643. result.m[12] = (left + right) / (left - right);
  1644. result.m[13] = (top + bottom) / (bottom - top);
  1645. result.m[14] = znear / (znear - zfar);
  1646. result.m[15] = 1.0;
  1647. };
  1648. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1649. var matrix = Matrix.Zero();
  1650. matrix.m[0] = (2.0 * znear) / width;
  1651. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1652. matrix.m[5] = (2.0 * znear) / height;
  1653. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1654. matrix.m[10] = -zfar / (znear - zfar);
  1655. matrix.m[8] = matrix.m[9] = 0.0;
  1656. matrix.m[11] = 1.0;
  1657. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1658. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1659. return matrix;
  1660. };
  1661. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1662. var matrix = Matrix.Zero();
  1663. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1664. return matrix;
  1665. };
  1666. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1667. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1668. var tan = 1.0 / (Math.tan(fov * 0.5));
  1669. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1670. if (v_fixed) {
  1671. result.m[0] = tan / aspect;
  1672. }
  1673. else {
  1674. result.m[0] = tan;
  1675. }
  1676. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1677. if (v_fixed) {
  1678. result.m[5] = tan;
  1679. }
  1680. else {
  1681. result.m[5] = tan * aspect;
  1682. }
  1683. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1684. result.m[8] = result.m[9] = 0.0;
  1685. result.m[10] = -zfar / (znear - zfar);
  1686. result.m[11] = 1.0;
  1687. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1688. result.m[14] = (znear * zfar) / (znear - zfar);
  1689. };
  1690. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1691. var cw = viewport.width;
  1692. var ch = viewport.height;
  1693. var cx = viewport.x;
  1694. var cy = viewport.y;
  1695. 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);
  1696. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1697. };
  1698. Matrix.Transpose = function (matrix) {
  1699. var result = new Matrix();
  1700. result.m[0] = matrix.m[0];
  1701. result.m[1] = matrix.m[4];
  1702. result.m[2] = matrix.m[8];
  1703. result.m[3] = matrix.m[12];
  1704. result.m[4] = matrix.m[1];
  1705. result.m[5] = matrix.m[5];
  1706. result.m[6] = matrix.m[9];
  1707. result.m[7] = matrix.m[13];
  1708. result.m[8] = matrix.m[2];
  1709. result.m[9] = matrix.m[6];
  1710. result.m[10] = matrix.m[10];
  1711. result.m[11] = matrix.m[14];
  1712. result.m[12] = matrix.m[3];
  1713. result.m[13] = matrix.m[7];
  1714. result.m[14] = matrix.m[11];
  1715. result.m[15] = matrix.m[15];
  1716. return result;
  1717. };
  1718. Matrix.Reflection = function (plane) {
  1719. var matrix = new Matrix();
  1720. Matrix.ReflectionToRef(plane, matrix);
  1721. return matrix;
  1722. };
  1723. Matrix.ReflectionToRef = function (plane, result) {
  1724. plane.normalize();
  1725. var x = plane.normal.x;
  1726. var y = plane.normal.y;
  1727. var z = plane.normal.z;
  1728. var temp = -2 * x;
  1729. var temp2 = -2 * y;
  1730. var temp3 = -2 * z;
  1731. result.m[0] = (temp * x) + 1;
  1732. result.m[1] = temp2 * x;
  1733. result.m[2] = temp3 * x;
  1734. result.m[3] = 0.0;
  1735. result.m[4] = temp * y;
  1736. result.m[5] = (temp2 * y) + 1;
  1737. result.m[6] = temp3 * y;
  1738. result.m[7] = 0.0;
  1739. result.m[8] = temp * z;
  1740. result.m[9] = temp2 * z;
  1741. result.m[10] = (temp3 * z) + 1;
  1742. result.m[11] = 0.0;
  1743. result.m[12] = temp * plane.d;
  1744. result.m[13] = temp2 * plane.d;
  1745. result.m[14] = temp3 * plane.d;
  1746. result.m[15] = 1.0;
  1747. };
  1748. Matrix._tempQuaternion = new Quaternion();
  1749. Matrix._xAxis = Vector3.Zero();
  1750. Matrix._yAxis = Vector3.Zero();
  1751. Matrix._zAxis = Vector3.Zero();
  1752. return Matrix;
  1753. })();
  1754. BABYLON.Matrix = Matrix;
  1755. var Plane = (function () {
  1756. function Plane(a, b, c, d) {
  1757. this.normal = new Vector3(a, b, c);
  1758. this.d = d;
  1759. }
  1760. Plane.prototype.asArray = function () {
  1761. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1762. };
  1763. // Methods
  1764. Plane.prototype.clone = function () {
  1765. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1766. };
  1767. Plane.prototype.normalize = function () {
  1768. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1769. var magnitude = 0;
  1770. if (norm !== 0) {
  1771. magnitude = 1.0 / norm;
  1772. }
  1773. this.normal.x *= magnitude;
  1774. this.normal.y *= magnitude;
  1775. this.normal.z *= magnitude;
  1776. this.d *= magnitude;
  1777. };
  1778. Plane.prototype.transform = function (transformation) {
  1779. var transposedMatrix = Matrix.Transpose(transformation);
  1780. var x = this.normal.x;
  1781. var y = this.normal.y;
  1782. var z = this.normal.z;
  1783. var d = this.d;
  1784. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1785. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1786. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1787. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1788. return new Plane(normalX, normalY, normalZ, finalD);
  1789. };
  1790. Plane.prototype.dotCoordinate = function (point) {
  1791. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1792. };
  1793. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1794. var x1 = point2.x - point1.x;
  1795. var y1 = point2.y - point1.y;
  1796. var z1 = point2.z - point1.z;
  1797. var x2 = point3.x - point1.x;
  1798. var y2 = point3.y - point1.y;
  1799. var z2 = point3.z - point1.z;
  1800. var yz = (y1 * z2) - (z1 * y2);
  1801. var xz = (z1 * x2) - (x1 * z2);
  1802. var xy = (x1 * y2) - (y1 * x2);
  1803. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1804. var invPyth;
  1805. if (pyth !== 0) {
  1806. invPyth = 1.0 / pyth;
  1807. }
  1808. else {
  1809. invPyth = 0;
  1810. }
  1811. this.normal.x = yz * invPyth;
  1812. this.normal.y = xz * invPyth;
  1813. this.normal.z = xy * invPyth;
  1814. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1815. };
  1816. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1817. var dot = Vector3.Dot(this.normal, direction);
  1818. return (dot <= epsilon);
  1819. };
  1820. Plane.prototype.signedDistanceTo = function (point) {
  1821. return Vector3.Dot(point, this.normal) + this.d;
  1822. };
  1823. // Statics
  1824. Plane.FromArray = function (array) {
  1825. return new Plane(array[0], array[1], array[2], array[3]);
  1826. };
  1827. Plane.FromPoints = function (point1, point2, point3) {
  1828. var result = new Plane(0, 0, 0, 0);
  1829. result.copyFromPoints(point1, point2, point3);
  1830. return result;
  1831. };
  1832. Plane.FromPositionAndNormal = function (origin, normal) {
  1833. var result = new Plane(0, 0, 0, 0);
  1834. normal.normalize();
  1835. result.normal = normal;
  1836. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1837. return result;
  1838. };
  1839. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1840. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1841. return Vector3.Dot(point, normal) + d;
  1842. };
  1843. return Plane;
  1844. })();
  1845. BABYLON.Plane = Plane;
  1846. var Viewport = (function () {
  1847. function Viewport(x, y, width, height) {
  1848. this.x = x;
  1849. this.y = y;
  1850. this.width = width;
  1851. this.height = height;
  1852. }
  1853. Viewport.prototype.toGlobal = function (engine) {
  1854. var width = engine.getRenderWidth();
  1855. var height = engine.getRenderHeight();
  1856. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1857. };
  1858. return Viewport;
  1859. })();
  1860. BABYLON.Viewport = Viewport;
  1861. var Frustum = (function () {
  1862. function Frustum() {
  1863. }
  1864. Frustum.GetPlanes = function (transform) {
  1865. var frustumPlanes = [];
  1866. for (var index = 0; index < 6; index++) {
  1867. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1868. }
  1869. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1870. return frustumPlanes;
  1871. };
  1872. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1873. // Near
  1874. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1875. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1876. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1877. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1878. frustumPlanes[0].normalize();
  1879. // Far
  1880. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1881. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1882. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1883. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1884. frustumPlanes[1].normalize();
  1885. // Left
  1886. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1887. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1888. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1889. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1890. frustumPlanes[2].normalize();
  1891. // Right
  1892. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1893. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1894. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1895. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1896. frustumPlanes[3].normalize();
  1897. // Top
  1898. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1899. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1900. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1901. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1902. frustumPlanes[4].normalize();
  1903. // Bottom
  1904. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1905. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1906. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1907. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1908. frustumPlanes[5].normalize();
  1909. };
  1910. return Frustum;
  1911. })();
  1912. BABYLON.Frustum = Frustum;
  1913. var Ray = (function () {
  1914. function Ray(origin, direction, length) {
  1915. if (length === void 0) { length = Number.MAX_VALUE; }
  1916. this.origin = origin;
  1917. this.direction = direction;
  1918. this.length = length;
  1919. }
  1920. // Methods
  1921. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1922. var d = 0.0;
  1923. var maxValue = Number.MAX_VALUE;
  1924. if (Math.abs(this.direction.x) < 0.0000001) {
  1925. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1926. return false;
  1927. }
  1928. }
  1929. else {
  1930. var inv = 1.0 / this.direction.x;
  1931. var min = (minimum.x - this.origin.x) * inv;
  1932. var max = (maximum.x - this.origin.x) * inv;
  1933. if (max === -Infinity) {
  1934. max = Infinity;
  1935. }
  1936. if (min > max) {
  1937. var temp = min;
  1938. min = max;
  1939. max = temp;
  1940. }
  1941. d = Math.max(min, d);
  1942. maxValue = Math.min(max, maxValue);
  1943. if (d > maxValue) {
  1944. return false;
  1945. }
  1946. }
  1947. if (Math.abs(this.direction.y) < 0.0000001) {
  1948. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1949. return false;
  1950. }
  1951. }
  1952. else {
  1953. inv = 1.0 / this.direction.y;
  1954. min = (minimum.y - this.origin.y) * inv;
  1955. max = (maximum.y - this.origin.y) * inv;
  1956. if (max === -Infinity) {
  1957. max = Infinity;
  1958. }
  1959. if (min > max) {
  1960. temp = min;
  1961. min = max;
  1962. max = temp;
  1963. }
  1964. d = Math.max(min, d);
  1965. maxValue = Math.min(max, maxValue);
  1966. if (d > maxValue) {
  1967. return false;
  1968. }
  1969. }
  1970. if (Math.abs(this.direction.z) < 0.0000001) {
  1971. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1972. return false;
  1973. }
  1974. }
  1975. else {
  1976. inv = 1.0 / this.direction.z;
  1977. min = (minimum.z - this.origin.z) * inv;
  1978. max = (maximum.z - this.origin.z) * inv;
  1979. if (max === -Infinity) {
  1980. max = Infinity;
  1981. }
  1982. if (min > max) {
  1983. temp = min;
  1984. min = max;
  1985. max = temp;
  1986. }
  1987. d = Math.max(min, d);
  1988. maxValue = Math.min(max, maxValue);
  1989. if (d > maxValue) {
  1990. return false;
  1991. }
  1992. }
  1993. return true;
  1994. };
  1995. Ray.prototype.intersectsBox = function (box) {
  1996. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1997. };
  1998. Ray.prototype.intersectsSphere = function (sphere) {
  1999. var x = sphere.center.x - this.origin.x;
  2000. var y = sphere.center.y - this.origin.y;
  2001. var z = sphere.center.z - this.origin.z;
  2002. var pyth = (x * x) + (y * y) + (z * z);
  2003. var rr = sphere.radius * sphere.radius;
  2004. if (pyth <= rr) {
  2005. return true;
  2006. }
  2007. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2008. if (dot < 0.0) {
  2009. return false;
  2010. }
  2011. var temp = pyth - (dot * dot);
  2012. return temp <= rr;
  2013. };
  2014. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2015. if (!this._edge1) {
  2016. this._edge1 = Vector3.Zero();
  2017. this._edge2 = Vector3.Zero();
  2018. this._pvec = Vector3.Zero();
  2019. this._tvec = Vector3.Zero();
  2020. this._qvec = Vector3.Zero();
  2021. }
  2022. vertex1.subtractToRef(vertex0, this._edge1);
  2023. vertex2.subtractToRef(vertex0, this._edge2);
  2024. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2025. var det = Vector3.Dot(this._edge1, this._pvec);
  2026. if (det === 0) {
  2027. return null;
  2028. }
  2029. var invdet = 1 / det;
  2030. this.origin.subtractToRef(vertex0, this._tvec);
  2031. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2032. if (bu < 0 || bu > 1.0) {
  2033. return null;
  2034. }
  2035. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2036. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2037. if (bv < 0 || bu + bv > 1.0) {
  2038. return null;
  2039. }
  2040. //check if the distance is longer than the predefined length.
  2041. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2042. if (distance > this.length) {
  2043. return null;
  2044. }
  2045. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2046. };
  2047. // Statics
  2048. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2049. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2050. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2051. var direction = end.subtract(start);
  2052. direction.normalize();
  2053. return new Ray(start, direction);
  2054. };
  2055. /**
  2056. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2057. * transformed to the given world matrix.
  2058. * @param origin The origin point
  2059. * @param end The end point
  2060. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2061. */
  2062. Ray.CreateNewFromTo = function (origin, end, world) {
  2063. if (world === void 0) { world = Matrix.Identity(); }
  2064. var direction = end.subtract(origin);
  2065. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2066. direction.normalize();
  2067. return Ray.Transform(new Ray(origin, direction, length), world);
  2068. };
  2069. Ray.Transform = function (ray, matrix) {
  2070. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2071. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2072. return new Ray(newOrigin, newDirection, ray.length);
  2073. };
  2074. return Ray;
  2075. })();
  2076. BABYLON.Ray = Ray;
  2077. (function (Space) {
  2078. Space[Space["LOCAL"] = 0] = "LOCAL";
  2079. Space[Space["WORLD"] = 1] = "WORLD";
  2080. })(BABYLON.Space || (BABYLON.Space = {}));
  2081. var Space = BABYLON.Space;
  2082. var Axis = (function () {
  2083. function Axis() {
  2084. }
  2085. Axis.X = new Vector3(1, 0, 0);
  2086. Axis.Y = new Vector3(0, 1, 0);
  2087. Axis.Z = new Vector3(0, 0, 1);
  2088. return Axis;
  2089. })();
  2090. BABYLON.Axis = Axis;
  2091. ;
  2092. var BezierCurve = (function () {
  2093. function BezierCurve() {
  2094. }
  2095. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2096. // Extract X (which is equal to time here)
  2097. var f0 = 1 - 3 * x2 + 3 * x1;
  2098. var f1 = 3 * x2 - 6 * x1;
  2099. var f2 = 3 * x1;
  2100. var refinedT = t;
  2101. for (var i = 0; i < 5; i++) {
  2102. var refinedT2 = refinedT * refinedT;
  2103. var refinedT3 = refinedT2 * refinedT;
  2104. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2105. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2106. refinedT -= (x - t) * slope;
  2107. refinedT = Math.min(1, Math.max(0, refinedT));
  2108. }
  2109. // Resolve cubic bezier for the given x
  2110. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2111. };
  2112. return BezierCurve;
  2113. })();
  2114. BABYLON.BezierCurve = BezierCurve;
  2115. (function (Orientation) {
  2116. Orientation[Orientation["CW"] = 0] = "CW";
  2117. Orientation[Orientation["CCW"] = 1] = "CCW";
  2118. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2119. var Orientation = BABYLON.Orientation;
  2120. var Angle = (function () {
  2121. function Angle(radians) {
  2122. var _this = this;
  2123. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2124. this.radians = function () { return _this._radians; };
  2125. this._radians = radians;
  2126. if (this._radians < 0)
  2127. this._radians += (2 * Math.PI);
  2128. }
  2129. Angle.BetweenTwoPoints = function (a, b) {
  2130. var delta = b.subtract(a);
  2131. var theta = Math.atan2(delta.y, delta.x);
  2132. return new Angle(theta);
  2133. };
  2134. Angle.FromRadians = function (radians) {
  2135. return new Angle(radians);
  2136. };
  2137. Angle.FromDegrees = function (degrees) {
  2138. return new Angle(degrees * Math.PI / 180);
  2139. };
  2140. return Angle;
  2141. })();
  2142. BABYLON.Angle = Angle;
  2143. var Arc2 = (function () {
  2144. function Arc2(startPoint, midPoint, endPoint) {
  2145. this.startPoint = startPoint;
  2146. this.midPoint = midPoint;
  2147. this.endPoint = endPoint;
  2148. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2149. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2150. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2151. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2152. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2153. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2154. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2155. var a1 = this.startAngle.degrees();
  2156. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2157. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2158. // angles correction
  2159. if (a2 - a1 > +180.0)
  2160. a2 -= 360.0;
  2161. if (a2 - a1 < -180.0)
  2162. a2 += 360.0;
  2163. if (a3 - a2 > +180.0)
  2164. a3 -= 360.0;
  2165. if (a3 - a2 < -180.0)
  2166. a3 += 360.0;
  2167. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2168. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2169. }
  2170. return Arc2;
  2171. })();
  2172. BABYLON.Arc2 = Arc2;
  2173. var PathCursor = (function () {
  2174. function PathCursor(path) {
  2175. this.path = path;
  2176. this._onchange = new Array();
  2177. this.value = 0;
  2178. this.animations = new Array();
  2179. }
  2180. PathCursor.prototype.getPoint = function () {
  2181. var point = this.path.getPointAtLengthPosition(this.value);
  2182. return new Vector3(point.x, 0, point.y);
  2183. };
  2184. PathCursor.prototype.moveAhead = function (step) {
  2185. if (step === void 0) { step = 0.002; }
  2186. this.move(step);
  2187. };
  2188. PathCursor.prototype.moveBack = function (step) {
  2189. if (step === void 0) { step = 0.002; }
  2190. this.move(-step);
  2191. };
  2192. PathCursor.prototype.move = function (step) {
  2193. if (Math.abs(step) > 1) {
  2194. throw "step size should be less than 1.";
  2195. }
  2196. this.value += step;
  2197. this.ensureLimits();
  2198. this.raiseOnChange();
  2199. };
  2200. PathCursor.prototype.ensureLimits = function () {
  2201. while (this.value > 1) {
  2202. this.value -= 1;
  2203. }
  2204. while (this.value < 0) {
  2205. this.value += 1;
  2206. }
  2207. };
  2208. // used by animation engine
  2209. PathCursor.prototype.markAsDirty = function (propertyName) {
  2210. this.ensureLimits();
  2211. this.raiseOnChange();
  2212. };
  2213. PathCursor.prototype.raiseOnChange = function () {
  2214. var _this = this;
  2215. this._onchange.forEach(function (f) { return f(_this); });
  2216. };
  2217. PathCursor.prototype.onchange = function (f) {
  2218. this._onchange.push(f);
  2219. };
  2220. return PathCursor;
  2221. })();
  2222. BABYLON.PathCursor = PathCursor;
  2223. var Path2 = (function () {
  2224. function Path2(x, y) {
  2225. this._points = [];
  2226. this._length = 0;
  2227. this.closed = false;
  2228. this._points.push(new Vector2(x, y));
  2229. }
  2230. Path2.prototype.addLineTo = function (x, y) {
  2231. if (closed) {
  2232. BABYLON.Tools.Error("cannot add lines to closed paths");
  2233. return this;
  2234. }
  2235. var newPoint = new Vector2(x, y);
  2236. var previousPoint = this._points[this._points.length - 1];
  2237. this._points.push(newPoint);
  2238. this._length += newPoint.subtract(previousPoint).length();
  2239. return this;
  2240. };
  2241. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2242. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2243. if (closed) {
  2244. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2245. return this;
  2246. }
  2247. var startPoint = this._points[this._points.length - 1];
  2248. var midPoint = new Vector2(midX, midY);
  2249. var endPoint = new Vector2(endX, endY);
  2250. var arc = new Arc2(startPoint, midPoint, endPoint);
  2251. var increment = arc.angle.radians() / numberOfSegments;
  2252. if (arc.orientation === 0 /* CW */)
  2253. increment *= -1;
  2254. var currentAngle = arc.startAngle.radians() + increment;
  2255. for (var i = 0; i < numberOfSegments; i++) {
  2256. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2257. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2258. this.addLineTo(x, y);
  2259. currentAngle += increment;
  2260. }
  2261. return this;
  2262. };
  2263. Path2.prototype.close = function () {
  2264. this.closed = true;
  2265. return this;
  2266. };
  2267. Path2.prototype.length = function () {
  2268. var result = this._length;
  2269. if (!this.closed) {
  2270. var lastPoint = this._points[this._points.length - 1];
  2271. var firstPoint = this._points[0];
  2272. result += (firstPoint.subtract(lastPoint).length());
  2273. }
  2274. return result;
  2275. };
  2276. Path2.prototype.getPoints = function () {
  2277. return this._points;
  2278. };
  2279. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2280. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2281. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2282. return;
  2283. }
  2284. var lengthPosition = normalizedLengthPosition * this.length();
  2285. var previousOffset = 0;
  2286. for (var i = 0; i < this._points.length; i++) {
  2287. var j = (i + 1) % this._points.length;
  2288. var a = this._points[i];
  2289. var b = this._points[j];
  2290. var bToA = b.subtract(a);
  2291. var nextOffset = (bToA.length() + previousOffset);
  2292. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2293. var dir = bToA.normalize();
  2294. var localOffset = lengthPosition - previousOffset;
  2295. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2296. }
  2297. previousOffset = nextOffset;
  2298. }
  2299. BABYLON.Tools.Error("internal error");
  2300. };
  2301. Path2.StartingAt = function (x, y) {
  2302. return new Path2(x, y);
  2303. };
  2304. return Path2;
  2305. })();
  2306. BABYLON.Path2 = Path2;
  2307. })(BABYLON || (BABYLON = {}));
  2308. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2309. (function (BABYLON) {
  2310. // Screenshots
  2311. var screenshotCanvas;
  2312. var cloneValue = function (source, destinationObject) {
  2313. if (!source)
  2314. return null;
  2315. if (source instanceof BABYLON.Mesh) {
  2316. return null;
  2317. }
  2318. if (source instanceof BABYLON.SubMesh) {
  2319. return source.clone(destinationObject);
  2320. }
  2321. else if (source.clone) {
  2322. return source.clone();
  2323. }
  2324. return null;
  2325. };
  2326. var Tools = (function () {
  2327. function Tools() {
  2328. }
  2329. Tools.GetFilename = function (path) {
  2330. var index = path.lastIndexOf("/");
  2331. if (index < 0)
  2332. return path;
  2333. return path.substring(index + 1);
  2334. };
  2335. Tools.GetDOMTextContent = function (element) {
  2336. var result = "";
  2337. var child = element.firstChild;
  2338. while (child) {
  2339. if (child.nodeType == 3) {
  2340. result += child.textContent;
  2341. }
  2342. child = child.nextSibling;
  2343. }
  2344. return result;
  2345. };
  2346. Tools.ToDegrees = function (angle) {
  2347. return angle * 180 / Math.PI;
  2348. };
  2349. Tools.ToRadians = function (angle) {
  2350. return angle * Math.PI / 180;
  2351. };
  2352. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2353. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2354. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2355. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2356. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2357. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2358. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2359. }
  2360. return {
  2361. minimum: minimum,
  2362. maximum: maximum
  2363. };
  2364. };
  2365. Tools.ExtractMinAndMax = function (positions, start, count) {
  2366. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2367. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2368. for (var index = start; index < start + count; index++) {
  2369. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2370. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2371. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2372. }
  2373. return {
  2374. minimum: minimum,
  2375. maximum: maximum
  2376. };
  2377. };
  2378. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2379. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2380. return undefined;
  2381. return Array.isArray(obj) ? obj : [obj];
  2382. };
  2383. // Misc.
  2384. Tools.GetPointerPrefix = function () {
  2385. var eventPrefix = "pointer";
  2386. // Check if hand.js is referenced or if the browser natively supports pointer events
  2387. if (!navigator.pointerEnabled) {
  2388. eventPrefix = "mouse";
  2389. }
  2390. return eventPrefix;
  2391. };
  2392. Tools.QueueNewFrame = function (func) {
  2393. if (window.requestAnimationFrame)
  2394. window.requestAnimationFrame(func);
  2395. else if (window.msRequestAnimationFrame)
  2396. window.msRequestAnimationFrame(func);
  2397. else if (window.webkitRequestAnimationFrame)
  2398. window.webkitRequestAnimationFrame(func);
  2399. else if (window.mozRequestAnimationFrame)
  2400. window.mozRequestAnimationFrame(func);
  2401. else if (window.oRequestAnimationFrame)
  2402. window.oRequestAnimationFrame(func);
  2403. else {
  2404. window.setTimeout(func, 16);
  2405. }
  2406. };
  2407. Tools.RequestFullscreen = function (element) {
  2408. if (element.requestFullscreen)
  2409. element.requestFullscreen();
  2410. else if (element.msRequestFullscreen)
  2411. element.msRequestFullscreen();
  2412. else if (element.webkitRequestFullscreen)
  2413. element.webkitRequestFullscreen();
  2414. else if (element.mozRequestFullScreen)
  2415. element.mozRequestFullScreen();
  2416. };
  2417. Tools.ExitFullscreen = function () {
  2418. if (document.exitFullscreen) {
  2419. document.exitFullscreen();
  2420. }
  2421. else if (document.mozCancelFullScreen) {
  2422. document.mozCancelFullScreen();
  2423. }
  2424. else if (document.webkitCancelFullScreen) {
  2425. document.webkitCancelFullScreen();
  2426. }
  2427. else if (document.msCancelFullScreen) {
  2428. document.msCancelFullScreen();
  2429. }
  2430. };
  2431. // External files
  2432. Tools.CleanUrl = function (url) {
  2433. url = url.replace(/#/mg, "%23");
  2434. return url;
  2435. };
  2436. Tools.LoadImage = function (url, onload, onerror, database) {
  2437. url = Tools.CleanUrl(url);
  2438. var img = new Image();
  2439. if (url.substr(0, 5) != "data:")
  2440. img.crossOrigin = 'anonymous';
  2441. img.onload = function () {
  2442. onload(img);
  2443. };
  2444. img.onerror = function (err) {
  2445. onerror(img, err);
  2446. };
  2447. var noIndexedDB = function () {
  2448. img.src = url;
  2449. };
  2450. var loadFromIndexedDB = function () {
  2451. database.loadImageFromDB(url, img);
  2452. };
  2453. //ANY database to do!
  2454. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2455. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2456. }
  2457. else {
  2458. if (url.indexOf("file:") === -1) {
  2459. noIndexedDB();
  2460. }
  2461. else {
  2462. try {
  2463. var textureName = url.substring(5);
  2464. var blobURL;
  2465. try {
  2466. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2467. }
  2468. catch (ex) {
  2469. // Chrome doesn't support oneTimeOnly parameter
  2470. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2471. }
  2472. img.src = blobURL;
  2473. }
  2474. catch (e) {
  2475. Tools.Log("Error while trying to load texture: " + textureName);
  2476. img.src = null;
  2477. }
  2478. }
  2479. }
  2480. return img;
  2481. };
  2482. //ANY
  2483. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2484. url = Tools.CleanUrl(url);
  2485. var noIndexedDB = function () {
  2486. var request = new XMLHttpRequest();
  2487. var loadUrl = Tools.BaseUrl + url;
  2488. request.open('GET', loadUrl, true);
  2489. if (useArrayBuffer) {
  2490. request.responseType = "arraybuffer";
  2491. }
  2492. request.onprogress = progressCallBack;
  2493. request.onreadystatechange = function () {
  2494. if (request.readyState == 4) {
  2495. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2496. callback(!useArrayBuffer ? request.responseText : request.response);
  2497. }
  2498. else {
  2499. if (onError) {
  2500. onError();
  2501. }
  2502. else {
  2503. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2504. }
  2505. }
  2506. }
  2507. };
  2508. request.send(null);
  2509. };
  2510. var loadFromIndexedDB = function () {
  2511. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2512. };
  2513. if (url.indexOf("file:") !== -1) {
  2514. var fileName = url.substring(5);
  2515. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2516. }
  2517. else {
  2518. // Caching all files
  2519. if (database && database.enableSceneOffline) {
  2520. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2521. }
  2522. else {
  2523. noIndexedDB();
  2524. }
  2525. }
  2526. };
  2527. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2528. var reader = new FileReader();
  2529. reader.onload = function (e) {
  2530. callback(e.target.result);
  2531. };
  2532. reader.onprogress = progressCallback;
  2533. reader.readAsDataURL(fileToLoad);
  2534. };
  2535. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2536. var reader = new FileReader();
  2537. reader.onload = function (e) {
  2538. callback(e.target.result);
  2539. };
  2540. reader.onprogress = progressCallBack;
  2541. if (!useArrayBuffer) {
  2542. // Asynchronous read
  2543. reader.readAsText(fileToLoad);
  2544. }
  2545. else {
  2546. reader.readAsArrayBuffer(fileToLoad);
  2547. }
  2548. };
  2549. // Misc.
  2550. Tools.Clamp = function (value, min, max) {
  2551. if (min === void 0) { min = 0; }
  2552. if (max === void 0) { max = 1; }
  2553. return Math.min(max, Math.max(min, value));
  2554. };
  2555. // Returns -1 when value is a negative number and
  2556. // +1 when value is a positive number.
  2557. Tools.Sign = function (value) {
  2558. value = +value; // convert to a number
  2559. if (value === 0 || isNaN(value))
  2560. return value;
  2561. return value > 0 ? 1 : -1;
  2562. };
  2563. Tools.Format = function (value, decimals) {
  2564. if (decimals === void 0) { decimals = 2; }
  2565. return value.toFixed(decimals);
  2566. };
  2567. Tools.CheckExtends = function (v, min, max) {
  2568. if (v.x < min.x)
  2569. min.x = v.x;
  2570. if (v.y < min.y)
  2571. min.y = v.y;
  2572. if (v.z < min.z)
  2573. min.z = v.z;
  2574. if (v.x > max.x)
  2575. max.x = v.x;
  2576. if (v.y > max.y)
  2577. max.y = v.y;
  2578. if (v.z > max.z)
  2579. max.z = v.z;
  2580. };
  2581. Tools.WithinEpsilon = function (a, b, epsilon) {
  2582. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2583. var num = a - b;
  2584. return -epsilon <= num && num <= epsilon;
  2585. };
  2586. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2587. for (var prop in source) {
  2588. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2589. continue;
  2590. }
  2591. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2592. continue;
  2593. }
  2594. var sourceValue = source[prop];
  2595. var typeOfSourceValue = typeof sourceValue;
  2596. if (typeOfSourceValue == "function") {
  2597. continue;
  2598. }
  2599. if (typeOfSourceValue == "object") {
  2600. if (sourceValue instanceof Array) {
  2601. destination[prop] = [];
  2602. if (sourceValue.length > 0) {
  2603. if (typeof sourceValue[0] == "object") {
  2604. for (var index = 0; index < sourceValue.length; index++) {
  2605. var clonedValue = cloneValue(sourceValue[index], destination);
  2606. if (destination[prop].indexOf(clonedValue) === -1) {
  2607. destination[prop].push(clonedValue);
  2608. }
  2609. }
  2610. }
  2611. else {
  2612. destination[prop] = sourceValue.slice(0);
  2613. }
  2614. }
  2615. }
  2616. else {
  2617. destination[prop] = cloneValue(sourceValue, destination);
  2618. }
  2619. }
  2620. else {
  2621. destination[prop] = sourceValue;
  2622. }
  2623. }
  2624. };
  2625. Tools.IsEmpty = function (obj) {
  2626. for (var i in obj) {
  2627. return false;
  2628. }
  2629. return true;
  2630. };
  2631. Tools.RegisterTopRootEvents = function (events) {
  2632. for (var index = 0; index < events.length; index++) {
  2633. var event = events[index];
  2634. window.addEventListener(event.name, event.handler, false);
  2635. try {
  2636. if (window.parent) {
  2637. window.parent.addEventListener(event.name, event.handler, false);
  2638. }
  2639. }
  2640. catch (e) {
  2641. }
  2642. }
  2643. };
  2644. Tools.UnregisterTopRootEvents = function (events) {
  2645. for (var index = 0; index < events.length; index++) {
  2646. var event = events[index];
  2647. window.removeEventListener(event.name, event.handler);
  2648. try {
  2649. if (window.parent) {
  2650. window.parent.removeEventListener(event.name, event.handler);
  2651. }
  2652. }
  2653. catch (e) {
  2654. }
  2655. }
  2656. };
  2657. Tools.CreateScreenshot = function (engine, camera, size) {
  2658. var width;
  2659. var height;
  2660. var scene = camera.getScene();
  2661. var previousCamera = null;
  2662. if (scene.activeCamera !== camera) {
  2663. previousCamera = scene.activeCamera;
  2664. scene.activeCamera = camera;
  2665. }
  2666. //If a precision value is specified
  2667. if (size.precision) {
  2668. width = Math.round(engine.getRenderWidth() * size.precision);
  2669. height = Math.round(width / engine.getAspectRatio(camera));
  2670. size = { width: width, height: height };
  2671. }
  2672. else if (size.width && size.height) {
  2673. width = size.width;
  2674. height = size.height;
  2675. }
  2676. else if (size.width && !size.height) {
  2677. width = size.width;
  2678. height = Math.round(width / engine.getAspectRatio(camera));
  2679. size = { width: width, height: height };
  2680. }
  2681. else if (size.height && !size.width) {
  2682. height = size.height;
  2683. width = Math.round(height * engine.getAspectRatio(camera));
  2684. size = { width: width, height: height };
  2685. }
  2686. else if (!isNaN(size)) {
  2687. height = size;
  2688. width = size;
  2689. }
  2690. else {
  2691. Tools.Error("Invalid 'size' parameter !");
  2692. return;
  2693. }
  2694. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2695. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2696. texture.renderList = scene.meshes;
  2697. texture.onAfterRender = function () {
  2698. // Read the contents of the framebuffer
  2699. var numberOfChannelsByLine = width * 4;
  2700. var halfHeight = height / 2;
  2701. //Reading datas from WebGL
  2702. var data = engine.readPixels(0, 0, width, height);
  2703. for (var i = 0; i < halfHeight; i++) {
  2704. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2705. var currentCell = j + i * numberOfChannelsByLine;
  2706. var targetLine = height - i - 1;
  2707. var targetCell = j + targetLine * numberOfChannelsByLine;
  2708. var temp = data[currentCell];
  2709. data[currentCell] = data[targetCell];
  2710. data[targetCell] = temp;
  2711. }
  2712. }
  2713. // Create a 2D canvas to store the result
  2714. if (!screenshotCanvas) {
  2715. screenshotCanvas = document.createElement('canvas');
  2716. }
  2717. screenshotCanvas.width = width;
  2718. screenshotCanvas.height = height;
  2719. var context = screenshotCanvas.getContext('2d');
  2720. // Copy the pixels to a 2D canvas
  2721. var imageData = context.createImageData(width, height);
  2722. imageData.data.set(data);
  2723. context.putImageData(imageData, 0, 0);
  2724. var base64Image = screenshotCanvas.toDataURL();
  2725. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2726. if (("download" in document.createElement("a"))) {
  2727. var a = window.document.createElement("a");
  2728. a.href = base64Image;
  2729. var date = new Date();
  2730. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2731. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2732. window.document.body.appendChild(a);
  2733. a.addEventListener("click", function () {
  2734. a.parentElement.removeChild(a);
  2735. });
  2736. a.click();
  2737. }
  2738. else {
  2739. var newWindow = window.open("");
  2740. var img = newWindow.document.createElement("img");
  2741. img.src = base64Image;
  2742. newWindow.document.body.appendChild(img);
  2743. }
  2744. };
  2745. scene.incrementRenderId();
  2746. texture.render(true);
  2747. texture.dispose();
  2748. if (previousCamera) {
  2749. scene.activeCamera = previousCamera;
  2750. }
  2751. };
  2752. // XHR response validator for local file scenario
  2753. Tools.ValidateXHRData = function (xhr, dataType) {
  2754. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2755. if (dataType === void 0) { dataType = 7; }
  2756. try {
  2757. if (dataType & 1) {
  2758. if (xhr.responseText && xhr.responseText.length > 0) {
  2759. return true;
  2760. }
  2761. else if (dataType === 1) {
  2762. return false;
  2763. }
  2764. }
  2765. if (dataType & 2) {
  2766. // Check header width and height since there is no "TGA" magic number
  2767. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2768. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2769. return true;
  2770. }
  2771. else if (dataType === 2) {
  2772. return false;
  2773. }
  2774. }
  2775. if (dataType & 4) {
  2776. // Check for the "DDS" magic number
  2777. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2778. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2779. return true;
  2780. }
  2781. else {
  2782. return false;
  2783. }
  2784. }
  2785. }
  2786. catch (e) {
  2787. }
  2788. return false;
  2789. };
  2790. Object.defineProperty(Tools, "NoneLogLevel", {
  2791. get: function () {
  2792. return Tools._NoneLogLevel;
  2793. },
  2794. enumerable: true,
  2795. configurable: true
  2796. });
  2797. Object.defineProperty(Tools, "MessageLogLevel", {
  2798. get: function () {
  2799. return Tools._MessageLogLevel;
  2800. },
  2801. enumerable: true,
  2802. configurable: true
  2803. });
  2804. Object.defineProperty(Tools, "WarningLogLevel", {
  2805. get: function () {
  2806. return Tools._WarningLogLevel;
  2807. },
  2808. enumerable: true,
  2809. configurable: true
  2810. });
  2811. Object.defineProperty(Tools, "ErrorLogLevel", {
  2812. get: function () {
  2813. return Tools._ErrorLogLevel;
  2814. },
  2815. enumerable: true,
  2816. configurable: true
  2817. });
  2818. Object.defineProperty(Tools, "AllLogLevel", {
  2819. get: function () {
  2820. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2821. },
  2822. enumerable: true,
  2823. configurable: true
  2824. });
  2825. Tools._AddLogEntry = function (entry) {
  2826. Tools._LogCache = entry + Tools._LogCache;
  2827. if (Tools.OnNewCacheEntry) {
  2828. Tools.OnNewCacheEntry(entry);
  2829. }
  2830. };
  2831. Tools._FormatMessage = function (message) {
  2832. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  2833. var date = new Date();
  2834. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2835. };
  2836. Tools._LogDisabled = function (message) {
  2837. // nothing to do
  2838. };
  2839. Tools._LogEnabled = function (message) {
  2840. var formattedMessage = Tools._FormatMessage(message);
  2841. console.log("BJS - " + formattedMessage);
  2842. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2843. Tools._AddLogEntry(entry);
  2844. };
  2845. Tools._WarnDisabled = function (message) {
  2846. // nothing to do
  2847. };
  2848. Tools._WarnEnabled = function (message) {
  2849. var formattedMessage = Tools._FormatMessage(message);
  2850. console.warn("BJS - " + formattedMessage);
  2851. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2852. Tools._AddLogEntry(entry);
  2853. };
  2854. Tools._ErrorDisabled = function (message) {
  2855. // nothing to do
  2856. };
  2857. Tools._ErrorEnabled = function (message) {
  2858. var formattedMessage = Tools._FormatMessage(message);
  2859. console.error("BJS - " + formattedMessage);
  2860. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2861. Tools._AddLogEntry(entry);
  2862. };
  2863. Object.defineProperty(Tools, "LogCache", {
  2864. get: function () {
  2865. return Tools._LogCache;
  2866. },
  2867. enumerable: true,
  2868. configurable: true
  2869. });
  2870. Object.defineProperty(Tools, "LogLevels", {
  2871. set: function (level) {
  2872. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2873. Tools.Log = Tools._LogEnabled;
  2874. }
  2875. else {
  2876. Tools.Log = Tools._LogDisabled;
  2877. }
  2878. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2879. Tools.Warn = Tools._WarnEnabled;
  2880. }
  2881. else {
  2882. Tools.Warn = Tools._WarnDisabled;
  2883. }
  2884. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2885. Tools.Error = Tools._ErrorEnabled;
  2886. }
  2887. else {
  2888. Tools.Error = Tools._ErrorDisabled;
  2889. }
  2890. },
  2891. enumerable: true,
  2892. configurable: true
  2893. });
  2894. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2895. get: function () {
  2896. return Tools._PerformanceNoneLogLevel;
  2897. },
  2898. enumerable: true,
  2899. configurable: true
  2900. });
  2901. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2902. get: function () {
  2903. return Tools._PerformanceUserMarkLogLevel;
  2904. },
  2905. enumerable: true,
  2906. configurable: true
  2907. });
  2908. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2909. get: function () {
  2910. return Tools._PerformanceConsoleLogLevel;
  2911. },
  2912. enumerable: true,
  2913. configurable: true
  2914. });
  2915. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2916. set: function (level) {
  2917. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2918. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2919. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2920. return;
  2921. }
  2922. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2923. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2924. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2925. return;
  2926. }
  2927. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2928. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2929. },
  2930. enumerable: true,
  2931. configurable: true
  2932. });
  2933. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2934. };
  2935. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2936. };
  2937. Tools._StartUserMark = function (counterName, condition) {
  2938. if (condition === void 0) { condition = true; }
  2939. if (!condition || !Tools._performance.mark) {
  2940. return;
  2941. }
  2942. Tools._performance.mark(counterName + "-Begin");
  2943. };
  2944. Tools._EndUserMark = function (counterName, condition) {
  2945. if (condition === void 0) { condition = true; }
  2946. if (!condition || !Tools._performance.mark) {
  2947. return;
  2948. }
  2949. Tools._performance.mark(counterName + "-End");
  2950. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2951. };
  2952. Tools._StartPerformanceConsole = function (counterName, condition) {
  2953. if (condition === void 0) { condition = true; }
  2954. if (!condition) {
  2955. return;
  2956. }
  2957. Tools._StartUserMark(counterName, condition);
  2958. if (console.time) {
  2959. console.time(counterName);
  2960. }
  2961. };
  2962. Tools._EndPerformanceConsole = function (counterName, condition) {
  2963. if (condition === void 0) { condition = true; }
  2964. if (!condition) {
  2965. return;
  2966. }
  2967. Tools._EndUserMark(counterName, condition);
  2968. if (console.time) {
  2969. console.timeEnd(counterName);
  2970. }
  2971. };
  2972. Object.defineProperty(Tools, "Now", {
  2973. get: function () {
  2974. if (window.performance && window.performance.now) {
  2975. return window.performance.now();
  2976. }
  2977. return new Date().getTime();
  2978. },
  2979. enumerable: true,
  2980. configurable: true
  2981. });
  2982. // Deprecated
  2983. Tools.GetFps = function () {
  2984. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  2985. return 0;
  2986. };
  2987. Tools.BaseUrl = "";
  2988. Tools.GetExponantOfTwo = function (value, max) {
  2989. var count = 1;
  2990. do {
  2991. count *= 2;
  2992. } while (count < value);
  2993. if (count > max)
  2994. count = max;
  2995. return count;
  2996. };
  2997. // Logs
  2998. Tools._NoneLogLevel = 0;
  2999. Tools._MessageLogLevel = 1;
  3000. Tools._WarningLogLevel = 2;
  3001. Tools._ErrorLogLevel = 4;
  3002. Tools._LogCache = "";
  3003. Tools.Log = Tools._LogEnabled;
  3004. Tools.Warn = Tools._WarnEnabled;
  3005. Tools.Error = Tools._ErrorEnabled;
  3006. // Performances
  3007. Tools._PerformanceNoneLogLevel = 0;
  3008. Tools._PerformanceUserMarkLogLevel = 1;
  3009. Tools._PerformanceConsoleLogLevel = 2;
  3010. Tools._performance = window.performance;
  3011. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3012. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3013. return Tools;
  3014. })();
  3015. BABYLON.Tools = Tools;
  3016. /**
  3017. * An implementation of a loop for asynchronous functions.
  3018. */
  3019. var AsyncLoop = (function () {
  3020. /**
  3021. * Constroctor.
  3022. * @param iterations the number of iterations.
  3023. * @param _fn the function to run each iteration
  3024. * @param _successCallback the callback that will be called upon succesful execution
  3025. * @param offset starting offset.
  3026. */
  3027. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3028. if (offset === void 0) { offset = 0; }
  3029. this.iterations = iterations;
  3030. this._fn = _fn;
  3031. this._successCallback = _successCallback;
  3032. this.index = offset - 1;
  3033. this._done = false;
  3034. }
  3035. /**
  3036. * Execute the next iteration. Must be called after the last iteration was finished.
  3037. */
  3038. AsyncLoop.prototype.executeNext = function () {
  3039. if (!this._done) {
  3040. if (this.index + 1 < this.iterations) {
  3041. ++this.index;
  3042. this._fn(this);
  3043. }
  3044. else {
  3045. this.breakLoop();
  3046. }
  3047. }
  3048. };
  3049. /**
  3050. * Break the loop and run the success callback.
  3051. */
  3052. AsyncLoop.prototype.breakLoop = function () {
  3053. this._done = true;
  3054. this._successCallback();
  3055. };
  3056. /**
  3057. * Helper function
  3058. */
  3059. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3060. if (offset === void 0) { offset = 0; }
  3061. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3062. loop.executeNext();
  3063. return loop;
  3064. };
  3065. /**
  3066. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3067. * @param iterations total number of iterations
  3068. * @param syncedIterations number of synchronous iterations in each async iteration.
  3069. * @param fn the function to call each iteration.
  3070. * @param callback a success call back that will be called when iterating stops.
  3071. * @param breakFunction a break condition (optional)
  3072. * @param timeout timeout settings for the setTimeout function. default - 0.
  3073. * @constructor
  3074. */
  3075. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3076. if (timeout === void 0) { timeout = 0; }
  3077. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3078. if (breakFunction && breakFunction())
  3079. loop.breakLoop();
  3080. else {
  3081. setTimeout(function () {
  3082. for (var i = 0; i < syncedIterations; ++i) {
  3083. var iteration = (loop.index * syncedIterations) + i;
  3084. if (iteration >= iterations)
  3085. break;
  3086. fn(iteration);
  3087. if (breakFunction && breakFunction()) {
  3088. loop.breakLoop();
  3089. break;
  3090. }
  3091. }
  3092. loop.executeNext();
  3093. }, timeout);
  3094. }
  3095. }, callback);
  3096. };
  3097. return AsyncLoop;
  3098. })();
  3099. BABYLON.AsyncLoop = AsyncLoop;
  3100. })(BABYLON || (BABYLON = {}));
  3101. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3102. (function (BABYLON) {
  3103. var _DepthCullingState = (function () {
  3104. function _DepthCullingState() {
  3105. this._isDepthTestDirty = false;
  3106. this._isDepthMaskDirty = false;
  3107. this._isDepthFuncDirty = false;
  3108. this._isCullFaceDirty = false;
  3109. this._isCullDirty = false;
  3110. }
  3111. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3112. get: function () {
  3113. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3114. },
  3115. enumerable: true,
  3116. configurable: true
  3117. });
  3118. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3119. get: function () {
  3120. return this._cullFace;
  3121. },
  3122. set: function (value) {
  3123. if (this._cullFace === value) {
  3124. return;
  3125. }
  3126. this._cullFace = value;
  3127. this._isCullFaceDirty = true;
  3128. },
  3129. enumerable: true,
  3130. configurable: true
  3131. });
  3132. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3133. get: function () {
  3134. return this._cull;
  3135. },
  3136. set: function (value) {
  3137. if (this._cull === value) {
  3138. return;
  3139. }
  3140. this._cull = value;
  3141. this._isCullDirty = true;
  3142. },
  3143. enumerable: true,
  3144. configurable: true
  3145. });
  3146. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3147. get: function () {
  3148. return this._depthFunc;
  3149. },
  3150. set: function (value) {
  3151. if (this._depthFunc === value) {
  3152. return;
  3153. }
  3154. this._depthFunc = value;
  3155. this._isDepthFuncDirty = true;
  3156. },
  3157. enumerable: true,
  3158. configurable: true
  3159. });
  3160. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3161. get: function () {
  3162. return this._depthMask;
  3163. },
  3164. set: function (value) {
  3165. if (this._depthMask === value) {
  3166. return;
  3167. }
  3168. this._depthMask = value;
  3169. this._isDepthMaskDirty = true;
  3170. },
  3171. enumerable: true,
  3172. configurable: true
  3173. });
  3174. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3175. get: function () {
  3176. return this._depthTest;
  3177. },
  3178. set: function (value) {
  3179. if (this._depthTest === value) {
  3180. return;
  3181. }
  3182. this._depthTest = value;
  3183. this._isDepthTestDirty = true;
  3184. },
  3185. enumerable: true,
  3186. configurable: true
  3187. });
  3188. _DepthCullingState.prototype.reset = function () {
  3189. this._depthMask = true;
  3190. this._depthTest = true;
  3191. this._depthFunc = null;
  3192. this._cull = null;
  3193. this._cullFace = null;
  3194. this._isDepthTestDirty = true;
  3195. this._isDepthMaskDirty = true;
  3196. this._isDepthFuncDirty = false;
  3197. this._isCullFaceDirty = false;
  3198. this._isCullDirty = false;
  3199. };
  3200. _DepthCullingState.prototype.apply = function (gl) {
  3201. if (!this.isDirty) {
  3202. return;
  3203. }
  3204. // Cull
  3205. if (this._isCullDirty) {
  3206. if (this.cull) {
  3207. gl.enable(gl.CULL_FACE);
  3208. }
  3209. else {
  3210. gl.disable(gl.CULL_FACE);
  3211. }
  3212. this._isCullDirty = false;
  3213. }
  3214. // Cull face
  3215. if (this._isCullFaceDirty) {
  3216. gl.cullFace(this.cullFace);
  3217. this._isCullFaceDirty = false;
  3218. }
  3219. // Depth mask
  3220. if (this._isDepthMaskDirty) {
  3221. gl.depthMask(this.depthMask);
  3222. this._isDepthMaskDirty = false;
  3223. }
  3224. // Depth test
  3225. if (this._isDepthTestDirty) {
  3226. if (this.depthTest) {
  3227. gl.enable(gl.DEPTH_TEST);
  3228. }
  3229. else {
  3230. gl.disable(gl.DEPTH_TEST);
  3231. }
  3232. this._isDepthTestDirty = false;
  3233. }
  3234. // Depth func
  3235. if (this._isDepthFuncDirty) {
  3236. gl.depthFunc(this.depthFunc);
  3237. this._isDepthFuncDirty = false;
  3238. }
  3239. };
  3240. return _DepthCullingState;
  3241. })();
  3242. BABYLON._DepthCullingState = _DepthCullingState;
  3243. var _AlphaState = (function () {
  3244. function _AlphaState() {
  3245. this._isAlphaBlendDirty = false;
  3246. this._isBlendFunctionParametersDirty = false;
  3247. this._alphaBlend = false;
  3248. this._blendFunctionParameters = new Array(4);
  3249. }
  3250. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3251. get: function () {
  3252. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3253. },
  3254. enumerable: true,
  3255. configurable: true
  3256. });
  3257. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3258. get: function () {
  3259. return this._alphaBlend;
  3260. },
  3261. set: function (value) {
  3262. if (this._alphaBlend === value) {
  3263. return;
  3264. }
  3265. this._alphaBlend = value;
  3266. this._isAlphaBlendDirty = true;
  3267. },
  3268. enumerable: true,
  3269. configurable: true
  3270. });
  3271. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3272. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3273. return;
  3274. }
  3275. this._blendFunctionParameters[0] = value0;
  3276. this._blendFunctionParameters[1] = value1;
  3277. this._blendFunctionParameters[2] = value2;
  3278. this._blendFunctionParameters[3] = value3;
  3279. this._isBlendFunctionParametersDirty = true;
  3280. };
  3281. _AlphaState.prototype.reset = function () {
  3282. this._alphaBlend = false;
  3283. this._blendFunctionParameters[0] = null;
  3284. this._blendFunctionParameters[1] = null;
  3285. this._blendFunctionParameters[2] = null;
  3286. this._blendFunctionParameters[3] = null;
  3287. this._isAlphaBlendDirty = true;
  3288. this._isBlendFunctionParametersDirty = false;
  3289. };
  3290. _AlphaState.prototype.apply = function (gl) {
  3291. if (!this.isDirty) {
  3292. return;
  3293. }
  3294. // Alpha blend
  3295. if (this._isAlphaBlendDirty) {
  3296. if (this._alphaBlend) {
  3297. gl.enable(gl.BLEND);
  3298. }
  3299. else {
  3300. gl.disable(gl.BLEND);
  3301. }
  3302. this._isAlphaBlendDirty = false;
  3303. }
  3304. // Alpha function
  3305. if (this._isBlendFunctionParametersDirty) {
  3306. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3307. this._isBlendFunctionParametersDirty = false;
  3308. }
  3309. };
  3310. return _AlphaState;
  3311. })();
  3312. BABYLON._AlphaState = _AlphaState;
  3313. var compileShader = function (gl, source, type, defines) {
  3314. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3315. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3316. gl.compileShader(shader);
  3317. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3318. throw new Error(gl.getShaderInfoLog(shader));
  3319. }
  3320. return shader;
  3321. };
  3322. var getWebGLTextureType = function (gl, type) {
  3323. var textureType = gl.UNSIGNED_BYTE;
  3324. if (type === Engine.TEXTURETYPE_FLOAT)
  3325. textureType = gl.FLOAT;
  3326. return textureType;
  3327. };
  3328. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3329. var magFilter = gl.NEAREST;
  3330. var minFilter = gl.NEAREST;
  3331. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3332. magFilter = gl.LINEAR;
  3333. if (generateMipMaps) {
  3334. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3335. }
  3336. else {
  3337. minFilter = gl.LINEAR;
  3338. }
  3339. }
  3340. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3341. magFilter = gl.LINEAR;
  3342. if (generateMipMaps) {
  3343. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3344. }
  3345. else {
  3346. minFilter = gl.LINEAR;
  3347. }
  3348. }
  3349. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3350. magFilter = gl.NEAREST;
  3351. if (generateMipMaps) {
  3352. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3353. }
  3354. else {
  3355. minFilter = gl.NEAREST;
  3356. }
  3357. }
  3358. return {
  3359. min: minFilter,
  3360. mag: magFilter
  3361. };
  3362. };
  3363. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3364. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3365. var engine = scene.getEngine();
  3366. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3367. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3368. gl.bindTexture(gl.TEXTURE_2D, texture);
  3369. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3370. processFunction(potWidth, potHeight);
  3371. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3372. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3373. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3374. if (!noMipmap && !isCompressed) {
  3375. gl.generateMipmap(gl.TEXTURE_2D);
  3376. }
  3377. gl.bindTexture(gl.TEXTURE_2D, null);
  3378. engine._activeTexturesCache = [];
  3379. texture._baseWidth = width;
  3380. texture._baseHeight = height;
  3381. texture._width = potWidth;
  3382. texture._height = potHeight;
  3383. texture.isReady = true;
  3384. texture.samplingMode = samplingMode;
  3385. scene._removePendingData(texture);
  3386. };
  3387. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3388. var onload = function () {
  3389. loadedImages[index] = img;
  3390. loadedImages._internalCount++;
  3391. scene._removePendingData(img);
  3392. if (loadedImages._internalCount === 6) {
  3393. onfinish(loadedImages);
  3394. }
  3395. };
  3396. var onerror = function () {
  3397. scene._removePendingData(img);
  3398. };
  3399. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3400. scene._addPendingData(img);
  3401. };
  3402. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3403. var loadedImages = [];
  3404. loadedImages._internalCount = 0;
  3405. for (var index = 0; index < 6; index++) {
  3406. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3407. }
  3408. };
  3409. var EngineCapabilities = (function () {
  3410. function EngineCapabilities() {
  3411. }
  3412. return EngineCapabilities;
  3413. })();
  3414. BABYLON.EngineCapabilities = EngineCapabilities;
  3415. /**
  3416. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3417. */
  3418. var Engine = (function () {
  3419. /**
  3420. * @constructor
  3421. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3422. * @param {boolean} [antialias] - enable antialias
  3423. * @param options - further options to be sent to the getContext function
  3424. */
  3425. function Engine(canvas, antialias, options) {
  3426. var _this = this;
  3427. // Public members
  3428. this.isFullscreen = false;
  3429. this.isPointerLock = false;
  3430. this.cullBackFaces = true;
  3431. this.renderEvenInBackground = true;
  3432. this.scenes = new Array();
  3433. this._windowIsBackground = false;
  3434. this._loadingDivBackgroundColor = "black";
  3435. this._drawCalls = 0;
  3436. this._renderingQueueLaunched = false;
  3437. this._activeRenderLoops = [];
  3438. // FPS
  3439. this.fpsRange = 60;
  3440. this.previousFramesDuration = [];
  3441. this.fps = 60;
  3442. this.deltaTime = 0;
  3443. // States
  3444. this._depthCullingState = new _DepthCullingState();
  3445. this._alphaState = new _AlphaState();
  3446. this._alphaMode = Engine.ALPHA_DISABLE;
  3447. // Cache
  3448. this._loadedTexturesCache = new Array();
  3449. this._activeTexturesCache = new Array();
  3450. this._compiledEffects = {};
  3451. this._uintIndicesCurrentlySet = false;
  3452. this._renderingCanvas = canvas;
  3453. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3454. options = options || {};
  3455. options.antialias = antialias;
  3456. try {
  3457. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3458. }
  3459. catch (e) {
  3460. throw new Error("WebGL not supported");
  3461. }
  3462. if (!this._gl) {
  3463. throw new Error("WebGL not supported");
  3464. }
  3465. this._onBlur = function () {
  3466. _this._windowIsBackground = true;
  3467. };
  3468. this._onFocus = function () {
  3469. _this._windowIsBackground = false;
  3470. };
  3471. window.addEventListener("blur", this._onBlur);
  3472. window.addEventListener("focus", this._onFocus);
  3473. // Textures
  3474. this._workingCanvas = document.createElement("canvas");
  3475. this._workingContext = this._workingCanvas.getContext("2d");
  3476. // Viewport
  3477. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3478. this.resize();
  3479. // Caps
  3480. this._caps = new EngineCapabilities();
  3481. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3482. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3483. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3484. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3485. // Infos
  3486. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3487. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3488. if (rendererInfo != null) {
  3489. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3490. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3491. }
  3492. if (!this._glVendor) {
  3493. this._glVendor = "Unknown vendor";
  3494. }
  3495. if (!this._glRenderer) {
  3496. this._glRenderer = "Unknown renderer";
  3497. }
  3498. // Extensions
  3499. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3500. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3501. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3502. 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');
  3503. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3504. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3505. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3506. // Depth buffer
  3507. this.setDepthBuffer(true);
  3508. this.setDepthFunctionToLessOrEqual();
  3509. this.setDepthWrite(true);
  3510. // Fullscreen
  3511. this._onFullscreenChange = function () {
  3512. if (document.fullscreen !== undefined) {
  3513. _this.isFullscreen = document.fullscreen;
  3514. }
  3515. else if (document.mozFullScreen !== undefined) {
  3516. _this.isFullscreen = document.mozFullScreen;
  3517. }
  3518. else if (document.webkitIsFullScreen !== undefined) {
  3519. _this.isFullscreen = document.webkitIsFullScreen;
  3520. }
  3521. else if (document.msIsFullScreen !== undefined) {
  3522. _this.isFullscreen = document.msIsFullScreen;
  3523. }
  3524. // Pointer lock
  3525. if (_this.isFullscreen && _this._pointerLockRequested) {
  3526. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3527. if (canvas.requestPointerLock) {
  3528. canvas.requestPointerLock();
  3529. }
  3530. }
  3531. };
  3532. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3533. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3534. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3535. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3536. // Pointer lock
  3537. this._onPointerLockChange = function () {
  3538. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3539. };
  3540. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3541. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3542. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3543. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3544. if (!Engine.audioEngine) {
  3545. Engine.audioEngine = new BABYLON.AudioEngine();
  3546. }
  3547. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3548. }
  3549. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3550. get: function () {
  3551. return Engine._ALPHA_DISABLE;
  3552. },
  3553. enumerable: true,
  3554. configurable: true
  3555. });
  3556. Object.defineProperty(Engine, "ALPHA_ADD", {
  3557. get: function () {
  3558. return Engine._ALPHA_ADD;
  3559. },
  3560. enumerable: true,
  3561. configurable: true
  3562. });
  3563. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3564. get: function () {
  3565. return Engine._ALPHA_COMBINE;
  3566. },
  3567. enumerable: true,
  3568. configurable: true
  3569. });
  3570. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3571. get: function () {
  3572. return Engine._DELAYLOADSTATE_NONE;
  3573. },
  3574. enumerable: true,
  3575. configurable: true
  3576. });
  3577. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3578. get: function () {
  3579. return Engine._DELAYLOADSTATE_LOADED;
  3580. },
  3581. enumerable: true,
  3582. configurable: true
  3583. });
  3584. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3585. get: function () {
  3586. return Engine._DELAYLOADSTATE_LOADING;
  3587. },
  3588. enumerable: true,
  3589. configurable: true
  3590. });
  3591. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3592. get: function () {
  3593. return Engine._DELAYLOADSTATE_NOTLOADED;
  3594. },
  3595. enumerable: true,
  3596. configurable: true
  3597. });
  3598. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3599. get: function () {
  3600. return Engine._TEXTUREFORMAT_ALPHA;
  3601. },
  3602. enumerable: true,
  3603. configurable: true
  3604. });
  3605. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3606. get: function () {
  3607. return Engine._TEXTUREFORMAT_LUMINANCE;
  3608. },
  3609. enumerable: true,
  3610. configurable: true
  3611. });
  3612. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3613. get: function () {
  3614. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3615. },
  3616. enumerable: true,
  3617. configurable: true
  3618. });
  3619. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3620. get: function () {
  3621. return Engine._TEXTUREFORMAT_RGB;
  3622. },
  3623. enumerable: true,
  3624. configurable: true
  3625. });
  3626. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3627. get: function () {
  3628. return Engine._TEXTUREFORMAT_RGBA;
  3629. },
  3630. enumerable: true,
  3631. configurable: true
  3632. });
  3633. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3634. get: function () {
  3635. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3636. },
  3637. enumerable: true,
  3638. configurable: true
  3639. });
  3640. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3641. get: function () {
  3642. return Engine._TEXTURETYPE_FLOAT;
  3643. },
  3644. enumerable: true,
  3645. configurable: true
  3646. });
  3647. Object.defineProperty(Engine, "Version", {
  3648. get: function () {
  3649. return "2.0.0";
  3650. },
  3651. enumerable: true,
  3652. configurable: true
  3653. });
  3654. Engine.prototype.getGlInfo = function () {
  3655. return {
  3656. vendor: this._glVendor,
  3657. renderer: this._glRenderer,
  3658. version: this._glVersion
  3659. };
  3660. };
  3661. Engine.prototype.getAspectRatio = function (camera) {
  3662. var viewport = camera.viewport;
  3663. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3664. };
  3665. Engine.prototype.getRenderWidth = function () {
  3666. if (this._currentRenderTarget) {
  3667. return this._currentRenderTarget._width;
  3668. }
  3669. return this._renderingCanvas.width;
  3670. };
  3671. Engine.prototype.getRenderHeight = function () {
  3672. if (this._currentRenderTarget) {
  3673. return this._currentRenderTarget._height;
  3674. }
  3675. return this._renderingCanvas.height;
  3676. };
  3677. Engine.prototype.getRenderingCanvas = function () {
  3678. return this._renderingCanvas;
  3679. };
  3680. Engine.prototype.getRenderingCanvasClientRect = function () {
  3681. return this._renderingCanvas.getBoundingClientRect();
  3682. };
  3683. Engine.prototype.setHardwareScalingLevel = function (level) {
  3684. this._hardwareScalingLevel = level;
  3685. this.resize();
  3686. };
  3687. Engine.prototype.getHardwareScalingLevel = function () {
  3688. return this._hardwareScalingLevel;
  3689. };
  3690. Engine.prototype.getLoadedTexturesCache = function () {
  3691. return this._loadedTexturesCache;
  3692. };
  3693. Engine.prototype.getCaps = function () {
  3694. return this._caps;
  3695. };
  3696. Object.defineProperty(Engine.prototype, "drawCalls", {
  3697. get: function () {
  3698. return this._drawCalls;
  3699. },
  3700. enumerable: true,
  3701. configurable: true
  3702. });
  3703. // Methods
  3704. Engine.prototype.resetDrawCalls = function () {
  3705. this._drawCalls = 0;
  3706. };
  3707. Engine.prototype.setDepthFunctionToGreater = function () {
  3708. this._depthCullingState.depthFunc = this._gl.GREATER;
  3709. };
  3710. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3711. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3712. };
  3713. Engine.prototype.setDepthFunctionToLess = function () {
  3714. this._depthCullingState.depthFunc = this._gl.LESS;
  3715. };
  3716. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3717. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3718. };
  3719. /**
  3720. * stop executing a render loop function and remove it from the execution array
  3721. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  3722. */
  3723. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3724. if (!renderFunction) {
  3725. this._activeRenderLoops = [];
  3726. return;
  3727. }
  3728. var index = this._activeRenderLoops.indexOf(renderFunction);
  3729. if (index >= 0) {
  3730. this._activeRenderLoops.splice(index, 1);
  3731. }
  3732. };
  3733. Engine.prototype._renderLoop = function () {
  3734. var _this = this;
  3735. var shouldRender = true;
  3736. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3737. shouldRender = false;
  3738. }
  3739. if (shouldRender) {
  3740. // Start new frame
  3741. this.beginFrame();
  3742. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3743. var renderFunction = this._activeRenderLoops[index];
  3744. renderFunction();
  3745. }
  3746. // Present
  3747. this.endFrame();
  3748. }
  3749. if (this._activeRenderLoops.length > 0) {
  3750. // Register new frame
  3751. BABYLON.Tools.QueueNewFrame(function () {
  3752. _this._renderLoop();
  3753. });
  3754. }
  3755. else {
  3756. this._renderingQueueLaunched = false;
  3757. }
  3758. };
  3759. /**
  3760. * Register and execute a render loop. The engine can have more than one render function.
  3761. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  3762. * @example
  3763. * engine.runRenderLoop(function () {
  3764. * scene.render()
  3765. * })
  3766. */
  3767. Engine.prototype.runRenderLoop = function (renderFunction) {
  3768. var _this = this;
  3769. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3770. return;
  3771. }
  3772. this._activeRenderLoops.push(renderFunction);
  3773. if (!this._renderingQueueLaunched) {
  3774. this._renderingQueueLaunched = true;
  3775. BABYLON.Tools.QueueNewFrame(function () {
  3776. _this._renderLoop();
  3777. });
  3778. }
  3779. };
  3780. /**
  3781. * Toggle full screen mode.
  3782. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  3783. */
  3784. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3785. if (this.isFullscreen) {
  3786. BABYLON.Tools.ExitFullscreen();
  3787. }
  3788. else {
  3789. this._pointerLockRequested = requestPointerLock;
  3790. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3791. }
  3792. };
  3793. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3794. this.applyStates();
  3795. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3796. if (this._depthCullingState.depthMask) {
  3797. this._gl.clearDepth(1.0);
  3798. }
  3799. var mode = 0;
  3800. if (backBuffer)
  3801. mode |= this._gl.COLOR_BUFFER_BIT;
  3802. if (depthStencil && this._depthCullingState.depthMask)
  3803. mode |= this._gl.DEPTH_BUFFER_BIT;
  3804. this._gl.clear(mode);
  3805. };
  3806. /**
  3807. * Set the WebGL's viewport
  3808. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  3809. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  3810. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  3811. */
  3812. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3813. var width = requiredWidth || this._renderingCanvas.width;
  3814. var height = requiredHeight || this._renderingCanvas.height;
  3815. var x = viewport.x || 0;
  3816. var y = viewport.y || 0;
  3817. this._cachedViewport = viewport;
  3818. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3819. };
  3820. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3821. this._cachedViewport = null;
  3822. this._gl.viewport(x, y, width, height);
  3823. };
  3824. Engine.prototype.beginFrame = function () {
  3825. this._measureFps();
  3826. };
  3827. Engine.prototype.endFrame = function () {
  3828. this.flushFramebuffer();
  3829. };
  3830. /**
  3831. * resize the view according to the canvas' size.
  3832. * @example
  3833. * window.addEventListener("resize", function () {
  3834. * engine.resize();
  3835. * });
  3836. */
  3837. Engine.prototype.resize = function () {
  3838. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3839. };
  3840. /**
  3841. * force a specific size of the canvas
  3842. * @param {number} width - the new canvas' width
  3843. * @param {number} height - the new canvas' height
  3844. */
  3845. Engine.prototype.setSize = function (width, height) {
  3846. this._renderingCanvas.width = width;
  3847. this._renderingCanvas.height = height;
  3848. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3849. };
  3850. Engine.prototype.bindFramebuffer = function (texture) {
  3851. this._currentRenderTarget = texture;
  3852. var gl = this._gl;
  3853. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3854. this._gl.viewport(0, 0, texture._width, texture._height);
  3855. this.wipeCaches();
  3856. };
  3857. Engine.prototype.unBindFramebuffer = function (texture) {
  3858. this._currentRenderTarget = null;
  3859. if (texture.generateMipMaps) {
  3860. var gl = this._gl;
  3861. gl.bindTexture(gl.TEXTURE_2D, texture);
  3862. gl.generateMipmap(gl.TEXTURE_2D);
  3863. gl.bindTexture(gl.TEXTURE_2D, null);
  3864. }
  3865. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3866. };
  3867. Engine.prototype.flushFramebuffer = function () {
  3868. // this._gl.flush();
  3869. };
  3870. Engine.prototype.restoreDefaultFramebuffer = function () {
  3871. this._currentRenderTarget = null;
  3872. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3873. this.setViewport(this._cachedViewport);
  3874. this.wipeCaches();
  3875. };
  3876. // VBOs
  3877. Engine.prototype._resetVertexBufferBinding = function () {
  3878. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3879. this._cachedVertexBuffers = null;
  3880. };
  3881. Engine.prototype.createVertexBuffer = function (vertices) {
  3882. var vbo = this._gl.createBuffer();
  3883. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3884. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3885. this._resetVertexBufferBinding();
  3886. vbo.references = 1;
  3887. return vbo;
  3888. };
  3889. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3890. var vbo = this._gl.createBuffer();
  3891. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3892. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3893. this._resetVertexBufferBinding();
  3894. vbo.references = 1;
  3895. return vbo;
  3896. };
  3897. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3898. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3899. if (offset === undefined) {
  3900. offset = 0;
  3901. }
  3902. if (vertices instanceof Float32Array) {
  3903. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3904. }
  3905. else {
  3906. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3907. }
  3908. this._resetVertexBufferBinding();
  3909. };
  3910. Engine.prototype._resetIndexBufferBinding = function () {
  3911. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3912. this._cachedIndexBuffer = null;
  3913. };
  3914. Engine.prototype.createIndexBuffer = function (indices) {
  3915. var vbo = this._gl.createBuffer();
  3916. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3917. // Check for 32 bits indices
  3918. var arrayBuffer;
  3919. var need32Bits = false;
  3920. if (this._caps.uintIndices) {
  3921. for (var index = 0; index < indices.length; index++) {
  3922. if (indices[index] > 65535) {
  3923. need32Bits = true;
  3924. break;
  3925. }
  3926. }
  3927. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3928. }
  3929. else {
  3930. arrayBuffer = new Uint16Array(indices);
  3931. }
  3932. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3933. this._resetIndexBufferBinding();
  3934. vbo.references = 1;
  3935. vbo.is32Bits = need32Bits;
  3936. return vbo;
  3937. };
  3938. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3939. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3940. this._cachedVertexBuffers = vertexBuffer;
  3941. this._cachedEffectForVertexBuffers = effect;
  3942. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3943. var offset = 0;
  3944. for (var index = 0; index < vertexDeclaration.length; index++) {
  3945. var order = effect.getAttributeLocation(index);
  3946. if (order >= 0) {
  3947. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3948. }
  3949. offset += vertexDeclaration[index] * 4;
  3950. }
  3951. }
  3952. if (this._cachedIndexBuffer !== indexBuffer) {
  3953. this._cachedIndexBuffer = indexBuffer;
  3954. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3955. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3956. }
  3957. };
  3958. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3959. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3960. this._cachedVertexBuffers = vertexBuffers;
  3961. this._cachedEffectForVertexBuffers = effect;
  3962. var attributes = effect.getAttributesNames();
  3963. for (var index = 0; index < attributes.length; index++) {
  3964. var order = effect.getAttributeLocation(index);
  3965. if (order >= 0) {
  3966. var vertexBuffer = vertexBuffers[attributes[index]];
  3967. if (!vertexBuffer) {
  3968. continue;
  3969. }
  3970. var stride = vertexBuffer.getStrideSize();
  3971. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3972. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3973. }
  3974. }
  3975. }
  3976. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3977. this._cachedIndexBuffer = indexBuffer;
  3978. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3979. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3980. }
  3981. };
  3982. Engine.prototype._releaseBuffer = function (buffer) {
  3983. buffer.references--;
  3984. if (buffer.references === 0) {
  3985. this._gl.deleteBuffer(buffer);
  3986. return true;
  3987. }
  3988. return false;
  3989. };
  3990. Engine.prototype.createInstancesBuffer = function (capacity) {
  3991. var buffer = this._gl.createBuffer();
  3992. buffer.capacity = capacity;
  3993. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3994. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3995. return buffer;
  3996. };
  3997. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3998. this._gl.deleteBuffer(buffer);
  3999. };
  4000. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4001. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4002. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4003. for (var index = 0; index < 4; index++) {
  4004. var offsetLocation = offsetLocations[index];
  4005. this._gl.enableVertexAttribArray(offsetLocation);
  4006. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4007. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4008. }
  4009. };
  4010. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4011. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4012. for (var index = 0; index < 4; index++) {
  4013. var offsetLocation = offsetLocations[index];
  4014. this._gl.disableVertexAttribArray(offsetLocation);
  4015. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4016. }
  4017. };
  4018. Engine.prototype.applyStates = function () {
  4019. this._depthCullingState.apply(this._gl);
  4020. this._alphaState.apply(this._gl);
  4021. };
  4022. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4023. // Apply states
  4024. this.applyStates();
  4025. this._drawCalls++;
  4026. // Render
  4027. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4028. if (instancesCount) {
  4029. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4030. return;
  4031. }
  4032. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4033. };
  4034. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4035. // Apply states
  4036. this.applyStates();
  4037. this._drawCalls++;
  4038. if (instancesCount) {
  4039. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4040. return;
  4041. }
  4042. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4043. };
  4044. // Shaders
  4045. Engine.prototype._releaseEffect = function (effect) {
  4046. if (this._compiledEffects[effect._key]) {
  4047. delete this._compiledEffects[effect._key];
  4048. if (effect.getProgram()) {
  4049. this._gl.deleteProgram(effect.getProgram());
  4050. }
  4051. }
  4052. };
  4053. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4054. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4055. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4056. var name = vertex + "+" + fragment + "@" + defines;
  4057. if (this._compiledEffects[name]) {
  4058. return this._compiledEffects[name];
  4059. }
  4060. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4061. effect._key = name;
  4062. this._compiledEffects[name] = effect;
  4063. return effect;
  4064. };
  4065. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4066. if (uniformsNames === void 0) { uniformsNames = []; }
  4067. if (samplers === void 0) { samplers = []; }
  4068. if (defines === void 0) { defines = ""; }
  4069. return this.createEffect({
  4070. vertex: "particles",
  4071. fragmentElement: fragmentName
  4072. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4073. };
  4074. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4075. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4076. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4077. var shaderProgram = this._gl.createProgram();
  4078. this._gl.attachShader(shaderProgram, vertexShader);
  4079. this._gl.attachShader(shaderProgram, fragmentShader);
  4080. this._gl.linkProgram(shaderProgram);
  4081. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4082. if (!linked) {
  4083. var error = this._gl.getProgramInfoLog(shaderProgram);
  4084. if (error) {
  4085. throw new Error(error);
  4086. }
  4087. }
  4088. this._gl.deleteShader(vertexShader);
  4089. this._gl.deleteShader(fragmentShader);
  4090. return shaderProgram;
  4091. };
  4092. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4093. var results = [];
  4094. for (var index = 0; index < uniformsNames.length; index++) {
  4095. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4096. }
  4097. return results;
  4098. };
  4099. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4100. var results = [];
  4101. for (var index = 0; index < attributesNames.length; index++) {
  4102. try {
  4103. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4104. }
  4105. catch (e) {
  4106. results.push(-1);
  4107. }
  4108. }
  4109. return results;
  4110. };
  4111. Engine.prototype.enableEffect = function (effect) {
  4112. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4113. if (effect && effect.onBind) {
  4114. effect.onBind(effect);
  4115. }
  4116. return;
  4117. }
  4118. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4119. // Use program
  4120. this._gl.useProgram(effect.getProgram());
  4121. for (var i in this._vertexAttribArrays) {
  4122. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4123. continue;
  4124. }
  4125. this._vertexAttribArrays[i] = false;
  4126. this._gl.disableVertexAttribArray(i);
  4127. }
  4128. var attributesCount = effect.getAttributesCount();
  4129. for (var index = 0; index < attributesCount; index++) {
  4130. // Attributes
  4131. var order = effect.getAttributeLocation(index);
  4132. if (order >= 0) {
  4133. this._vertexAttribArrays[order] = true;
  4134. this._gl.enableVertexAttribArray(order);
  4135. }
  4136. }
  4137. this._currentEffect = effect;
  4138. if (effect.onBind) {
  4139. effect.onBind(effect);
  4140. }
  4141. };
  4142. Engine.prototype.setArray = function (uniform, array) {
  4143. if (!uniform)
  4144. return;
  4145. this._gl.uniform1fv(uniform, array);
  4146. };
  4147. Engine.prototype.setArray2 = function (uniform, array) {
  4148. if (!uniform || array.length % 2 !== 0)
  4149. return;
  4150. this._gl.uniform2fv(uniform, array);
  4151. };
  4152. Engine.prototype.setArray3 = function (uniform, array) {
  4153. if (!uniform || array.length % 3 !== 0)
  4154. return;
  4155. this._gl.uniform3fv(uniform, array);
  4156. };
  4157. Engine.prototype.setArray4 = function (uniform, array) {
  4158. if (!uniform || array.length % 4 !== 0)
  4159. return;
  4160. this._gl.uniform4fv(uniform, array);
  4161. };
  4162. Engine.prototype.setMatrices = function (uniform, matrices) {
  4163. if (!uniform)
  4164. return;
  4165. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4166. };
  4167. Engine.prototype.setMatrix = function (uniform, matrix) {
  4168. if (!uniform)
  4169. return;
  4170. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4171. };
  4172. Engine.prototype.setFloat = function (uniform, value) {
  4173. if (!uniform)
  4174. return;
  4175. this._gl.uniform1f(uniform, value);
  4176. };
  4177. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4178. if (!uniform)
  4179. return;
  4180. this._gl.uniform2f(uniform, x, y);
  4181. };
  4182. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4183. if (!uniform)
  4184. return;
  4185. this._gl.uniform3f(uniform, x, y, z);
  4186. };
  4187. Engine.prototype.setBool = function (uniform, bool) {
  4188. if (!uniform)
  4189. return;
  4190. this._gl.uniform1i(uniform, bool);
  4191. };
  4192. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4193. if (!uniform)
  4194. return;
  4195. this._gl.uniform4f(uniform, x, y, z, w);
  4196. };
  4197. Engine.prototype.setColor3 = function (uniform, color3) {
  4198. if (!uniform)
  4199. return;
  4200. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4201. };
  4202. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4203. if (!uniform)
  4204. return;
  4205. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4206. };
  4207. // States
  4208. Engine.prototype.setState = function (culling, force) {
  4209. // Culling
  4210. if (this._depthCullingState.cull !== culling || force) {
  4211. if (culling) {
  4212. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4213. this._depthCullingState.cull = true;
  4214. }
  4215. else {
  4216. this._depthCullingState.cull = false;
  4217. }
  4218. }
  4219. };
  4220. Engine.prototype.setDepthBuffer = function (enable) {
  4221. this._depthCullingState.depthTest = enable;
  4222. };
  4223. Engine.prototype.getDepthWrite = function () {
  4224. return this._depthCullingState.depthMask;
  4225. };
  4226. Engine.prototype.setDepthWrite = function (enable) {
  4227. this._depthCullingState.depthMask = enable;
  4228. };
  4229. Engine.prototype.setColorWrite = function (enable) {
  4230. this._gl.colorMask(enable, enable, enable, enable);
  4231. };
  4232. Engine.prototype.setAlphaMode = function (mode) {
  4233. switch (mode) {
  4234. case Engine.ALPHA_DISABLE:
  4235. this.setDepthWrite(true);
  4236. this._alphaState.alphaBlend = false;
  4237. break;
  4238. case Engine.ALPHA_COMBINE:
  4239. this.setDepthWrite(false);
  4240. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4241. this._alphaState.alphaBlend = true;
  4242. break;
  4243. case Engine.ALPHA_ADD:
  4244. this.setDepthWrite(false);
  4245. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4246. this._alphaState.alphaBlend = true;
  4247. break;
  4248. }
  4249. this._alphaMode = mode;
  4250. };
  4251. Engine.prototype.getAlphaMode = function () {
  4252. return this._alphaMode;
  4253. };
  4254. Engine.prototype.setAlphaTesting = function (enable) {
  4255. this._alphaTest = enable;
  4256. };
  4257. Engine.prototype.getAlphaTesting = function () {
  4258. return this._alphaTest;
  4259. };
  4260. // Textures
  4261. Engine.prototype.wipeCaches = function () {
  4262. this._activeTexturesCache = [];
  4263. this._currentEffect = null;
  4264. this._depthCullingState.reset();
  4265. this._alphaState.reset();
  4266. this._cachedVertexBuffers = null;
  4267. this._cachedIndexBuffer = null;
  4268. this._cachedEffectForVertexBuffers = null;
  4269. };
  4270. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4271. var gl = this._gl;
  4272. gl.bindTexture(gl.TEXTURE_2D, texture);
  4273. var magFilter = gl.NEAREST;
  4274. var minFilter = gl.NEAREST;
  4275. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4276. magFilter = gl.LINEAR;
  4277. minFilter = gl.LINEAR;
  4278. }
  4279. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4280. magFilter = gl.LINEAR;
  4281. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4282. }
  4283. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4284. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4285. gl.bindTexture(gl.TEXTURE_2D, null);
  4286. texture.samplingMode = samplingMode;
  4287. };
  4288. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4289. var _this = this;
  4290. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4291. if (onLoad === void 0) { onLoad = null; }
  4292. if (onError === void 0) { onError = null; }
  4293. if (buffer === void 0) { buffer = null; }
  4294. var texture = this._gl.createTexture();
  4295. var extension;
  4296. var fromData = false;
  4297. if (url.substr(0, 5) === "data:") {
  4298. fromData = true;
  4299. }
  4300. if (!fromData)
  4301. extension = url.substr(url.length - 4, 4).toLowerCase();
  4302. else {
  4303. var oldUrl = url;
  4304. fromData = oldUrl.split(':');
  4305. url = oldUrl;
  4306. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4307. }
  4308. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4309. var isTGA = (extension === ".tga");
  4310. scene._addPendingData(texture);
  4311. texture.url = url;
  4312. texture.noMipmap = noMipmap;
  4313. texture.references = 1;
  4314. this._loadedTexturesCache.push(texture);
  4315. var onerror = function () {
  4316. scene._removePendingData(texture);
  4317. if (onError) {
  4318. onError();
  4319. }
  4320. };
  4321. if (isTGA) {
  4322. var callback = function (arrayBuffer) {
  4323. var data = new Uint8Array(arrayBuffer);
  4324. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4325. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4326. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4327. if (onLoad) {
  4328. onLoad();
  4329. }
  4330. }, samplingMode);
  4331. };
  4332. if (!(fromData instanceof Array))
  4333. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4334. callback(arrayBuffer);
  4335. }, onerror, scene.database, true);
  4336. else
  4337. callback(buffer);
  4338. }
  4339. else if (isDDS) {
  4340. callback = function (data) {
  4341. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4342. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4343. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4344. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4345. if (onLoad) {
  4346. onLoad();
  4347. }
  4348. }, samplingMode);
  4349. };
  4350. if (!(fromData instanceof Array))
  4351. BABYLON.Tools.LoadFile(url, function (data) {
  4352. callback(data);
  4353. }, onerror, scene.database, true);
  4354. else
  4355. callback(buffer);
  4356. }
  4357. else {
  4358. var onload = function (img) {
  4359. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4360. var isPot = (img.width === potWidth && img.height === potHeight);
  4361. if (!isPot) {
  4362. _this._workingCanvas.width = potWidth;
  4363. _this._workingCanvas.height = potHeight;
  4364. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4365. _this._workingContext.imageSmoothingEnabled = false;
  4366. _this._workingContext.mozImageSmoothingEnabled = false;
  4367. _this._workingContext.oImageSmoothingEnabled = false;
  4368. _this._workingContext.webkitImageSmoothingEnabled = false;
  4369. _this._workingContext.msImageSmoothingEnabled = false;
  4370. }
  4371. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4372. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4373. _this._workingContext.imageSmoothingEnabled = true;
  4374. _this._workingContext.mozImageSmoothingEnabled = true;
  4375. _this._workingContext.oImageSmoothingEnabled = true;
  4376. _this._workingContext.webkitImageSmoothingEnabled = true;
  4377. _this._workingContext.msImageSmoothingEnabled = true;
  4378. }
  4379. }
  4380. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4381. if (onLoad) {
  4382. onLoad();
  4383. }
  4384. }, samplingMode);
  4385. };
  4386. if (!(fromData instanceof Array))
  4387. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4388. else
  4389. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4390. }
  4391. return texture;
  4392. };
  4393. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4394. var texture = this._gl.createTexture();
  4395. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4396. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4397. // Format
  4398. var internalFormat = this._gl.RGBA;
  4399. switch (format) {
  4400. case Engine.TEXTUREFORMAT_ALPHA:
  4401. internalFormat = this._gl.ALPHA;
  4402. break;
  4403. case Engine.TEXTUREFORMAT_LUMINANCE:
  4404. internalFormat = this._gl.LUMINANCE;
  4405. break;
  4406. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4407. internalFormat = this._gl.LUMINANCE_ALPHA;
  4408. break;
  4409. case Engine.TEXTUREFORMAT_RGB:
  4410. internalFormat = this._gl.RGB;
  4411. break;
  4412. case Engine.TEXTUREFORMAT_RGBA:
  4413. internalFormat = this._gl.RGBA;
  4414. break;
  4415. }
  4416. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4417. if (generateMipMaps) {
  4418. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4419. }
  4420. // Filters
  4421. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4422. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4423. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4424. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4425. this._activeTexturesCache = [];
  4426. texture._baseWidth = width;
  4427. texture._baseHeight = height;
  4428. texture._width = width;
  4429. texture._height = height;
  4430. texture.isReady = true;
  4431. texture.references = 1;
  4432. texture.samplingMode = samplingMode;
  4433. this._loadedTexturesCache.push(texture);
  4434. return texture;
  4435. };
  4436. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4437. var texture = this._gl.createTexture();
  4438. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4439. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4440. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4441. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4442. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4443. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4444. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4445. this._activeTexturesCache = [];
  4446. texture._baseWidth = width;
  4447. texture._baseHeight = height;
  4448. texture._width = width;
  4449. texture._height = height;
  4450. texture.isReady = false;
  4451. texture.generateMipMaps = generateMipMaps;
  4452. texture.references = 1;
  4453. texture.samplingMode = samplingMode;
  4454. this._loadedTexturesCache.push(texture);
  4455. return texture;
  4456. };
  4457. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4458. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4459. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4460. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4461. if (texture.generateMipMaps) {
  4462. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4463. }
  4464. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4465. this._activeTexturesCache = [];
  4466. texture.isReady = true;
  4467. };
  4468. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4469. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4470. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4471. // Scale the video if it is a NPOT using the current working canvas
  4472. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4473. if (!texture._workingCanvas) {
  4474. texture._workingCanvas = document.createElement("canvas");
  4475. texture._workingContext = texture._workingCanvas.getContext("2d");
  4476. texture._workingCanvas.width = texture._width;
  4477. texture._workingCanvas.height = texture._height;
  4478. }
  4479. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4480. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4481. }
  4482. else {
  4483. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4484. }
  4485. if (texture.generateMipMaps) {
  4486. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4487. }
  4488. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4489. this._activeTexturesCache = [];
  4490. texture.isReady = true;
  4491. };
  4492. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4493. // old version had a "generateMipMaps" arg instead of options.
  4494. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4495. // in the same way, generateDepthBuffer is defaulted to true
  4496. var generateMipMaps = false;
  4497. var generateDepthBuffer = true;
  4498. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4499. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4500. if (options !== undefined) {
  4501. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4502. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4503. type = options.type === undefined ? type : options.type;
  4504. if (options.samplingMode !== undefined) {
  4505. samplingMode = options.samplingMode;
  4506. }
  4507. if (type === Engine.TEXTURETYPE_FLOAT) {
  4508. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4509. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4510. }
  4511. }
  4512. var gl = this._gl;
  4513. var texture = gl.createTexture();
  4514. gl.bindTexture(gl.TEXTURE_2D, texture);
  4515. var width = size.width || size;
  4516. var height = size.height || size;
  4517. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4518. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4519. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4520. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4521. }
  4522. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4523. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4524. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4525. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4526. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4527. var depthBuffer;
  4528. // Create the depth buffer
  4529. if (generateDepthBuffer) {
  4530. depthBuffer = gl.createRenderbuffer();
  4531. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4532. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4533. }
  4534. // Create the framebuffer
  4535. var framebuffer = gl.createFramebuffer();
  4536. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4537. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4538. if (generateDepthBuffer) {
  4539. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4540. }
  4541. // Unbind
  4542. gl.bindTexture(gl.TEXTURE_2D, null);
  4543. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4544. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4545. texture._framebuffer = framebuffer;
  4546. if (generateDepthBuffer) {
  4547. texture._depthBuffer = depthBuffer;
  4548. }
  4549. texture._width = width;
  4550. texture._height = height;
  4551. texture.isReady = true;
  4552. texture.generateMipMaps = generateMipMaps;
  4553. texture.references = 1;
  4554. texture.samplingMode = samplingMode;
  4555. this._activeTexturesCache = [];
  4556. this._loadedTexturesCache.push(texture);
  4557. return texture;
  4558. };
  4559. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4560. var _this = this;
  4561. var gl = this._gl;
  4562. var texture = gl.createTexture();
  4563. texture.isCube = true;
  4564. texture.url = rootUrl;
  4565. texture.references = 1;
  4566. this._loadedTexturesCache.push(texture);
  4567. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4568. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4569. if (isDDS) {
  4570. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4571. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4572. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4573. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4574. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4575. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4576. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4577. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4578. }
  4579. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4580. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4581. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4582. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4583. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4584. _this._activeTexturesCache = [];
  4585. texture._width = info.width;
  4586. texture._height = info.height;
  4587. texture.isReady = true;
  4588. }, null, null, true);
  4589. }
  4590. else {
  4591. cascadeLoad(rootUrl, scene, function (imgs) {
  4592. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4593. var height = width;
  4594. _this._workingCanvas.width = width;
  4595. _this._workingCanvas.height = height;
  4596. var faces = [
  4597. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4598. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4599. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4600. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4601. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4602. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4603. ];
  4604. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4605. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4606. for (var index = 0; index < faces.length; index++) {
  4607. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4608. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4609. }
  4610. if (!noMipmap) {
  4611. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4612. }
  4613. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4614. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4615. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4616. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4617. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4618. _this._activeTexturesCache = [];
  4619. texture._width = width;
  4620. texture._height = height;
  4621. texture.isReady = true;
  4622. }, extensions);
  4623. }
  4624. return texture;
  4625. };
  4626. Engine.prototype._releaseTexture = function (texture) {
  4627. var gl = this._gl;
  4628. if (texture._framebuffer) {
  4629. gl.deleteFramebuffer(texture._framebuffer);
  4630. }
  4631. if (texture._depthBuffer) {
  4632. gl.deleteRenderbuffer(texture._depthBuffer);
  4633. }
  4634. gl.deleteTexture(texture);
  4635. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4636. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4637. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4638. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4639. this._activeTexturesCache[channel] = null;
  4640. }
  4641. var index = this._loadedTexturesCache.indexOf(texture);
  4642. if (index !== -1) {
  4643. this._loadedTexturesCache.splice(index, 1);
  4644. }
  4645. };
  4646. Engine.prototype.bindSamplers = function (effect) {
  4647. this._gl.useProgram(effect.getProgram());
  4648. var samplers = effect.getSamplers();
  4649. for (var index = 0; index < samplers.length; index++) {
  4650. var uniform = effect.getUniform(samplers[index]);
  4651. this._gl.uniform1i(uniform, index);
  4652. }
  4653. this._currentEffect = null;
  4654. };
  4655. Engine.prototype._bindTexture = function (channel, texture) {
  4656. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4657. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4658. this._activeTexturesCache[channel] = null;
  4659. };
  4660. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4661. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4662. };
  4663. Engine.prototype.setTexture = function (channel, texture) {
  4664. if (channel < 0) {
  4665. return;
  4666. }
  4667. // Not ready?
  4668. if (!texture || !texture.isReady()) {
  4669. if (this._activeTexturesCache[channel] != null) {
  4670. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4671. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4672. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4673. this._activeTexturesCache[channel] = null;
  4674. }
  4675. return;
  4676. }
  4677. // Video
  4678. if (texture instanceof BABYLON.VideoTexture) {
  4679. if (texture.update()) {
  4680. this._activeTexturesCache[channel] = null;
  4681. }
  4682. }
  4683. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4684. texture.delayLoad();
  4685. return;
  4686. }
  4687. if (this._activeTexturesCache[channel] === texture) {
  4688. return;
  4689. }
  4690. this._activeTexturesCache[channel] = texture;
  4691. var internalTexture = texture.getInternalTexture();
  4692. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4693. if (internalTexture.isCube) {
  4694. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4695. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4696. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4697. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4698. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4699. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4700. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4701. }
  4702. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4703. }
  4704. else {
  4705. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4706. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4707. internalTexture._cachedWrapU = texture.wrapU;
  4708. switch (texture.wrapU) {
  4709. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4710. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4711. break;
  4712. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4713. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4714. break;
  4715. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4716. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4717. break;
  4718. }
  4719. }
  4720. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4721. internalTexture._cachedWrapV = texture.wrapV;
  4722. switch (texture.wrapV) {
  4723. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4724. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4725. break;
  4726. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4727. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4728. break;
  4729. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4730. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4731. break;
  4732. }
  4733. }
  4734. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4735. }
  4736. };
  4737. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4738. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4739. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4740. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4741. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4742. }
  4743. };
  4744. Engine.prototype.readPixels = function (x, y, width, height) {
  4745. var data = new Uint8Array(height * width * 4);
  4746. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4747. return data;
  4748. };
  4749. // Dispose
  4750. Engine.prototype.dispose = function () {
  4751. this.hideLoadingUI();
  4752. this.stopRenderLoop();
  4753. while (this.scenes.length) {
  4754. this.scenes[0].dispose();
  4755. }
  4756. // Release audio engine
  4757. Engine.audioEngine.dispose();
  4758. for (var name in this._compiledEffects) {
  4759. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4760. }
  4761. for (var i in this._vertexAttribArrays) {
  4762. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4763. continue;
  4764. }
  4765. this._gl.disableVertexAttribArray(i);
  4766. }
  4767. // Events
  4768. window.removeEventListener("blur", this._onBlur);
  4769. window.removeEventListener("focus", this._onFocus);
  4770. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4771. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4772. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4773. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4774. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4775. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4776. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4777. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4778. };
  4779. // Loading screen
  4780. Engine.prototype.displayLoadingUI = function () {
  4781. var _this = this;
  4782. this._loadingDiv = document.createElement("div");
  4783. this._loadingDiv.style.opacity = "0";
  4784. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4785. // Loading text
  4786. this._loadingTextDiv = document.createElement("div");
  4787. this._loadingTextDiv.style.position = "absolute";
  4788. this._loadingTextDiv.style.left = "0";
  4789. this._loadingTextDiv.style.top = "50%";
  4790. this._loadingTextDiv.style.marginTop = "80px";
  4791. this._loadingTextDiv.style.width = "100%";
  4792. this._loadingTextDiv.style.height = "20px";
  4793. this._loadingTextDiv.style.fontFamily = "Arial";
  4794. this._loadingTextDiv.style.fontSize = "14px";
  4795. this._loadingTextDiv.style.color = "white";
  4796. this._loadingTextDiv.style.textAlign = "center";
  4797. this._loadingTextDiv.innerHTML = "Loading";
  4798. this._loadingDiv.appendChild(this._loadingTextDiv);
  4799. // Loading img
  4800. var imgBack = new Image();
  4801. 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==";
  4802. imgBack.style.position = "absolute";
  4803. imgBack.style.left = "50%";
  4804. imgBack.style.top = "50%";
  4805. imgBack.style.marginLeft = "-50px";
  4806. imgBack.style.marginTop = "-50px";
  4807. imgBack.style.transition = "transform 1.0s ease";
  4808. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4809. var deg = 360;
  4810. var onTransitionEnd = function () {
  4811. deg += 360;
  4812. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4813. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4814. };
  4815. imgBack.addEventListener("transitionend", onTransitionEnd);
  4816. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4817. this._loadingDiv.appendChild(imgBack);
  4818. // front image
  4819. var imgFront = new Image();
  4820. 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=";
  4821. imgFront.style.position = "absolute";
  4822. imgFront.style.left = "50%";
  4823. imgFront.style.top = "50%";
  4824. imgFront.style.marginLeft = "-50px";
  4825. imgFront.style.marginTop = "-50px";
  4826. this._loadingDiv.appendChild(imgFront);
  4827. // Resize
  4828. this._resizeLoadingUI = function () {
  4829. var canvasRect = _this.getRenderingCanvasClientRect();
  4830. _this._loadingDiv.style.position = "absolute";
  4831. _this._loadingDiv.style.left = canvasRect.left + "px";
  4832. _this._loadingDiv.style.top = canvasRect.top + "px";
  4833. _this._loadingDiv.style.width = canvasRect.width + "px";
  4834. _this._loadingDiv.style.height = canvasRect.height + "px";
  4835. };
  4836. this._resizeLoadingUI();
  4837. window.addEventListener("resize", this._resizeLoadingUI);
  4838. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4839. document.body.appendChild(this._loadingDiv);
  4840. setTimeout(function () {
  4841. _this._loadingDiv.style.opacity = "1";
  4842. imgBack.style.transform = "rotateZ(360deg)";
  4843. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4844. }, 0);
  4845. };
  4846. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4847. set: function (text) {
  4848. if (!this._loadingDiv) {
  4849. return;
  4850. }
  4851. this._loadingTextDiv.innerHTML = text;
  4852. },
  4853. enumerable: true,
  4854. configurable: true
  4855. });
  4856. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4857. get: function () {
  4858. return this._loadingDivBackgroundColor;
  4859. },
  4860. set: function (color) {
  4861. this._loadingDivBackgroundColor = color;
  4862. if (!this._loadingDiv) {
  4863. return;
  4864. }
  4865. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4866. },
  4867. enumerable: true,
  4868. configurable: true
  4869. });
  4870. Engine.prototype.hideLoadingUI = function () {
  4871. var _this = this;
  4872. if (!this._loadingDiv) {
  4873. return;
  4874. }
  4875. var onTransitionEnd = function () {
  4876. if (!_this._loadingDiv) {
  4877. return;
  4878. }
  4879. document.body.removeChild(_this._loadingDiv);
  4880. window.removeEventListener("resize", _this._resizeLoadingUI);
  4881. _this._loadingDiv = null;
  4882. };
  4883. this._loadingDiv.style.opacity = "0";
  4884. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4885. };
  4886. // FPS
  4887. Engine.prototype.getFps = function () {
  4888. return this.fps;
  4889. };
  4890. Engine.prototype.getDeltaTime = function () {
  4891. return this.deltaTime;
  4892. };
  4893. Engine.prototype._measureFps = function () {
  4894. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4895. var length = this.previousFramesDuration.length;
  4896. if (length >= 2) {
  4897. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4898. }
  4899. if (length >= this.fpsRange) {
  4900. if (length > this.fpsRange) {
  4901. this.previousFramesDuration.splice(0, 1);
  4902. length = this.previousFramesDuration.length;
  4903. }
  4904. var sum = 0;
  4905. for (var id = 0; id < length - 1; id++) {
  4906. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4907. }
  4908. this.fps = 1000.0 / (sum / (length - 1));
  4909. }
  4910. };
  4911. // Statics
  4912. Engine.isSupported = function () {
  4913. try {
  4914. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4915. if (navigator.isCocoonJS) {
  4916. return true;
  4917. }
  4918. var tempcanvas = document.createElement("canvas");
  4919. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4920. return gl != null && !!window.WebGLRenderingContext;
  4921. }
  4922. catch (e) {
  4923. return false;
  4924. }
  4925. };
  4926. // Const statics
  4927. Engine._ALPHA_DISABLE = 0;
  4928. Engine._ALPHA_ADD = 1;
  4929. Engine._ALPHA_COMBINE = 2;
  4930. Engine._DELAYLOADSTATE_NONE = 0;
  4931. Engine._DELAYLOADSTATE_LOADED = 1;
  4932. Engine._DELAYLOADSTATE_LOADING = 2;
  4933. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4934. Engine._TEXTUREFORMAT_ALPHA = 0;
  4935. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  4936. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  4937. Engine._TEXTUREFORMAT_RGB = 4;
  4938. Engine._TEXTUREFORMAT_RGBA = 4;
  4939. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  4940. Engine._TEXTURETYPE_FLOAT = 1;
  4941. // Updatable statics so stick with vars here
  4942. Engine.Epsilon = 0.001;
  4943. Engine.CollisionsEpsilon = 0.001;
  4944. Engine.ShadersRepository = "Babylon/Shaders/";
  4945. return Engine;
  4946. })();
  4947. BABYLON.Engine = Engine;
  4948. })(BABYLON || (BABYLON = {}));
  4949. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  4950. (function (BABYLON) {
  4951. /**
  4952. * Node is the basic class for all scene objects (Mesh, Light Camera).
  4953. */
  4954. var Node = (function () {
  4955. /**
  4956. * @constructor
  4957. * @param {string} name - the name and id to be given to this node
  4958. * @param {BABYLON.Scene} the scene this node will be added to
  4959. */
  4960. function Node(name, scene) {
  4961. this.state = "";
  4962. this.animations = new Array();
  4963. this._childrenFlag = -1;
  4964. this._isEnabled = true;
  4965. this._isReady = true;
  4966. this._currentRenderId = -1;
  4967. this.name = name;
  4968. this.id = name;
  4969. this._scene = scene;
  4970. this._initCache();
  4971. }
  4972. Node.prototype.getScene = function () {
  4973. return this._scene;
  4974. };
  4975. Node.prototype.getEngine = function () {
  4976. return this._scene.getEngine();
  4977. };
  4978. // override it in derived class
  4979. Node.prototype.getWorldMatrix = function () {
  4980. return BABYLON.Matrix.Identity();
  4981. };
  4982. // override it in derived class if you add new variables to the cache
  4983. // and call the parent class method
  4984. Node.prototype._initCache = function () {
  4985. this._cache = {};
  4986. this._cache.parent = undefined;
  4987. };
  4988. Node.prototype.updateCache = function (force) {
  4989. if (!force && this.isSynchronized())
  4990. return;
  4991. this._cache.parent = this.parent;
  4992. this._updateCache();
  4993. };
  4994. // override it in derived class if you add new variables to the cache
  4995. // and call the parent class method if !ignoreParentClass
  4996. Node.prototype._updateCache = function (ignoreParentClass) {
  4997. };
  4998. // override it in derived class if you add new variables to the cache
  4999. Node.prototype._isSynchronized = function () {
  5000. return true;
  5001. };
  5002. Node.prototype.isSynchronizedWithParent = function () {
  5003. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  5004. };
  5005. Node.prototype.isSynchronized = function (updateCache) {
  5006. var check = this.hasNewParent();
  5007. check = check || !this.isSynchronizedWithParent();
  5008. check = check || !this._isSynchronized();
  5009. if (updateCache)
  5010. this.updateCache(true);
  5011. return !check;
  5012. };
  5013. Node.prototype.hasNewParent = function (update) {
  5014. if (this._cache.parent === this.parent)
  5015. return false;
  5016. if (update)
  5017. this._cache.parent = this.parent;
  5018. return true;
  5019. };
  5020. /**
  5021. * Is this node ready to be used/rendered
  5022. * @return {boolean} is it ready
  5023. */
  5024. Node.prototype.isReady = function () {
  5025. return this._isReady;
  5026. };
  5027. /**
  5028. * Is this node enabled.
  5029. * If the node has a parent and is enabled, the parent will be inspected as well.
  5030. * @return {boolean} whether this node (and its parent) is enabled.
  5031. * @see setEnabled
  5032. */
  5033. Node.prototype.isEnabled = function () {
  5034. if (!this._isEnabled) {
  5035. return false;
  5036. }
  5037. if (this.parent) {
  5038. return this.parent.isEnabled();
  5039. }
  5040. return true;
  5041. };
  5042. /**
  5043. * Set the enabled state of this node.
  5044. * @param {boolean} value - the new enabled state
  5045. * @see isEnabled
  5046. */
  5047. Node.prototype.setEnabled = function (value) {
  5048. this._isEnabled = value;
  5049. };
  5050. /**
  5051. * Is this node a descendant of the given node.
  5052. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5053. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5054. * @see parent
  5055. */
  5056. Node.prototype.isDescendantOf = function (ancestor) {
  5057. if (this.parent) {
  5058. if (this.parent === ancestor) {
  5059. return true;
  5060. }
  5061. return this.parent.isDescendantOf(ancestor);
  5062. }
  5063. return false;
  5064. };
  5065. Node.prototype._getDescendants = function (list, results) {
  5066. for (var index = 0; index < list.length; index++) {
  5067. var item = list[index];
  5068. if (item.isDescendantOf(this)) {
  5069. results.push(item);
  5070. }
  5071. }
  5072. };
  5073. /**
  5074. * Will return all nodes that have this node as parent.
  5075. * @return {BABYLON.Node[]} all children nodes of all types.
  5076. */
  5077. Node.prototype.getDescendants = function () {
  5078. var results = [];
  5079. this._getDescendants(this._scene.meshes, results);
  5080. this._getDescendants(this._scene.lights, results);
  5081. this._getDescendants(this._scene.cameras, results);
  5082. return results;
  5083. };
  5084. Node.prototype._setReady = function (state) {
  5085. if (state == this._isReady) {
  5086. return;
  5087. }
  5088. if (!state) {
  5089. this._isReady = false;
  5090. return;
  5091. }
  5092. this._isReady = true;
  5093. if (this.onReady) {
  5094. this.onReady(this);
  5095. }
  5096. };
  5097. return Node;
  5098. })();
  5099. BABYLON.Node = Node;
  5100. })(BABYLON || (BABYLON = {}));
  5101. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5102. (function (BABYLON) {
  5103. var BoundingSphere = (function () {
  5104. function BoundingSphere(minimum, maximum) {
  5105. this.minimum = minimum;
  5106. this.maximum = maximum;
  5107. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5108. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5109. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5110. this.radius = distance * 0.5;
  5111. this.centerWorld = BABYLON.Vector3.Zero();
  5112. this._update(BABYLON.Matrix.Identity());
  5113. }
  5114. // Methods
  5115. BoundingSphere.prototype._update = function (world) {
  5116. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5117. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5118. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5119. };
  5120. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5121. for (var i = 0; i < 6; i++) {
  5122. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5123. return false;
  5124. }
  5125. return true;
  5126. };
  5127. BoundingSphere.prototype.intersectsPoint = function (point) {
  5128. var x = this.centerWorld.x - point.x;
  5129. var y = this.centerWorld.y - point.y;
  5130. var z = this.centerWorld.z - point.z;
  5131. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5132. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5133. return false;
  5134. return true;
  5135. };
  5136. // Statics
  5137. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5138. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5139. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5140. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5141. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5142. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5143. return false;
  5144. return true;
  5145. };
  5146. return BoundingSphere;
  5147. })();
  5148. BABYLON.BoundingSphere = BoundingSphere;
  5149. })(BABYLON || (BABYLON = {}));
  5150. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5151. (function (BABYLON) {
  5152. var BoundingBox = (function () {
  5153. function BoundingBox(minimum, maximum) {
  5154. this.minimum = minimum;
  5155. this.maximum = maximum;
  5156. this.vectors = new Array();
  5157. this.vectorsWorld = new Array();
  5158. // Bounding vectors
  5159. this.vectors.push(this.minimum.clone());
  5160. this.vectors.push(this.maximum.clone());
  5161. this.vectors.push(this.minimum.clone());
  5162. this.vectors[2].x = this.maximum.x;
  5163. this.vectors.push(this.minimum.clone());
  5164. this.vectors[3].y = this.maximum.y;
  5165. this.vectors.push(this.minimum.clone());
  5166. this.vectors[4].z = this.maximum.z;
  5167. this.vectors.push(this.maximum.clone());
  5168. this.vectors[5].z = this.minimum.z;
  5169. this.vectors.push(this.maximum.clone());
  5170. this.vectors[6].x = this.minimum.x;
  5171. this.vectors.push(this.maximum.clone());
  5172. this.vectors[7].y = this.minimum.y;
  5173. // OBB
  5174. this.center = this.maximum.add(this.minimum).scale(0.5);
  5175. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5176. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5177. for (var index = 0; index < this.vectors.length; index++) {
  5178. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5179. }
  5180. this.minimumWorld = BABYLON.Vector3.Zero();
  5181. this.maximumWorld = BABYLON.Vector3.Zero();
  5182. this._update(BABYLON.Matrix.Identity());
  5183. }
  5184. // Methods
  5185. BoundingBox.prototype.getWorldMatrix = function () {
  5186. return this._worldMatrix;
  5187. };
  5188. BoundingBox.prototype._update = function (world) {
  5189. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5190. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5191. for (var index = 0; index < this.vectors.length; index++) {
  5192. var v = this.vectorsWorld[index];
  5193. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5194. if (v.x < this.minimumWorld.x)
  5195. this.minimumWorld.x = v.x;
  5196. if (v.y < this.minimumWorld.y)
  5197. this.minimumWorld.y = v.y;
  5198. if (v.z < this.minimumWorld.z)
  5199. this.minimumWorld.z = v.z;
  5200. if (v.x > this.maximumWorld.x)
  5201. this.maximumWorld.x = v.x;
  5202. if (v.y > this.maximumWorld.y)
  5203. this.maximumWorld.y = v.y;
  5204. if (v.z > this.maximumWorld.z)
  5205. this.maximumWorld.z = v.z;
  5206. }
  5207. // OBB
  5208. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5209. this.center.scaleInPlace(0.5);
  5210. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5211. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5212. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5213. this._worldMatrix = world;
  5214. };
  5215. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5216. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5217. };
  5218. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5219. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5220. };
  5221. BoundingBox.prototype.intersectsPoint = function (point) {
  5222. var delta = BABYLON.Engine.Epsilon;
  5223. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5224. return false;
  5225. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5226. return false;
  5227. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5228. return false;
  5229. return true;
  5230. };
  5231. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5232. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5233. };
  5234. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5235. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5236. return false;
  5237. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5238. return false;
  5239. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5240. return false;
  5241. return true;
  5242. };
  5243. // Statics
  5244. BoundingBox.Intersects = function (box0, box1) {
  5245. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5246. return false;
  5247. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5248. return false;
  5249. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5250. return false;
  5251. return true;
  5252. };
  5253. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5254. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5255. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5256. return (num <= (sphereRadius * sphereRadius));
  5257. };
  5258. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5259. for (var p = 0; p < 6; p++) {
  5260. for (var i = 0; i < 8; i++) {
  5261. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5262. return false;
  5263. }
  5264. }
  5265. }
  5266. return true;
  5267. };
  5268. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5269. for (var p = 0; p < 6; p++) {
  5270. var inCount = 8;
  5271. for (var i = 0; i < 8; i++) {
  5272. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5273. --inCount;
  5274. }
  5275. else {
  5276. break;
  5277. }
  5278. }
  5279. if (inCount == 0)
  5280. return false;
  5281. }
  5282. return true;
  5283. };
  5284. return BoundingBox;
  5285. })();
  5286. BABYLON.BoundingBox = BoundingBox;
  5287. })(BABYLON || (BABYLON = {}));
  5288. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5289. (function (BABYLON) {
  5290. var computeBoxExtents = function (axis, box) {
  5291. var p = BABYLON.Vector3.Dot(box.center, axis);
  5292. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5293. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5294. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5295. var r = r0 + r1 + r2;
  5296. return {
  5297. min: p - r,
  5298. max: p + r
  5299. };
  5300. };
  5301. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5302. var axisOverlap = function (axis, box0, box1) {
  5303. var result0 = computeBoxExtents(axis, box0);
  5304. var result1 = computeBoxExtents(axis, box1);
  5305. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5306. };
  5307. var BoundingInfo = (function () {
  5308. function BoundingInfo(minimum, maximum) {
  5309. this.minimum = minimum;
  5310. this.maximum = maximum;
  5311. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5312. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5313. }
  5314. // Methods
  5315. BoundingInfo.prototype._update = function (world) {
  5316. this.boundingBox._update(world);
  5317. this.boundingSphere._update(world);
  5318. };
  5319. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5320. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5321. return false;
  5322. return this.boundingBox.isInFrustum(frustumPlanes);
  5323. };
  5324. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5325. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5326. };
  5327. BoundingInfo.prototype._checkCollision = function (collider) {
  5328. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5329. };
  5330. BoundingInfo.prototype.intersectsPoint = function (point) {
  5331. if (!this.boundingSphere.centerWorld) {
  5332. return false;
  5333. }
  5334. if (!this.boundingSphere.intersectsPoint(point)) {
  5335. return false;
  5336. }
  5337. if (!this.boundingBox.intersectsPoint(point)) {
  5338. return false;
  5339. }
  5340. return true;
  5341. };
  5342. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5343. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5344. return false;
  5345. }
  5346. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5347. return false;
  5348. }
  5349. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5350. return false;
  5351. }
  5352. if (!precise) {
  5353. return true;
  5354. }
  5355. var box0 = this.boundingBox;
  5356. var box1 = boundingInfo.boundingBox;
  5357. if (!axisOverlap(box0.directions[0], box0, box1))
  5358. return false;
  5359. if (!axisOverlap(box0.directions[1], box0, box1))
  5360. return false;
  5361. if (!axisOverlap(box0.directions[2], box0, box1))
  5362. return false;
  5363. if (!axisOverlap(box1.directions[0], box0, box1))
  5364. return false;
  5365. if (!axisOverlap(box1.directions[1], box0, box1))
  5366. return false;
  5367. if (!axisOverlap(box1.directions[2], box0, box1))
  5368. return false;
  5369. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5370. return false;
  5371. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5372. return false;
  5373. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5374. return false;
  5375. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5376. return false;
  5377. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5378. return false;
  5379. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5380. return false;
  5381. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5382. return false;
  5383. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5384. return false;
  5385. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5386. return false;
  5387. return true;
  5388. };
  5389. return BoundingInfo;
  5390. })();
  5391. BABYLON.BoundingInfo = BoundingInfo;
  5392. })(BABYLON || (BABYLON = {}));
  5393. //# sourceMappingURL=babylon.boundingInfo.js.map
  5394. var BABYLON;
  5395. (function (BABYLON) {
  5396. var Light = (function (_super) {
  5397. __extends(Light, _super);
  5398. function Light(name, scene) {
  5399. _super.call(this, name, scene);
  5400. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5401. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5402. this.intensity = 1.0;
  5403. this.range = Number.MAX_VALUE;
  5404. this.includedOnlyMeshes = new Array();
  5405. this.excludedMeshes = new Array();
  5406. this._excludedMeshesIds = new Array();
  5407. this._includedOnlyMeshesIds = new Array();
  5408. scene.lights.push(this);
  5409. }
  5410. Light.prototype.getShadowGenerator = function () {
  5411. return this._shadowGenerator;
  5412. };
  5413. Light.prototype.getAbsolutePosition = function () {
  5414. return BABYLON.Vector3.Zero();
  5415. };
  5416. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5417. };
  5418. Light.prototype._getWorldMatrix = function () {
  5419. return BABYLON.Matrix.Identity();
  5420. };
  5421. Light.prototype.canAffectMesh = function (mesh) {
  5422. if (!mesh) {
  5423. return true;
  5424. }
  5425. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5426. return false;
  5427. }
  5428. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5429. return false;
  5430. }
  5431. return true;
  5432. };
  5433. Light.prototype.getWorldMatrix = function () {
  5434. this._currentRenderId = this.getScene().getRenderId();
  5435. var worldMatrix = this._getWorldMatrix();
  5436. if (this.parent && this.parent.getWorldMatrix) {
  5437. if (!this._parentedWorldMatrix) {
  5438. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5439. }
  5440. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5441. return this._parentedWorldMatrix;
  5442. }
  5443. return worldMatrix;
  5444. };
  5445. Light.prototype.dispose = function () {
  5446. if (this._shadowGenerator) {
  5447. this._shadowGenerator.dispose();
  5448. this._shadowGenerator = null;
  5449. }
  5450. // Remove from scene
  5451. var index = this.getScene().lights.indexOf(this);
  5452. this.getScene().lights.splice(index, 1);
  5453. };
  5454. return Light;
  5455. })(BABYLON.Node);
  5456. BABYLON.Light = Light;
  5457. })(BABYLON || (BABYLON = {}));
  5458. //# sourceMappingURL=babylon.light.js.map
  5459. var BABYLON;
  5460. (function (BABYLON) {
  5461. var PointLight = (function (_super) {
  5462. __extends(PointLight, _super);
  5463. function PointLight(name, position, scene) {
  5464. _super.call(this, name, scene);
  5465. this.position = position;
  5466. }
  5467. PointLight.prototype.getAbsolutePosition = function () {
  5468. return this._transformedPosition ? this._transformedPosition : this.position;
  5469. };
  5470. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5471. if (this.parent && this.parent.getWorldMatrix) {
  5472. if (!this._transformedPosition) {
  5473. this._transformedPosition = BABYLON.Vector3.Zero();
  5474. }
  5475. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5476. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5477. return;
  5478. }
  5479. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5480. };
  5481. PointLight.prototype.getShadowGenerator = function () {
  5482. return null;
  5483. };
  5484. PointLight.prototype._getWorldMatrix = function () {
  5485. if (!this._worldMatrix) {
  5486. this._worldMatrix = BABYLON.Matrix.Identity();
  5487. }
  5488. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5489. return this._worldMatrix;
  5490. };
  5491. return PointLight;
  5492. })(BABYLON.Light);
  5493. BABYLON.PointLight = PointLight;
  5494. })(BABYLON || (BABYLON = {}));
  5495. //# sourceMappingURL=babylon.pointLight.js.map
  5496. var BABYLON;
  5497. (function (BABYLON) {
  5498. var SpotLight = (function (_super) {
  5499. __extends(SpotLight, _super);
  5500. function SpotLight(name, position, direction, angle, exponent, scene) {
  5501. _super.call(this, name, scene);
  5502. this.position = position;
  5503. this.direction = direction;
  5504. this.angle = angle;
  5505. this.exponent = exponent;
  5506. }
  5507. SpotLight.prototype.getAbsolutePosition = function () {
  5508. return this.transformedPosition ? this.transformedPosition : this.position;
  5509. };
  5510. SpotLight.prototype.setDirectionToTarget = function (target) {
  5511. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5512. return this.direction;
  5513. };
  5514. SpotLight.prototype.computeTransformedPosition = function () {
  5515. if (this.parent && this.parent.getWorldMatrix) {
  5516. if (!this.transformedPosition) {
  5517. this.transformedPosition = BABYLON.Vector3.Zero();
  5518. }
  5519. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5520. return true;
  5521. }
  5522. return false;
  5523. };
  5524. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5525. var normalizeDirection;
  5526. if (this.parent && this.parent.getWorldMatrix) {
  5527. if (!this._transformedDirection) {
  5528. this._transformedDirection = BABYLON.Vector3.Zero();
  5529. }
  5530. this.computeTransformedPosition();
  5531. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5532. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5533. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5534. }
  5535. else {
  5536. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5537. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5538. }
  5539. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5540. };
  5541. SpotLight.prototype._getWorldMatrix = function () {
  5542. if (!this._worldMatrix) {
  5543. this._worldMatrix = BABYLON.Matrix.Identity();
  5544. }
  5545. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5546. return this._worldMatrix;
  5547. };
  5548. return SpotLight;
  5549. })(BABYLON.Light);
  5550. BABYLON.SpotLight = SpotLight;
  5551. })(BABYLON || (BABYLON = {}));
  5552. //# sourceMappingURL=babylon.spotLight.js.map
  5553. var BABYLON;
  5554. (function (BABYLON) {
  5555. var DirectionalLight = (function (_super) {
  5556. __extends(DirectionalLight, _super);
  5557. function DirectionalLight(name, direction, scene) {
  5558. _super.call(this, name, scene);
  5559. this.direction = direction;
  5560. this.position = direction.scale(-1);
  5561. }
  5562. DirectionalLight.prototype.getAbsolutePosition = function () {
  5563. return this.transformedPosition ? this.transformedPosition : this.position;
  5564. };
  5565. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5566. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5567. return this.direction;
  5568. };
  5569. DirectionalLight.prototype.computeTransformedPosition = function () {
  5570. if (this.parent && this.parent.getWorldMatrix) {
  5571. if (!this.transformedPosition) {
  5572. this.transformedPosition = BABYLON.Vector3.Zero();
  5573. }
  5574. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5575. return true;
  5576. }
  5577. return false;
  5578. };
  5579. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5580. if (this.parent && this.parent.getWorldMatrix) {
  5581. if (!this._transformedDirection) {
  5582. this._transformedDirection = BABYLON.Vector3.Zero();
  5583. }
  5584. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5585. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5586. return;
  5587. }
  5588. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5589. };
  5590. DirectionalLight.prototype._getWorldMatrix = function () {
  5591. if (!this._worldMatrix) {
  5592. this._worldMatrix = BABYLON.Matrix.Identity();
  5593. }
  5594. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5595. return this._worldMatrix;
  5596. };
  5597. return DirectionalLight;
  5598. })(BABYLON.Light);
  5599. BABYLON.DirectionalLight = DirectionalLight;
  5600. })(BABYLON || (BABYLON = {}));
  5601. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5602. (function (BABYLON) {
  5603. var ShadowGenerator = (function () {
  5604. function ShadowGenerator(mapSize, light) {
  5605. var _this = this;
  5606. // Members
  5607. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5608. this._darkness = 0;
  5609. this._transparencyShadow = false;
  5610. this._viewMatrix = BABYLON.Matrix.Zero();
  5611. this._projectionMatrix = BABYLON.Matrix.Zero();
  5612. this._transformMatrix = BABYLON.Matrix.Zero();
  5613. this._worldViewProjection = BABYLON.Matrix.Zero();
  5614. this._light = light;
  5615. this._scene = light.getScene();
  5616. light._shadowGenerator = this;
  5617. // Render target
  5618. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5619. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5620. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5621. this._shadowMap.renderParticles = false;
  5622. // Custom render function
  5623. var renderSubMesh = function (subMesh) {
  5624. var mesh = subMesh.getRenderingMesh();
  5625. var scene = _this._scene;
  5626. var engine = scene.getEngine();
  5627. // Culling
  5628. engine.setState(subMesh.getMaterial().backFaceCulling);
  5629. // Managing instances
  5630. var batch = mesh._getInstancesRenderList(subMesh._id);
  5631. if (batch.mustReturn) {
  5632. return;
  5633. }
  5634. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5635. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5636. engine.enableEffect(_this._effect);
  5637. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5638. var material = subMesh.getMaterial();
  5639. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5640. // Alpha test
  5641. if (material && material.needAlphaTesting()) {
  5642. var alphaTexture = material.getAlphaTestTexture();
  5643. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5644. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5645. }
  5646. // Bones
  5647. if (mesh.useBones) {
  5648. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5649. }
  5650. // Draw
  5651. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  5652. }
  5653. else {
  5654. // Need to reset refresh rate of the shadowMap
  5655. _this._shadowMap.resetRefreshCounter();
  5656. }
  5657. };
  5658. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5659. var index;
  5660. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5661. renderSubMesh(opaqueSubMeshes.data[index]);
  5662. }
  5663. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5664. renderSubMesh(alphaTestSubMeshes.data[index]);
  5665. }
  5666. if (_this._transparencyShadow) {
  5667. for (index = 0; index < transparentSubMeshes.length; index++) {
  5668. renderSubMesh(transparentSubMeshes.data[index]);
  5669. }
  5670. }
  5671. };
  5672. }
  5673. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5674. // Static
  5675. get: function () {
  5676. return ShadowGenerator._FILTER_NONE;
  5677. },
  5678. enumerable: true,
  5679. configurable: true
  5680. });
  5681. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5682. get: function () {
  5683. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5684. },
  5685. enumerable: true,
  5686. configurable: true
  5687. });
  5688. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5689. get: function () {
  5690. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5691. },
  5692. enumerable: true,
  5693. configurable: true
  5694. });
  5695. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5696. get: function () {
  5697. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5698. },
  5699. set: function (value) {
  5700. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5701. },
  5702. enumerable: true,
  5703. configurable: true
  5704. });
  5705. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5706. get: function () {
  5707. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5708. },
  5709. set: function (value) {
  5710. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5711. },
  5712. enumerable: true,
  5713. configurable: true
  5714. });
  5715. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5716. var defines = [];
  5717. if (this.useVarianceShadowMap) {
  5718. defines.push("#define VSM");
  5719. }
  5720. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5721. var mesh = subMesh.getMesh();
  5722. var material = subMesh.getMaterial();
  5723. // Alpha test
  5724. if (material && material.needAlphaTesting()) {
  5725. defines.push("#define ALPHATEST");
  5726. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5727. attribs.push(BABYLON.VertexBuffer.UVKind);
  5728. defines.push("#define UV1");
  5729. }
  5730. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5731. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5732. defines.push("#define UV2");
  5733. }
  5734. }
  5735. // Bones
  5736. if (mesh.useBones) {
  5737. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5738. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5739. defines.push("#define BONES");
  5740. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5741. }
  5742. // Instances
  5743. if (useInstances) {
  5744. defines.push("#define INSTANCES");
  5745. attribs.push("world0");
  5746. attribs.push("world1");
  5747. attribs.push("world2");
  5748. attribs.push("world3");
  5749. }
  5750. // Get correct effect
  5751. var join = defines.join("\n");
  5752. if (this._cachedDefines !== join) {
  5753. this._cachedDefines = join;
  5754. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5755. }
  5756. return this._effect.isReady();
  5757. };
  5758. ShadowGenerator.prototype.getShadowMap = function () {
  5759. return this._shadowMap;
  5760. };
  5761. ShadowGenerator.prototype.getLight = function () {
  5762. return this._light;
  5763. };
  5764. // Methods
  5765. ShadowGenerator.prototype.getTransformMatrix = function () {
  5766. var lightPosition = this._light.position;
  5767. var lightDirection = this._light.direction;
  5768. if (this._light.computeTransformedPosition()) {
  5769. lightPosition = this._light.transformedPosition;
  5770. }
  5771. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5772. this._cachedPosition = lightPosition.clone();
  5773. this._cachedDirection = lightDirection.clone();
  5774. var activeCamera = this._scene.activeCamera;
  5775. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5776. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5777. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5778. }
  5779. return this._transformMatrix;
  5780. };
  5781. ShadowGenerator.prototype.getDarkness = function () {
  5782. return this._darkness;
  5783. };
  5784. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5785. if (darkness >= 1.0)
  5786. this._darkness = 1.0;
  5787. else if (darkness <= 0.0)
  5788. this._darkness = 0.0;
  5789. else
  5790. this._darkness = darkness;
  5791. };
  5792. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5793. this._transparencyShadow = hasShadow;
  5794. };
  5795. ShadowGenerator.prototype.dispose = function () {
  5796. this._shadowMap.dispose();
  5797. };
  5798. ShadowGenerator._FILTER_NONE = 0;
  5799. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5800. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5801. return ShadowGenerator;
  5802. })();
  5803. BABYLON.ShadowGenerator = ShadowGenerator;
  5804. })(BABYLON || (BABYLON = {}));
  5805. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5806. var BABYLON;
  5807. (function (BABYLON) {
  5808. var HemisphericLight = (function (_super) {
  5809. __extends(HemisphericLight, _super);
  5810. function HemisphericLight(name, direction, scene) {
  5811. _super.call(this, name, scene);
  5812. this.direction = direction;
  5813. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5814. }
  5815. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5816. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5817. return this.direction;
  5818. };
  5819. HemisphericLight.prototype.getShadowGenerator = function () {
  5820. return null;
  5821. };
  5822. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5823. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5824. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5825. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5826. };
  5827. HemisphericLight.prototype._getWorldMatrix = function () {
  5828. if (!this._worldMatrix) {
  5829. this._worldMatrix = BABYLON.Matrix.Identity();
  5830. }
  5831. return this._worldMatrix;
  5832. };
  5833. return HemisphericLight;
  5834. })(BABYLON.Light);
  5835. BABYLON.HemisphericLight = HemisphericLight;
  5836. })(BABYLON || (BABYLON = {}));
  5837. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  5838. (function (BABYLON) {
  5839. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5840. if (boxMin.x > sphereCenter.x + sphereRadius)
  5841. return false;
  5842. if (sphereCenter.x - sphereRadius > boxMax.x)
  5843. return false;
  5844. if (boxMin.y > sphereCenter.y + sphereRadius)
  5845. return false;
  5846. if (sphereCenter.y - sphereRadius > boxMax.y)
  5847. return false;
  5848. if (boxMin.z > sphereCenter.z + sphereRadius)
  5849. return false;
  5850. if (sphereCenter.z - sphereRadius > boxMax.z)
  5851. return false;
  5852. return true;
  5853. };
  5854. var getLowestRoot = function (a, b, c, maxR) {
  5855. var determinant = b * b - 4.0 * a * c;
  5856. var result = { root: 0, found: false };
  5857. if (determinant < 0)
  5858. return result;
  5859. var sqrtD = Math.sqrt(determinant);
  5860. var r1 = (-b - sqrtD) / (2.0 * a);
  5861. var r2 = (-b + sqrtD) / (2.0 * a);
  5862. if (r1 > r2) {
  5863. var temp = r2;
  5864. r2 = r1;
  5865. r1 = temp;
  5866. }
  5867. if (r1 > 0 && r1 < maxR) {
  5868. result.root = r1;
  5869. result.found = true;
  5870. return result;
  5871. }
  5872. if (r2 > 0 && r2 < maxR) {
  5873. result.root = r2;
  5874. result.found = true;
  5875. return result;
  5876. }
  5877. return result;
  5878. };
  5879. var Collider = (function () {
  5880. function Collider() {
  5881. this.radius = new BABYLON.Vector3(1, 1, 1);
  5882. this.retry = 0;
  5883. this.basePointWorld = BABYLON.Vector3.Zero();
  5884. this.velocityWorld = BABYLON.Vector3.Zero();
  5885. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5886. this._collisionPoint = BABYLON.Vector3.Zero();
  5887. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5888. this._tempVector = BABYLON.Vector3.Zero();
  5889. this._tempVector2 = BABYLON.Vector3.Zero();
  5890. this._tempVector3 = BABYLON.Vector3.Zero();
  5891. this._tempVector4 = BABYLON.Vector3.Zero();
  5892. this._edge = BABYLON.Vector3.Zero();
  5893. this._baseToVertex = BABYLON.Vector3.Zero();
  5894. this._destinationPoint = BABYLON.Vector3.Zero();
  5895. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5896. this._displacementVector = BABYLON.Vector3.Zero();
  5897. }
  5898. // Methods
  5899. Collider.prototype._initialize = function (source, dir, e) {
  5900. this.velocity = dir;
  5901. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5902. this.basePoint = source;
  5903. source.multiplyToRef(this.radius, this.basePointWorld);
  5904. dir.multiplyToRef(this.radius, this.velocityWorld);
  5905. this.velocityWorldLength = this.velocityWorld.length();
  5906. this.epsilon = e;
  5907. this.collisionFound = false;
  5908. };
  5909. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5910. pa.subtractToRef(point, this._tempVector);
  5911. pb.subtractToRef(point, this._tempVector2);
  5912. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5913. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5914. if (d < 0)
  5915. return false;
  5916. pc.subtractToRef(point, this._tempVector3);
  5917. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5918. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5919. if (d < 0)
  5920. return false;
  5921. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5922. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5923. return d >= 0;
  5924. };
  5925. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5926. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5927. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5928. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5929. return false;
  5930. }
  5931. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5932. return false;
  5933. return true;
  5934. };
  5935. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5936. var t0;
  5937. var embeddedInPlane = false;
  5938. if (!subMesh._trianglePlanes) {
  5939. subMesh._trianglePlanes = [];
  5940. }
  5941. if (!subMesh._trianglePlanes[faceIndex]) {
  5942. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5943. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5944. }
  5945. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5946. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5947. return;
  5948. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5949. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5950. if (normalDotVelocity == 0) {
  5951. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5952. return;
  5953. embeddedInPlane = true;
  5954. t0 = 0;
  5955. }
  5956. else {
  5957. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5958. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5959. if (t0 > t1) {
  5960. var temp = t1;
  5961. t1 = t0;
  5962. t0 = temp;
  5963. }
  5964. if (t0 > 1.0 || t1 < 0.0)
  5965. return;
  5966. if (t0 < 0)
  5967. t0 = 0;
  5968. if (t0 > 1.0)
  5969. t0 = 1.0;
  5970. }
  5971. this._collisionPoint.copyFromFloats(0, 0, 0);
  5972. var found = false;
  5973. var t = 1.0;
  5974. if (!embeddedInPlane) {
  5975. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5976. this.velocity.scaleToRef(t0, this._tempVector);
  5977. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5978. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5979. found = true;
  5980. t = t0;
  5981. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5982. }
  5983. }
  5984. if (!found) {
  5985. var velocitySquaredLength = this.velocity.lengthSquared();
  5986. var a = velocitySquaredLength;
  5987. this.basePoint.subtractToRef(p1, this._tempVector);
  5988. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5989. var c = this._tempVector.lengthSquared() - 1.0;
  5990. var lowestRoot = getLowestRoot(a, b, c, t);
  5991. if (lowestRoot.found) {
  5992. t = lowestRoot.root;
  5993. found = true;
  5994. this._collisionPoint.copyFrom(p1);
  5995. }
  5996. this.basePoint.subtractToRef(p2, this._tempVector);
  5997. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5998. c = this._tempVector.lengthSquared() - 1.0;
  5999. lowestRoot = getLowestRoot(a, b, c, t);
  6000. if (lowestRoot.found) {
  6001. t = lowestRoot.root;
  6002. found = true;
  6003. this._collisionPoint.copyFrom(p2);
  6004. }
  6005. this.basePoint.subtractToRef(p3, this._tempVector);
  6006. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6007. c = this._tempVector.lengthSquared() - 1.0;
  6008. lowestRoot = getLowestRoot(a, b, c, t);
  6009. if (lowestRoot.found) {
  6010. t = lowestRoot.root;
  6011. found = true;
  6012. this._collisionPoint.copyFrom(p3);
  6013. }
  6014. p2.subtractToRef(p1, this._edge);
  6015. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6016. var edgeSquaredLength = this._edge.lengthSquared();
  6017. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6018. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6019. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6020. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6021. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6022. lowestRoot = getLowestRoot(a, b, c, t);
  6023. if (lowestRoot.found) {
  6024. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6025. if (f >= 0.0 && f <= 1.0) {
  6026. t = lowestRoot.root;
  6027. found = true;
  6028. this._edge.scaleInPlace(f);
  6029. p1.addToRef(this._edge, this._collisionPoint);
  6030. }
  6031. }
  6032. p3.subtractToRef(p2, this._edge);
  6033. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6034. edgeSquaredLength = this._edge.lengthSquared();
  6035. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6036. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6037. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6038. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6039. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6040. lowestRoot = getLowestRoot(a, b, c, t);
  6041. if (lowestRoot.found) {
  6042. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6043. if (f >= 0.0 && f <= 1.0) {
  6044. t = lowestRoot.root;
  6045. found = true;
  6046. this._edge.scaleInPlace(f);
  6047. p2.addToRef(this._edge, this._collisionPoint);
  6048. }
  6049. }
  6050. p1.subtractToRef(p3, this._edge);
  6051. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6052. edgeSquaredLength = this._edge.lengthSquared();
  6053. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6054. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6055. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6056. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6057. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6058. lowestRoot = getLowestRoot(a, b, c, t);
  6059. if (lowestRoot.found) {
  6060. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6061. if (f >= 0.0 && f <= 1.0) {
  6062. t = lowestRoot.root;
  6063. found = true;
  6064. this._edge.scaleInPlace(f);
  6065. p3.addToRef(this._edge, this._collisionPoint);
  6066. }
  6067. }
  6068. }
  6069. if (found) {
  6070. var distToCollision = t * this.velocity.length();
  6071. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6072. if (!this.intersectionPoint) {
  6073. this.intersectionPoint = this._collisionPoint.clone();
  6074. }
  6075. else {
  6076. this.intersectionPoint.copyFrom(this._collisionPoint);
  6077. }
  6078. this.nearestDistance = distToCollision;
  6079. this.collisionFound = true;
  6080. this.collidedMesh = subMesh.getMesh();
  6081. }
  6082. }
  6083. };
  6084. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6085. for (var i = indexStart; i < indexEnd; i += 3) {
  6086. var p1 = pts[indices[i] - decal];
  6087. var p2 = pts[indices[i + 1] - decal];
  6088. var p3 = pts[indices[i + 2] - decal];
  6089. this._testTriangle(i, subMesh, p3, p2, p1);
  6090. }
  6091. };
  6092. Collider.prototype._getResponse = function (pos, vel) {
  6093. pos.addToRef(vel, this._destinationPoint);
  6094. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6095. this.basePoint.addToRef(vel, pos);
  6096. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6097. this._slidePlaneNormal.normalize();
  6098. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6099. pos.addInPlace(this._displacementVector);
  6100. this.intersectionPoint.addInPlace(this._displacementVector);
  6101. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6102. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6103. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6104. };
  6105. return Collider;
  6106. })();
  6107. BABYLON.Collider = Collider;
  6108. })(BABYLON || (BABYLON = {}));
  6109. //# sourceMappingURL=babylon.collider.js.map
  6110. var BABYLON;
  6111. (function (BABYLON) {
  6112. var Camera = (function (_super) {
  6113. __extends(Camera, _super);
  6114. function Camera(name, position, scene) {
  6115. _super.call(this, name, scene);
  6116. this.position = position;
  6117. // Members
  6118. this.upVector = BABYLON.Vector3.Up();
  6119. this.orthoLeft = null;
  6120. this.orthoRight = null;
  6121. this.orthoBottom = null;
  6122. this.orthoTop = null;
  6123. this.fov = 0.8;
  6124. this.minZ = 1.0;
  6125. this.maxZ = 10000.0;
  6126. this.inertia = 0.9;
  6127. this.mode = Camera.PERSPECTIVE_CAMERA;
  6128. this.isIntermediate = false;
  6129. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6130. this.subCameras = [];
  6131. this.layerMask = 0xFFFFFFFF;
  6132. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6133. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6134. this._projectionMatrix = new BABYLON.Matrix();
  6135. this._postProcesses = new Array();
  6136. this._postProcessesTakenIndices = [];
  6137. scene.cameras.push(this);
  6138. if (!scene.activeCamera) {
  6139. scene.activeCamera = this;
  6140. }
  6141. }
  6142. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6143. get: function () {
  6144. return Camera._PERSPECTIVE_CAMERA;
  6145. },
  6146. enumerable: true,
  6147. configurable: true
  6148. });
  6149. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6150. get: function () {
  6151. return Camera._ORTHOGRAPHIC_CAMERA;
  6152. },
  6153. enumerable: true,
  6154. configurable: true
  6155. });
  6156. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6157. get: function () {
  6158. return Camera._FOVMODE_VERTICAL_FIXED;
  6159. },
  6160. enumerable: true,
  6161. configurable: true
  6162. });
  6163. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6164. get: function () {
  6165. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6166. },
  6167. enumerable: true,
  6168. configurable: true
  6169. });
  6170. //Cache
  6171. Camera.prototype._initCache = function () {
  6172. _super.prototype._initCache.call(this);
  6173. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6174. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6175. this._cache.mode = undefined;
  6176. this._cache.minZ = undefined;
  6177. this._cache.maxZ = undefined;
  6178. this._cache.fov = undefined;
  6179. this._cache.aspectRatio = undefined;
  6180. this._cache.orthoLeft = undefined;
  6181. this._cache.orthoRight = undefined;
  6182. this._cache.orthoBottom = undefined;
  6183. this._cache.orthoTop = undefined;
  6184. this._cache.renderWidth = undefined;
  6185. this._cache.renderHeight = undefined;
  6186. };
  6187. Camera.prototype._updateCache = function (ignoreParentClass) {
  6188. if (!ignoreParentClass) {
  6189. _super.prototype._updateCache.call(this);
  6190. }
  6191. var engine = this.getEngine();
  6192. this._cache.position.copyFrom(this.position);
  6193. this._cache.upVector.copyFrom(this.upVector);
  6194. this._cache.mode = this.mode;
  6195. this._cache.minZ = this.minZ;
  6196. this._cache.maxZ = this.maxZ;
  6197. this._cache.fov = this.fov;
  6198. this._cache.aspectRatio = engine.getAspectRatio(this);
  6199. this._cache.orthoLeft = this.orthoLeft;
  6200. this._cache.orthoRight = this.orthoRight;
  6201. this._cache.orthoBottom = this.orthoBottom;
  6202. this._cache.orthoTop = this.orthoTop;
  6203. this._cache.renderWidth = engine.getRenderWidth();
  6204. this._cache.renderHeight = engine.getRenderHeight();
  6205. };
  6206. Camera.prototype._updateFromScene = function () {
  6207. this.updateCache();
  6208. this._update();
  6209. };
  6210. // Synchronized
  6211. Camera.prototype._isSynchronized = function () {
  6212. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6213. };
  6214. Camera.prototype._isSynchronizedViewMatrix = function () {
  6215. if (!_super.prototype._isSynchronized.call(this))
  6216. return false;
  6217. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6218. };
  6219. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6220. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6221. if (!check) {
  6222. return false;
  6223. }
  6224. var engine = this.getEngine();
  6225. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6226. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6227. }
  6228. else {
  6229. 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();
  6230. }
  6231. return check;
  6232. };
  6233. // Controls
  6234. Camera.prototype.attachControl = function (element) {
  6235. };
  6236. Camera.prototype.detachControl = function (element) {
  6237. };
  6238. Camera.prototype._update = function () {
  6239. };
  6240. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6241. if (insertAt === void 0) { insertAt = null; }
  6242. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6243. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6244. return 0;
  6245. }
  6246. if (insertAt == null || insertAt < 0) {
  6247. this._postProcesses.push(postProcess);
  6248. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6249. return this._postProcesses.length - 1;
  6250. }
  6251. var add = 0;
  6252. if (this._postProcesses[insertAt]) {
  6253. var start = this._postProcesses.length - 1;
  6254. for (var i = start; i >= insertAt + 1; --i) {
  6255. this._postProcesses[i + 1] = this._postProcesses[i];
  6256. }
  6257. add = 1;
  6258. }
  6259. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6260. if (this._postProcessesTakenIndices[i] < insertAt) {
  6261. continue;
  6262. }
  6263. start = this._postProcessesTakenIndices.length - 1;
  6264. for (var j = start; j >= i; --j) {
  6265. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6266. }
  6267. this._postProcessesTakenIndices[i] = insertAt;
  6268. break;
  6269. }
  6270. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6271. this._postProcessesTakenIndices.push(insertAt);
  6272. }
  6273. var result = insertAt + add;
  6274. this._postProcesses[result] = postProcess;
  6275. return result;
  6276. };
  6277. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6278. if (atIndices === void 0) { atIndices = null; }
  6279. var result = [];
  6280. if (!atIndices) {
  6281. var length = this._postProcesses.length;
  6282. for (var i = 0; i < length; i++) {
  6283. if (this._postProcesses[i] !== postProcess) {
  6284. continue;
  6285. }
  6286. delete this._postProcesses[i];
  6287. var index = this._postProcessesTakenIndices.indexOf(i);
  6288. this._postProcessesTakenIndices.splice(index, 1);
  6289. }
  6290. }
  6291. else {
  6292. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6293. for (i = 0; i < atIndices.length; i++) {
  6294. var foundPostProcess = this._postProcesses[atIndices[i]];
  6295. if (foundPostProcess !== postProcess) {
  6296. result.push(i);
  6297. continue;
  6298. }
  6299. delete this._postProcesses[atIndices[i]];
  6300. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6301. this._postProcessesTakenIndices.splice(index, 1);
  6302. }
  6303. }
  6304. return result;
  6305. };
  6306. Camera.prototype.getWorldMatrix = function () {
  6307. if (!this._worldMatrix) {
  6308. this._worldMatrix = BABYLON.Matrix.Identity();
  6309. }
  6310. var viewMatrix = this.getViewMatrix();
  6311. viewMatrix.invertToRef(this._worldMatrix);
  6312. return this._worldMatrix;
  6313. };
  6314. Camera.prototype._getViewMatrix = function () {
  6315. return BABYLON.Matrix.Identity();
  6316. };
  6317. Camera.prototype.getViewMatrix = function () {
  6318. this._computedViewMatrix = this._computeViewMatrix();
  6319. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6320. return this._computedViewMatrix;
  6321. }
  6322. if (!this._worldMatrix) {
  6323. this._worldMatrix = BABYLON.Matrix.Identity();
  6324. }
  6325. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6326. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6327. this._computedViewMatrix.invert();
  6328. this._currentRenderId = this.getScene().getRenderId();
  6329. return this._computedViewMatrix;
  6330. };
  6331. Camera.prototype._computeViewMatrix = function (force) {
  6332. if (!force && this._isSynchronizedViewMatrix()) {
  6333. return this._computedViewMatrix;
  6334. }
  6335. this._computedViewMatrix = this._getViewMatrix();
  6336. if (!this.parent || !this.parent.getWorldMatrix) {
  6337. this._currentRenderId = this.getScene().getRenderId();
  6338. }
  6339. return this._computedViewMatrix;
  6340. };
  6341. Camera.prototype.getProjectionMatrix = function (force) {
  6342. if (!force && this._isSynchronizedProjectionMatrix()) {
  6343. return this._projectionMatrix;
  6344. }
  6345. var engine = this.getEngine();
  6346. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6347. if (this.minZ <= 0) {
  6348. this.minZ = 0.1;
  6349. }
  6350. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  6351. return this._projectionMatrix;
  6352. }
  6353. var halfWidth = engine.getRenderWidth() / 2.0;
  6354. var halfHeight = engine.getRenderHeight() / 2.0;
  6355. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6356. return this._projectionMatrix;
  6357. };
  6358. Camera.prototype.dispose = function () {
  6359. // Remove from scene
  6360. var index = this.getScene().cameras.indexOf(this);
  6361. this.getScene().cameras.splice(index, 1);
  6362. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6363. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6364. }
  6365. };
  6366. // Statics
  6367. Camera._PERSPECTIVE_CAMERA = 0;
  6368. Camera._ORTHOGRAPHIC_CAMERA = 1;
  6369. Camera._FOVMODE_VERTICAL_FIXED = 0;
  6370. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  6371. return Camera;
  6372. })(BABYLON.Node);
  6373. BABYLON.Camera = Camera;
  6374. })(BABYLON || (BABYLON = {}));
  6375. //# sourceMappingURL=babylon.camera.js.map
  6376. var BABYLON;
  6377. (function (BABYLON) {
  6378. var TargetCamera = (function (_super) {
  6379. __extends(TargetCamera, _super);
  6380. function TargetCamera(name, position, scene) {
  6381. _super.call(this, name, position, scene);
  6382. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6383. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6384. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6385. this.speed = 2.0;
  6386. this.noRotationConstraint = false;
  6387. this.lockedTarget = null;
  6388. this._currentTarget = BABYLON.Vector3.Zero();
  6389. this._viewMatrix = BABYLON.Matrix.Zero();
  6390. this._camMatrix = BABYLON.Matrix.Zero();
  6391. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6392. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6393. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6394. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6395. this._lookAtTemp = BABYLON.Matrix.Zero();
  6396. this._tempMatrix = BABYLON.Matrix.Zero();
  6397. }
  6398. TargetCamera.prototype._getLockedTargetPosition = function () {
  6399. if (!this.lockedTarget) {
  6400. return null;
  6401. }
  6402. return this.lockedTarget.position || this.lockedTarget;
  6403. };
  6404. // Cache
  6405. TargetCamera.prototype._initCache = function () {
  6406. _super.prototype._initCache.call(this);
  6407. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6408. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6409. };
  6410. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6411. if (!ignoreParentClass) {
  6412. _super.prototype._updateCache.call(this);
  6413. }
  6414. var lockedTargetPosition = this._getLockedTargetPosition();
  6415. if (!lockedTargetPosition) {
  6416. this._cache.lockedTarget = null;
  6417. }
  6418. else {
  6419. if (!this._cache.lockedTarget) {
  6420. this._cache.lockedTarget = lockedTargetPosition.clone();
  6421. }
  6422. else {
  6423. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6424. }
  6425. }
  6426. this._cache.rotation.copyFrom(this.rotation);
  6427. };
  6428. // Synchronized
  6429. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6430. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6431. return false;
  6432. }
  6433. var lockedTargetPosition = this._getLockedTargetPosition();
  6434. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6435. };
  6436. // Methods
  6437. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6438. var engine = this.getEngine();
  6439. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6440. };
  6441. // Target
  6442. TargetCamera.prototype.setTarget = function (target) {
  6443. this.upVector.normalize();
  6444. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6445. this._camMatrix.invert();
  6446. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6447. var vDir = target.subtract(this.position);
  6448. if (vDir.x >= 0.0) {
  6449. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6450. }
  6451. else {
  6452. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6453. }
  6454. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6455. if (isNaN(this.rotation.x)) {
  6456. this.rotation.x = 0;
  6457. }
  6458. if (isNaN(this.rotation.y)) {
  6459. this.rotation.y = 0;
  6460. }
  6461. if (isNaN(this.rotation.z)) {
  6462. this.rotation.z = 0;
  6463. }
  6464. };
  6465. TargetCamera.prototype.getTarget = function () {
  6466. return this._currentTarget;
  6467. };
  6468. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6469. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6470. };
  6471. TargetCamera.prototype._updatePosition = function () {
  6472. this.position.addInPlace(this.cameraDirection);
  6473. };
  6474. TargetCamera.prototype._update = function () {
  6475. var needToMove = this._decideIfNeedsToMove();
  6476. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6477. // Move
  6478. if (needToMove) {
  6479. this._updatePosition();
  6480. }
  6481. // Rotate
  6482. if (needToRotate) {
  6483. this.rotation.x += this.cameraRotation.x;
  6484. this.rotation.y += this.cameraRotation.y;
  6485. if (!this.noRotationConstraint) {
  6486. var limit = (Math.PI / 2) * 0.95;
  6487. if (this.rotation.x > limit)
  6488. this.rotation.x = limit;
  6489. if (this.rotation.x < -limit)
  6490. this.rotation.x = -limit;
  6491. }
  6492. }
  6493. // Inertia
  6494. if (needToMove) {
  6495. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6496. this.cameraDirection.x = 0;
  6497. }
  6498. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6499. this.cameraDirection.y = 0;
  6500. }
  6501. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6502. this.cameraDirection.z = 0;
  6503. }
  6504. this.cameraDirection.scaleInPlace(this.inertia);
  6505. }
  6506. if (needToRotate) {
  6507. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6508. this.cameraRotation.x = 0;
  6509. }
  6510. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6511. this.cameraRotation.y = 0;
  6512. }
  6513. this.cameraRotation.scaleInPlace(this.inertia);
  6514. }
  6515. };
  6516. TargetCamera.prototype._getViewMatrix = function () {
  6517. if (!this.lockedTarget) {
  6518. // Compute
  6519. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6520. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6521. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6522. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6523. this._lookAtTemp.invert();
  6524. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6525. }
  6526. else {
  6527. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6528. }
  6529. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6530. // Computing target and final matrix
  6531. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6532. }
  6533. else {
  6534. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6535. }
  6536. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6537. return this._viewMatrix;
  6538. };
  6539. return TargetCamera;
  6540. })(BABYLON.Camera);
  6541. BABYLON.TargetCamera = TargetCamera;
  6542. })(BABYLON || (BABYLON = {}));
  6543. //# sourceMappingURL=babylon.targetCamera.js.map
  6544. var BABYLON;
  6545. (function (BABYLON) {
  6546. var FollowCamera = (function (_super) {
  6547. __extends(FollowCamera, _super);
  6548. function FollowCamera(name, position, scene) {
  6549. _super.call(this, name, position, scene);
  6550. this.radius = 12;
  6551. this.rotationOffset = 0;
  6552. this.heightOffset = 4;
  6553. this.cameraAcceleration = 0.05;
  6554. this.maxCameraSpeed = 20;
  6555. }
  6556. FollowCamera.prototype.getRadians = function (degrees) {
  6557. return degrees * Math.PI / 180;
  6558. };
  6559. FollowCamera.prototype.follow = function (cameraTarget) {
  6560. if (!cameraTarget)
  6561. return;
  6562. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6563. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6564. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6565. var dx = targetX - this.position.x;
  6566. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6567. var dz = (targetZ) - this.position.z;
  6568. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  6569. var vy = dy * this.cameraAcceleration;
  6570. var vz = dz * this.cameraAcceleration * 2;
  6571. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6572. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6573. }
  6574. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6575. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6576. }
  6577. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6578. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6579. }
  6580. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6581. this.setTarget(cameraTarget.position);
  6582. };
  6583. FollowCamera.prototype._update = function () {
  6584. _super.prototype._update.call(this);
  6585. this.follow(this.target);
  6586. };
  6587. return FollowCamera;
  6588. })(BABYLON.TargetCamera);
  6589. BABYLON.FollowCamera = FollowCamera;
  6590. })(BABYLON || (BABYLON = {}));
  6591. //# sourceMappingURL=babylon.followCamera.js.map
  6592. var BABYLON;
  6593. (function (BABYLON) {
  6594. var FreeCamera = (function (_super) {
  6595. __extends(FreeCamera, _super);
  6596. function FreeCamera(name, position, scene) {
  6597. _super.call(this, name, position, scene);
  6598. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6599. this.keysUp = [38];
  6600. this.keysDown = [40];
  6601. this.keysLeft = [37];
  6602. this.keysRight = [39];
  6603. this.checkCollisions = false;
  6604. this.applyGravity = false;
  6605. this.angularSensibility = 2000.0;
  6606. this._keys = [];
  6607. this._collider = new BABYLON.Collider();
  6608. this._needMoveForGravity = true;
  6609. this._oldPosition = BABYLON.Vector3.Zero();
  6610. this._diffPosition = BABYLON.Vector3.Zero();
  6611. this._newPosition = BABYLON.Vector3.Zero();
  6612. }
  6613. // Controls
  6614. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6615. var _this = this;
  6616. var previousPosition;
  6617. var engine = this.getEngine();
  6618. if (this._attachedElement) {
  6619. return;
  6620. }
  6621. this._attachedElement = element;
  6622. if (this._onMouseDown === undefined) {
  6623. this._onMouseDown = function (evt) {
  6624. previousPosition = {
  6625. x: evt.clientX,
  6626. y: evt.clientY
  6627. };
  6628. if (!noPreventDefault) {
  6629. evt.preventDefault();
  6630. }
  6631. };
  6632. this._onMouseUp = function (evt) {
  6633. previousPosition = null;
  6634. if (!noPreventDefault) {
  6635. evt.preventDefault();
  6636. }
  6637. };
  6638. this._onMouseOut = function (evt) {
  6639. previousPosition = null;
  6640. _this._keys = [];
  6641. if (!noPreventDefault) {
  6642. evt.preventDefault();
  6643. }
  6644. };
  6645. this._onMouseMove = function (evt) {
  6646. if (!previousPosition && !engine.isPointerLock) {
  6647. return;
  6648. }
  6649. var offsetX;
  6650. var offsetY;
  6651. if (!engine.isPointerLock) {
  6652. offsetX = evt.clientX - previousPosition.x;
  6653. offsetY = evt.clientY - previousPosition.y;
  6654. }
  6655. else {
  6656. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6657. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6658. }
  6659. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6660. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6661. previousPosition = {
  6662. x: evt.clientX,
  6663. y: evt.clientY
  6664. };
  6665. if (!noPreventDefault) {
  6666. evt.preventDefault();
  6667. }
  6668. };
  6669. this._onKeyDown = function (evt) {
  6670. 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) {
  6671. var index = _this._keys.indexOf(evt.keyCode);
  6672. if (index === -1) {
  6673. _this._keys.push(evt.keyCode);
  6674. }
  6675. if (!noPreventDefault) {
  6676. evt.preventDefault();
  6677. }
  6678. }
  6679. };
  6680. this._onKeyUp = function (evt) {
  6681. 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) {
  6682. var index = _this._keys.indexOf(evt.keyCode);
  6683. if (index >= 0) {
  6684. _this._keys.splice(index, 1);
  6685. }
  6686. if (!noPreventDefault) {
  6687. evt.preventDefault();
  6688. }
  6689. }
  6690. };
  6691. this._onLostFocus = function () {
  6692. _this._keys = [];
  6693. };
  6694. this._reset = function () {
  6695. _this._keys = [];
  6696. previousPosition = null;
  6697. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6698. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6699. };
  6700. }
  6701. element.addEventListener("mousedown", this._onMouseDown, false);
  6702. element.addEventListener("mouseup", this._onMouseUp, false);
  6703. element.addEventListener("mouseout", this._onMouseOut, false);
  6704. element.addEventListener("mousemove", this._onMouseMove, false);
  6705. BABYLON.Tools.RegisterTopRootEvents([
  6706. { name: "keydown", handler: this._onKeyDown },
  6707. { name: "keyup", handler: this._onKeyUp },
  6708. { name: "blur", handler: this._onLostFocus }
  6709. ]);
  6710. };
  6711. FreeCamera.prototype.detachControl = function (element) {
  6712. if (this._attachedElement != element) {
  6713. return;
  6714. }
  6715. element.removeEventListener("mousedown", this._onMouseDown);
  6716. element.removeEventListener("mouseup", this._onMouseUp);
  6717. element.removeEventListener("mouseout", this._onMouseOut);
  6718. element.removeEventListener("mousemove", this._onMouseMove);
  6719. BABYLON.Tools.UnregisterTopRootEvents([
  6720. { name: "keydown", handler: this._onKeyDown },
  6721. { name: "keyup", handler: this._onKeyUp },
  6722. { name: "blur", handler: this._onLostFocus }
  6723. ]);
  6724. this._attachedElement = null;
  6725. if (this._reset) {
  6726. this._reset();
  6727. }
  6728. };
  6729. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6730. var globalPosition;
  6731. if (this.parent) {
  6732. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6733. }
  6734. else {
  6735. globalPosition = this.position;
  6736. }
  6737. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6738. this._collider.radius = this.ellipsoid;
  6739. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6740. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6741. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6742. this.position.addInPlace(this._diffPosition);
  6743. if (this.onCollide) {
  6744. this.onCollide(this._collider.collidedMesh);
  6745. }
  6746. }
  6747. };
  6748. FreeCamera.prototype._checkInputs = function () {
  6749. if (!this._localDirection) {
  6750. this._localDirection = BABYLON.Vector3.Zero();
  6751. this._transformedDirection = BABYLON.Vector3.Zero();
  6752. }
  6753. for (var index = 0; index < this._keys.length; index++) {
  6754. var keyCode = this._keys[index];
  6755. var speed = this._computeLocalCameraSpeed();
  6756. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6757. this._localDirection.copyFromFloats(-speed, 0, 0);
  6758. }
  6759. else if (this.keysUp.indexOf(keyCode) !== -1) {
  6760. this._localDirection.copyFromFloats(0, 0, speed);
  6761. }
  6762. else if (this.keysRight.indexOf(keyCode) !== -1) {
  6763. this._localDirection.copyFromFloats(speed, 0, 0);
  6764. }
  6765. else if (this.keysDown.indexOf(keyCode) !== -1) {
  6766. this._localDirection.copyFromFloats(0, 0, -speed);
  6767. }
  6768. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6769. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6770. this.cameraDirection.addInPlace(this._transformedDirection);
  6771. }
  6772. };
  6773. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6774. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6775. };
  6776. FreeCamera.prototype._updatePosition = function () {
  6777. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6778. this._collideWithWorld(this.cameraDirection);
  6779. if (this.applyGravity) {
  6780. var oldPosition = this.position;
  6781. this._collideWithWorld(this.getScene().gravity);
  6782. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6783. }
  6784. }
  6785. else {
  6786. this.position.addInPlace(this.cameraDirection);
  6787. }
  6788. };
  6789. FreeCamera.prototype._update = function () {
  6790. this._checkInputs();
  6791. _super.prototype._update.call(this);
  6792. };
  6793. return FreeCamera;
  6794. })(BABYLON.TargetCamera);
  6795. BABYLON.FreeCamera = FreeCamera;
  6796. })(BABYLON || (BABYLON = {}));
  6797. //# sourceMappingURL=babylon.freeCamera.js.map
  6798. var BABYLON;
  6799. (function (BABYLON) {
  6800. // We're mainly based on the logic defined into the FreeCamera code
  6801. var TouchCamera = (function (_super) {
  6802. __extends(TouchCamera, _super);
  6803. function TouchCamera(name, position, scene) {
  6804. _super.call(this, name, position, scene);
  6805. this._offsetX = null;
  6806. this._offsetY = null;
  6807. this._pointerCount = 0;
  6808. this._pointerPressed = [];
  6809. this.angularSensibility = 200000.0;
  6810. this.moveSensibility = 500.0;
  6811. }
  6812. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6813. var _this = this;
  6814. var previousPosition;
  6815. if (this._attachedCanvas) {
  6816. return;
  6817. }
  6818. this._attachedCanvas = canvas;
  6819. if (this._onPointerDown === undefined) {
  6820. this._onPointerDown = function (evt) {
  6821. if (!noPreventDefault) {
  6822. evt.preventDefault();
  6823. }
  6824. _this._pointerPressed.push(evt.pointerId);
  6825. if (_this._pointerPressed.length !== 1) {
  6826. return;
  6827. }
  6828. previousPosition = {
  6829. x: evt.clientX,
  6830. y: evt.clientY
  6831. };
  6832. };
  6833. this._onPointerUp = function (evt) {
  6834. if (!noPreventDefault) {
  6835. evt.preventDefault();
  6836. }
  6837. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6838. if (index === -1) {
  6839. return;
  6840. }
  6841. _this._pointerPressed.splice(index, 1);
  6842. if (index != 0) {
  6843. return;
  6844. }
  6845. previousPosition = null;
  6846. _this._offsetX = null;
  6847. _this._offsetY = null;
  6848. };
  6849. this._onPointerMove = function (evt) {
  6850. if (!noPreventDefault) {
  6851. evt.preventDefault();
  6852. }
  6853. if (!previousPosition) {
  6854. return;
  6855. }
  6856. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6857. if (index != 0) {
  6858. return;
  6859. }
  6860. _this._offsetX = evt.clientX - previousPosition.x;
  6861. _this._offsetY = -(evt.clientY - previousPosition.y);
  6862. };
  6863. this._onLostFocus = function () {
  6864. _this._offsetX = null;
  6865. _this._offsetY = null;
  6866. };
  6867. }
  6868. canvas.addEventListener("pointerdown", this._onPointerDown);
  6869. canvas.addEventListener("pointerup", this._onPointerUp);
  6870. canvas.addEventListener("pointerout", this._onPointerUp);
  6871. canvas.addEventListener("pointermove", this._onPointerMove);
  6872. BABYLON.Tools.RegisterTopRootEvents([
  6873. { name: "blur", handler: this._onLostFocus }
  6874. ]);
  6875. };
  6876. TouchCamera.prototype.detachControl = function (canvas) {
  6877. if (this._attachedCanvas != canvas) {
  6878. return;
  6879. }
  6880. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6881. canvas.removeEventListener("pointerup", this._onPointerUp);
  6882. canvas.removeEventListener("pointerout", this._onPointerUp);
  6883. canvas.removeEventListener("pointermove", this._onPointerMove);
  6884. BABYLON.Tools.UnregisterTopRootEvents([
  6885. { name: "blur", handler: this._onLostFocus }
  6886. ]);
  6887. this._attachedCanvas = null;
  6888. };
  6889. TouchCamera.prototype._checkInputs = function () {
  6890. if (!this._offsetX) {
  6891. return;
  6892. }
  6893. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6894. if (this._pointerPressed.length > 1) {
  6895. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6896. }
  6897. else {
  6898. var speed = this._computeLocalCameraSpeed();
  6899. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6900. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6901. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6902. }
  6903. };
  6904. return TouchCamera;
  6905. })(BABYLON.FreeCamera);
  6906. BABYLON.TouchCamera = TouchCamera;
  6907. })(BABYLON || (BABYLON = {}));
  6908. //# sourceMappingURL=babylon.touchCamera.js.map
  6909. var BABYLON;
  6910. (function (BABYLON) {
  6911. // We're mainly based on the logic defined into the FreeCamera code
  6912. var DeviceOrientationCamera = (function (_super) {
  6913. __extends(DeviceOrientationCamera, _super);
  6914. function DeviceOrientationCamera(name, position, scene) {
  6915. var _this = this;
  6916. _super.call(this, name, position, scene);
  6917. this._offsetX = null;
  6918. this._offsetY = null;
  6919. this._orientationGamma = 0;
  6920. this._orientationBeta = 0;
  6921. this._initialOrientationGamma = 0;
  6922. this._initialOrientationBeta = 0;
  6923. this.angularSensibility = 10000.0;
  6924. this.moveSensibility = 50.0;
  6925. window.addEventListener("resize", function () {
  6926. _this._initialOrientationGamma = null;
  6927. }, false);
  6928. }
  6929. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6930. var _this = this;
  6931. if (this._attachedCanvas) {
  6932. return;
  6933. }
  6934. this._attachedCanvas = canvas;
  6935. if (!this._orientationChanged) {
  6936. this._orientationChanged = function (evt) {
  6937. if (!_this._initialOrientationGamma) {
  6938. _this._initialOrientationGamma = evt.gamma;
  6939. _this._initialOrientationBeta = evt.beta;
  6940. }
  6941. _this._orientationGamma = evt.gamma;
  6942. _this._orientationBeta = evt.beta;
  6943. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6944. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6945. };
  6946. }
  6947. window.addEventListener("deviceorientation", this._orientationChanged);
  6948. };
  6949. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6950. if (this._attachedCanvas != canvas) {
  6951. return;
  6952. }
  6953. window.removeEventListener("deviceorientation", this._orientationChanged);
  6954. this._attachedCanvas = null;
  6955. this._orientationGamma = 0;
  6956. this._orientationBeta = 0;
  6957. this._initialOrientationGamma = 0;
  6958. this._initialOrientationBeta = 0;
  6959. };
  6960. DeviceOrientationCamera.prototype._checkInputs = function () {
  6961. if (!this._offsetX) {
  6962. return;
  6963. }
  6964. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6965. var speed = this._computeLocalCameraSpeed();
  6966. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6967. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6968. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6969. };
  6970. return DeviceOrientationCamera;
  6971. })(BABYLON.FreeCamera);
  6972. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6973. })(BABYLON || (BABYLON = {}));
  6974. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  6975. var BABYLON;
  6976. (function (BABYLON) {
  6977. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6978. var ArcRotateCamera = (function (_super) {
  6979. __extends(ArcRotateCamera, _super);
  6980. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6981. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6982. this.alpha = alpha;
  6983. this.beta = beta;
  6984. this.radius = radius;
  6985. this.target = target;
  6986. this.inertialAlphaOffset = 0;
  6987. this.inertialBetaOffset = 0;
  6988. this.inertialRadiusOffset = 0;
  6989. this.lowerAlphaLimit = null;
  6990. this.upperAlphaLimit = null;
  6991. this.lowerBetaLimit = 0.01;
  6992. this.upperBetaLimit = Math.PI;
  6993. this.lowerRadiusLimit = null;
  6994. this.upperRadiusLimit = null;
  6995. this.angularSensibility = 1000.0;
  6996. this.wheelPrecision = 3.0;
  6997. this.keysUp = [38];
  6998. this.keysDown = [40];
  6999. this.keysLeft = [37];
  7000. this.keysRight = [39];
  7001. this.zoomOnFactor = 1;
  7002. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7003. this._keys = [];
  7004. this._viewMatrix = new BABYLON.Matrix();
  7005. this.checkCollisions = false;
  7006. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7007. this._collider = new BABYLON.Collider();
  7008. this._previousPosition = BABYLON.Vector3.Zero();
  7009. this._collisionVelocity = BABYLON.Vector3.Zero();
  7010. this._newPosition = BABYLON.Vector3.Zero();
  7011. // Pinch
  7012. // value for pinch step scaling
  7013. // set to 20 by default
  7014. this.pinchPrecision = 20;
  7015. this.getViewMatrix();
  7016. }
  7017. ArcRotateCamera.prototype._getTargetPosition = function () {
  7018. return this.target.position || this.target;
  7019. };
  7020. // Cache
  7021. ArcRotateCamera.prototype._initCache = function () {
  7022. _super.prototype._initCache.call(this);
  7023. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7024. this._cache.alpha = undefined;
  7025. this._cache.beta = undefined;
  7026. this._cache.radius = undefined;
  7027. this._cache.targetScreenOffset = undefined;
  7028. };
  7029. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7030. if (!ignoreParentClass) {
  7031. _super.prototype._updateCache.call(this);
  7032. }
  7033. this._cache.target.copyFrom(this._getTargetPosition());
  7034. this._cache.alpha = this.alpha;
  7035. this._cache.beta = this.beta;
  7036. this._cache.radius = this.radius;
  7037. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7038. };
  7039. // Synchronized
  7040. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7041. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7042. return false;
  7043. 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);
  7044. };
  7045. // Methods
  7046. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7047. var _this = this;
  7048. var previousPosition;
  7049. var pointerId;
  7050. // to know if pinch started
  7051. var pinchStarted = false;
  7052. // two pinch point on X
  7053. // that will use for find if user action is pinch open or pinch close
  7054. var pinchPointX1, pinchPointX2;
  7055. if (this._attachedElement) {
  7056. return;
  7057. }
  7058. this._attachedElement = element;
  7059. var engine = this.getEngine();
  7060. if (this._onPointerDown === undefined) {
  7061. this._onPointerDown = function (evt) {
  7062. if (pointerId) {
  7063. return;
  7064. }
  7065. pointerId = evt.pointerId;
  7066. previousPosition = {
  7067. x: evt.clientX,
  7068. y: evt.clientY
  7069. };
  7070. if (!noPreventDefault) {
  7071. evt.preventDefault();
  7072. }
  7073. };
  7074. this._onPointerUp = function (evt) {
  7075. previousPosition = null;
  7076. pointerId = null;
  7077. if (!noPreventDefault) {
  7078. evt.preventDefault();
  7079. }
  7080. };
  7081. this._onPointerMove = function (evt) {
  7082. if (!previousPosition) {
  7083. return;
  7084. }
  7085. if (pointerId !== evt.pointerId) {
  7086. return;
  7087. }
  7088. // return pinch is started
  7089. if (pinchStarted) {
  7090. return;
  7091. }
  7092. var offsetX = evt.clientX - previousPosition.x;
  7093. var offsetY = evt.clientY - previousPosition.y;
  7094. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7095. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7096. previousPosition = {
  7097. x: evt.clientX,
  7098. y: evt.clientY
  7099. };
  7100. if (!noPreventDefault) {
  7101. evt.preventDefault();
  7102. }
  7103. };
  7104. this._onMouseMove = function (evt) {
  7105. if (!engine.isPointerLock) {
  7106. return;
  7107. }
  7108. // return pinch is started
  7109. if (pinchStarted) {
  7110. return;
  7111. }
  7112. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7113. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7114. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7115. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7116. if (!noPreventDefault) {
  7117. evt.preventDefault();
  7118. }
  7119. };
  7120. this._wheel = function (event) {
  7121. var delta = 0;
  7122. if (event.wheelDelta) {
  7123. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7124. }
  7125. else if (event.detail) {
  7126. delta = -event.detail / _this.wheelPrecision;
  7127. }
  7128. if (delta)
  7129. _this.inertialRadiusOffset += delta;
  7130. if (event.preventDefault) {
  7131. if (!noPreventDefault) {
  7132. event.preventDefault();
  7133. }
  7134. }
  7135. };
  7136. this._onKeyDown = function (evt) {
  7137. 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) {
  7138. var index = _this._keys.indexOf(evt.keyCode);
  7139. if (index === -1) {
  7140. _this._keys.push(evt.keyCode);
  7141. }
  7142. if (evt.preventDefault) {
  7143. if (!noPreventDefault) {
  7144. evt.preventDefault();
  7145. }
  7146. }
  7147. }
  7148. };
  7149. this._onKeyUp = function (evt) {
  7150. 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) {
  7151. var index = _this._keys.indexOf(evt.keyCode);
  7152. if (index >= 0) {
  7153. _this._keys.splice(index, 1);
  7154. }
  7155. if (evt.preventDefault) {
  7156. if (!noPreventDefault) {
  7157. evt.preventDefault();
  7158. }
  7159. }
  7160. }
  7161. };
  7162. this._onLostFocus = function () {
  7163. _this._keys = [];
  7164. pointerId = null;
  7165. };
  7166. this._onGestureStart = function (e) {
  7167. if (window.MSGesture === undefined) {
  7168. return;
  7169. }
  7170. if (!_this._MSGestureHandler) {
  7171. _this._MSGestureHandler = new MSGesture();
  7172. _this._MSGestureHandler.target = element;
  7173. }
  7174. _this._MSGestureHandler.addPointer(e.pointerId);
  7175. };
  7176. this._onGesture = function (e) {
  7177. _this.radius *= e.scale;
  7178. if (e.preventDefault) {
  7179. if (!noPreventDefault) {
  7180. e.stopPropagation();
  7181. e.preventDefault();
  7182. }
  7183. }
  7184. };
  7185. this._reset = function () {
  7186. _this._keys = [];
  7187. _this.inertialAlphaOffset = 0;
  7188. _this.inertialBetaOffset = 0;
  7189. _this.inertialRadiusOffset = 0;
  7190. previousPosition = null;
  7191. pointerId = null;
  7192. };
  7193. this._touchStart = function (event) {
  7194. if (event.touches.length === 2) {
  7195. //-- start pinch if two fingers on the screen
  7196. pinchStarted = true;
  7197. _this._pinchStart(event);
  7198. }
  7199. };
  7200. this._touchMove = function (event) {
  7201. if (pinchStarted) {
  7202. //-- make scaling
  7203. _this._pinchMove(event);
  7204. }
  7205. };
  7206. this._touchEnd = function (event) {
  7207. if (pinchStarted) {
  7208. //-- end of pinch
  7209. _this._pinchEnd(event);
  7210. }
  7211. };
  7212. this._pinchStart = function (event) {
  7213. // save origin touch point
  7214. pinchPointX1 = event.touches[0].clientX;
  7215. pinchPointX2 = event.touches[1].clientX;
  7216. // block the camera
  7217. // if not it rotate around target during pinch
  7218. pinchStarted = true;
  7219. };
  7220. this._pinchMove = function (event) {
  7221. // variable for new camera's radius
  7222. var delta = 0;
  7223. // variables to know if pinch open or pinch close
  7224. var direction = 1;
  7225. var distanceXOrigine, distanceXNow;
  7226. if (event.touches.length !== 2)
  7227. return;
  7228. // calculate absolute distances of the two fingers
  7229. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7230. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7231. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7232. if (distanceXNow < distanceXOrigine) {
  7233. direction = -1;
  7234. }
  7235. // calculate new radius
  7236. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7237. // set new radius
  7238. _this.inertialRadiusOffset -= delta;
  7239. // save origin touch point
  7240. pinchPointX1 = event.touches[0].clientX;
  7241. pinchPointX2 = event.touches[1].clientX;
  7242. };
  7243. this._pinchEnd = function (event) {
  7244. // cancel pinch and deblock camera rotation
  7245. pinchStarted = false;
  7246. };
  7247. }
  7248. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7249. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7250. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7251. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7252. element.addEventListener("mousemove", this._onMouseMove, false);
  7253. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7254. element.addEventListener("MSGestureChange", this._onGesture, false);
  7255. element.addEventListener('mousewheel', this._wheel, false);
  7256. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7257. // pinch
  7258. element.addEventListener('touchstart', this._touchStart, false);
  7259. element.addEventListener('touchmove', this._touchMove, false);
  7260. element.addEventListener('touchend', this._touchEnd, false);
  7261. BABYLON.Tools.RegisterTopRootEvents([
  7262. { name: "keydown", handler: this._onKeyDown },
  7263. { name: "keyup", handler: this._onKeyUp },
  7264. { name: "blur", handler: this._onLostFocus }
  7265. ]);
  7266. };
  7267. ArcRotateCamera.prototype.detachControl = function (element) {
  7268. if (this._attachedElement != element) {
  7269. return;
  7270. }
  7271. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7272. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7273. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7274. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7275. element.removeEventListener("mousemove", this._onMouseMove);
  7276. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7277. element.removeEventListener("MSGestureChange", this._onGesture);
  7278. element.removeEventListener('mousewheel', this._wheel);
  7279. element.removeEventListener('DOMMouseScroll', this._wheel);
  7280. // pinch
  7281. element.removeEventListener('touchstart', this._touchStart);
  7282. element.removeEventListener('touchmove', this._touchMove);
  7283. element.removeEventListener('touchend', this._touchEnd);
  7284. BABYLON.Tools.UnregisterTopRootEvents([
  7285. { name: "keydown", handler: this._onKeyDown },
  7286. { name: "keyup", handler: this._onKeyUp },
  7287. { name: "blur", handler: this._onLostFocus }
  7288. ]);
  7289. this._MSGestureHandler = null;
  7290. this._attachedElement = null;
  7291. if (this._reset) {
  7292. this._reset();
  7293. }
  7294. };
  7295. ArcRotateCamera.prototype._update = function () {
  7296. for (var index = 0; index < this._keys.length; index++) {
  7297. var keyCode = this._keys[index];
  7298. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7299. this.inertialAlphaOffset -= 0.01;
  7300. }
  7301. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7302. this.inertialBetaOffset -= 0.01;
  7303. }
  7304. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7305. this.inertialAlphaOffset += 0.01;
  7306. }
  7307. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7308. this.inertialBetaOffset += 0.01;
  7309. }
  7310. }
  7311. // Inertia
  7312. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7313. this.alpha += this.inertialAlphaOffset;
  7314. this.beta += this.inertialBetaOffset;
  7315. this.radius -= this.inertialRadiusOffset;
  7316. this.inertialAlphaOffset *= this.inertia;
  7317. this.inertialBetaOffset *= this.inertia;
  7318. this.inertialRadiusOffset *= this.inertia;
  7319. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7320. this.inertialAlphaOffset = 0;
  7321. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7322. this.inertialBetaOffset = 0;
  7323. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7324. this.inertialRadiusOffset = 0;
  7325. }
  7326. // Limits
  7327. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7328. this.alpha = this.lowerAlphaLimit;
  7329. }
  7330. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7331. this.alpha = this.upperAlphaLimit;
  7332. }
  7333. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7334. this.beta = this.lowerBetaLimit;
  7335. }
  7336. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7337. this.beta = this.upperBetaLimit;
  7338. }
  7339. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7340. this.radius = this.lowerRadiusLimit;
  7341. }
  7342. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7343. this.radius = this.upperRadiusLimit;
  7344. }
  7345. };
  7346. ArcRotateCamera.prototype.setPosition = function (position) {
  7347. var radiusv3 = position.subtract(this._getTargetPosition());
  7348. this.radius = radiusv3.length();
  7349. // Alpha
  7350. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7351. if (radiusv3.z < 0) {
  7352. this.alpha = 2 * Math.PI - this.alpha;
  7353. }
  7354. // Beta
  7355. this.beta = Math.acos(radiusv3.y / this.radius);
  7356. };
  7357. ArcRotateCamera.prototype._getViewMatrix = function () {
  7358. // Compute
  7359. var cosa = Math.cos(this.alpha);
  7360. var sina = Math.sin(this.alpha);
  7361. var cosb = Math.cos(this.beta);
  7362. var sinb = Math.sin(this.beta);
  7363. var target = this._getTargetPosition();
  7364. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7365. if (this.checkCollisions) {
  7366. this._collider.radius = this.collisionRadius;
  7367. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7368. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7369. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7370. this.position.copyFrom(this._previousPosition);
  7371. this.alpha = this._previousAlpha;
  7372. this.beta = this._previousBeta;
  7373. this.radius = this._previousRadius;
  7374. if (this.onCollide) {
  7375. this.onCollide(this._collider.collidedMesh);
  7376. }
  7377. }
  7378. }
  7379. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7380. this._previousAlpha = this.alpha;
  7381. this._previousBeta = this.beta;
  7382. this._previousRadius = this.radius;
  7383. this._previousPosition.copyFrom(this.position);
  7384. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7385. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7386. return this._viewMatrix;
  7387. };
  7388. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7389. meshes = meshes || this.getScene().meshes;
  7390. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7391. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7392. this.radius = distance * this.zoomOnFactor;
  7393. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7394. };
  7395. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7396. var meshesOrMinMaxVector;
  7397. var distance;
  7398. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7399. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7400. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7401. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7402. }
  7403. else {
  7404. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7405. distance = meshesOrMinMaxVectorAndDistance.distance;
  7406. }
  7407. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7408. this.maxZ = distance * 2;
  7409. };
  7410. return ArcRotateCamera;
  7411. })(BABYLON.Camera);
  7412. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7413. })(BABYLON || (BABYLON = {}));
  7414. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7415. (function (BABYLON) {
  7416. /**
  7417. * Represents a scene to be rendered by the engine.
  7418. * @see http://doc.babylonjs.com/page.php?p=21911
  7419. */
  7420. var Scene = (function () {
  7421. /**
  7422. * @constructor
  7423. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7424. */
  7425. function Scene(engine) {
  7426. // Members
  7427. this.autoClear = true;
  7428. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7429. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7430. this.forceWireframe = false;
  7431. this.forcePointsCloud = false;
  7432. this.forceShowBoundingBoxes = false;
  7433. this.animationsEnabled = true;
  7434. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  7435. // Fog
  7436. /**
  7437. * is fog enabled on this scene.
  7438. * @type {boolean}
  7439. */
  7440. this.fogEnabled = true;
  7441. this.fogMode = Scene.FOGMODE_NONE;
  7442. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7443. this.fogDensity = 0.1;
  7444. this.fogStart = 0;
  7445. this.fogEnd = 1000.0;
  7446. // Lights
  7447. /**
  7448. * is shadow enabled on this scene.
  7449. * @type {boolean}
  7450. */
  7451. this.shadowsEnabled = true;
  7452. /**
  7453. * is light enabled on this scene.
  7454. * @type {boolean}
  7455. */
  7456. this.lightsEnabled = true;
  7457. /**
  7458. * All of the lights added to this scene.
  7459. * @see BABYLON.Light
  7460. * @type {BABYLON.Light[]}
  7461. */
  7462. this.lights = new Array();
  7463. // Cameras
  7464. /**
  7465. * All of the cameras added to this scene.
  7466. * @see BABYLON.Camera
  7467. * @type {BABYLON.Camera[]}
  7468. */
  7469. this.cameras = new Array();
  7470. this.activeCameras = new Array();
  7471. // Meshes
  7472. /**
  7473. * All of the (abstract) meshes added to this scene.
  7474. * @see BABYLON.AbstractMesh
  7475. * @type {BABYLON.AbstractMesh[]}
  7476. */
  7477. this.meshes = new Array();
  7478. // Geometries
  7479. this._geometries = new Array();
  7480. this.materials = new Array();
  7481. this.multiMaterials = new Array();
  7482. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7483. // Textures
  7484. this.texturesEnabled = true;
  7485. this.textures = new Array();
  7486. // Particles
  7487. this.particlesEnabled = true;
  7488. this.particleSystems = new Array();
  7489. // Sprites
  7490. this.spriteManagers = new Array();
  7491. // Layers
  7492. this.layers = new Array();
  7493. // Skeletons
  7494. this.skeletonsEnabled = true;
  7495. this.skeletons = new Array();
  7496. // Lens flares
  7497. this.lensFlaresEnabled = true;
  7498. this.lensFlareSystems = new Array();
  7499. // Collisions
  7500. this.collisionsEnabled = true;
  7501. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7502. // Postprocesses
  7503. this.postProcessesEnabled = true;
  7504. // Customs render targets
  7505. this.renderTargetsEnabled = true;
  7506. this.customRenderTargets = new Array();
  7507. // Imported meshes
  7508. this.importedMeshesFiles = new Array();
  7509. this._actionManagers = new Array();
  7510. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7511. // Procedural textures
  7512. this.proceduralTexturesEnabled = true;
  7513. this._proceduralTextures = new Array();
  7514. this.soundTracks = new Array();
  7515. this._totalVertices = 0;
  7516. this._activeVertices = 0;
  7517. this._activeParticles = 0;
  7518. this._lastFrameDuration = 0;
  7519. this._evaluateActiveMeshesDuration = 0;
  7520. this._renderTargetsDuration = 0;
  7521. this._particlesDuration = 0;
  7522. this._renderDuration = 0;
  7523. this._spritesDuration = 0;
  7524. this._animationRatio = 0;
  7525. this._renderId = 0;
  7526. this._executeWhenReadyTimeoutId = -1;
  7527. this._toBeDisposed = new BABYLON.SmartArray(256);
  7528. this._onReadyCallbacks = new Array();
  7529. this._pendingData = []; //ANY
  7530. this._onBeforeRenderCallbacks = new Array();
  7531. this._onAfterRenderCallbacks = new Array();
  7532. this._activeMeshes = new BABYLON.SmartArray(256);
  7533. this._processedMaterials = new BABYLON.SmartArray(256);
  7534. this._renderTargets = new BABYLON.SmartArray(256);
  7535. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7536. this._activeSkeletons = new BABYLON.SmartArray(32);
  7537. this._activeBones = 0;
  7538. this._activeAnimatables = new Array();
  7539. this._transformMatrix = BABYLON.Matrix.Zero();
  7540. this._scaledPosition = BABYLON.Vector3.Zero();
  7541. this._scaledVelocity = BABYLON.Vector3.Zero();
  7542. this._engine = engine;
  7543. engine.scenes.push(this);
  7544. this._renderingManager = new BABYLON.RenderingManager(this);
  7545. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7546. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7547. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7548. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7549. this.attachControl();
  7550. this._debugLayer = new BABYLON.DebugLayer(this);
  7551. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7552. }
  7553. Object.defineProperty(Scene, "FOGMODE_NONE", {
  7554. get: function () {
  7555. return Scene._FOGMODE_NONE;
  7556. },
  7557. enumerable: true,
  7558. configurable: true
  7559. });
  7560. Object.defineProperty(Scene, "FOGMODE_EXP", {
  7561. get: function () {
  7562. return Scene._FOGMODE_EXP;
  7563. },
  7564. enumerable: true,
  7565. configurable: true
  7566. });
  7567. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  7568. get: function () {
  7569. return Scene._FOGMODE_EXP2;
  7570. },
  7571. enumerable: true,
  7572. configurable: true
  7573. });
  7574. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  7575. get: function () {
  7576. return Scene._FOGMODE_LINEAR;
  7577. },
  7578. enumerable: true,
  7579. configurable: true
  7580. });
  7581. Object.defineProperty(Scene.prototype, "debugLayer", {
  7582. // Properties
  7583. get: function () {
  7584. return this._debugLayer;
  7585. },
  7586. enumerable: true,
  7587. configurable: true
  7588. });
  7589. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7590. /**
  7591. * The mesh that is currently under the pointer.
  7592. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  7593. */
  7594. get: function () {
  7595. return this._meshUnderPointer;
  7596. },
  7597. enumerable: true,
  7598. configurable: true
  7599. });
  7600. Object.defineProperty(Scene.prototype, "pointerX", {
  7601. /**
  7602. * Current on-screen X position of the pointer
  7603. * @return {number} X position of the pointer
  7604. */
  7605. get: function () {
  7606. return this._pointerX;
  7607. },
  7608. enumerable: true,
  7609. configurable: true
  7610. });
  7611. Object.defineProperty(Scene.prototype, "pointerY", {
  7612. /**
  7613. * Current on-screen Y position of the pointer
  7614. * @return {number} Y position of the pointer
  7615. */
  7616. get: function () {
  7617. return this._pointerY;
  7618. },
  7619. enumerable: true,
  7620. configurable: true
  7621. });
  7622. Scene.prototype.getCachedMaterial = function () {
  7623. return this._cachedMaterial;
  7624. };
  7625. Scene.prototype.getBoundingBoxRenderer = function () {
  7626. return this._boundingBoxRenderer;
  7627. };
  7628. Scene.prototype.getOutlineRenderer = function () {
  7629. return this._outlineRenderer;
  7630. };
  7631. Scene.prototype.getEngine = function () {
  7632. return this._engine;
  7633. };
  7634. Scene.prototype.getTotalVertices = function () {
  7635. return this._totalVertices;
  7636. };
  7637. Scene.prototype.getActiveVertices = function () {
  7638. return this._activeVertices;
  7639. };
  7640. Scene.prototype.getActiveParticles = function () {
  7641. return this._activeParticles;
  7642. };
  7643. Scene.prototype.getActiveBones = function () {
  7644. return this._activeBones;
  7645. };
  7646. // Stats
  7647. Scene.prototype.getLastFrameDuration = function () {
  7648. return this._lastFrameDuration;
  7649. };
  7650. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7651. return this._evaluateActiveMeshesDuration;
  7652. };
  7653. Scene.prototype.getActiveMeshes = function () {
  7654. return this._activeMeshes;
  7655. };
  7656. Scene.prototype.getRenderTargetsDuration = function () {
  7657. return this._renderTargetsDuration;
  7658. };
  7659. Scene.prototype.getRenderDuration = function () {
  7660. return this._renderDuration;
  7661. };
  7662. Scene.prototype.getParticlesDuration = function () {
  7663. return this._particlesDuration;
  7664. };
  7665. Scene.prototype.getSpritesDuration = function () {
  7666. return this._spritesDuration;
  7667. };
  7668. Scene.prototype.getAnimationRatio = function () {
  7669. return this._animationRatio;
  7670. };
  7671. Scene.prototype.getRenderId = function () {
  7672. return this._renderId;
  7673. };
  7674. Scene.prototype.incrementRenderId = function () {
  7675. this._renderId++;
  7676. };
  7677. Scene.prototype._updatePointerPosition = function (evt) {
  7678. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7679. this._pointerX = evt.clientX - canvasRect.left;
  7680. this._pointerY = evt.clientY - canvasRect.top;
  7681. if (this.cameraToUseForPointers) {
  7682. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7683. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7684. }
  7685. };
  7686. // Pointers handling
  7687. Scene.prototype.attachControl = function () {
  7688. var _this = this;
  7689. this._onPointerMove = function (evt) {
  7690. var canvas = _this._engine.getRenderingCanvas();
  7691. _this._updatePointerPosition(evt);
  7692. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers; }, false, _this.cameraToUseForPointers);
  7693. if (pickResult.hit) {
  7694. _this._meshUnderPointer = pickResult.pickedMesh;
  7695. _this.setPointerOverMesh(pickResult.pickedMesh);
  7696. canvas.style.cursor = "pointer";
  7697. }
  7698. else {
  7699. _this.setPointerOverMesh(null);
  7700. canvas.style.cursor = "";
  7701. _this._meshUnderPointer = null;
  7702. }
  7703. };
  7704. this._onPointerDown = function (evt) {
  7705. var predicate = null;
  7706. if (!_this.onPointerDown) {
  7707. predicate = function (mesh) {
  7708. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7709. };
  7710. }
  7711. _this._updatePointerPosition(evt);
  7712. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7713. if (pickResult.hit) {
  7714. if (pickResult.pickedMesh.actionManager) {
  7715. switch (evt.button) {
  7716. case 0:
  7717. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7718. break;
  7719. case 1:
  7720. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7721. break;
  7722. case 2:
  7723. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7724. break;
  7725. }
  7726. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7727. }
  7728. }
  7729. if (_this.onPointerDown) {
  7730. _this.onPointerDown(evt, pickResult);
  7731. }
  7732. };
  7733. this._onKeyDown = function (evt) {
  7734. if (_this.actionManager) {
  7735. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7736. }
  7737. };
  7738. this._onKeyUp = function (evt) {
  7739. if (_this.actionManager) {
  7740. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7741. }
  7742. };
  7743. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7744. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7745. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7746. BABYLON.Tools.RegisterTopRootEvents([
  7747. { name: "keydown", handler: this._onKeyDown },
  7748. { name: "keyup", handler: this._onKeyUp }
  7749. ]);
  7750. };
  7751. Scene.prototype.detachControl = function () {
  7752. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7753. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7754. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7755. BABYLON.Tools.UnregisterTopRootEvents([
  7756. { name: "keydown", handler: this._onKeyDown },
  7757. { name: "keyup", handler: this._onKeyUp }
  7758. ]);
  7759. };
  7760. // Ready
  7761. Scene.prototype.isReady = function () {
  7762. if (this._pendingData.length > 0) {
  7763. return false;
  7764. }
  7765. for (var index = 0; index < this._geometries.length; index++) {
  7766. var geometry = this._geometries[index];
  7767. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7768. return false;
  7769. }
  7770. }
  7771. for (index = 0; index < this.meshes.length; index++) {
  7772. var mesh = this.meshes[index];
  7773. if (!mesh.isReady()) {
  7774. return false;
  7775. }
  7776. var mat = mesh.material;
  7777. if (mat) {
  7778. if (!mat.isReady(mesh)) {
  7779. return false;
  7780. }
  7781. }
  7782. }
  7783. return true;
  7784. };
  7785. Scene.prototype.resetCachedMaterial = function () {
  7786. this._cachedMaterial = null;
  7787. };
  7788. Scene.prototype.registerBeforeRender = function (func) {
  7789. this._onBeforeRenderCallbacks.push(func);
  7790. };
  7791. Scene.prototype.unregisterBeforeRender = function (func) {
  7792. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7793. if (index > -1) {
  7794. this._onBeforeRenderCallbacks.splice(index, 1);
  7795. }
  7796. };
  7797. Scene.prototype.registerAfterRender = function (func) {
  7798. this._onAfterRenderCallbacks.push(func);
  7799. };
  7800. Scene.prototype.unregisterAfterRender = function (func) {
  7801. var index = this._onAfterRenderCallbacks.indexOf(func);
  7802. if (index > -1) {
  7803. this._onAfterRenderCallbacks.splice(index, 1);
  7804. }
  7805. };
  7806. Scene.prototype._addPendingData = function (data) {
  7807. this._pendingData.push(data);
  7808. };
  7809. Scene.prototype._removePendingData = function (data) {
  7810. var index = this._pendingData.indexOf(data);
  7811. if (index !== -1) {
  7812. this._pendingData.splice(index, 1);
  7813. }
  7814. };
  7815. Scene.prototype.getWaitingItemsCount = function () {
  7816. return this._pendingData.length;
  7817. };
  7818. /**
  7819. * Registers a function to be executed when the scene is ready.
  7820. * @param {Function} func - the function to be executed.
  7821. */
  7822. Scene.prototype.executeWhenReady = function (func) {
  7823. var _this = this;
  7824. this._onReadyCallbacks.push(func);
  7825. if (this._executeWhenReadyTimeoutId !== -1) {
  7826. return;
  7827. }
  7828. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7829. _this._checkIsReady();
  7830. }, 150);
  7831. };
  7832. Scene.prototype._checkIsReady = function () {
  7833. var _this = this;
  7834. if (this.isReady()) {
  7835. this._onReadyCallbacks.forEach(function (func) {
  7836. func();
  7837. });
  7838. this._onReadyCallbacks = [];
  7839. this._executeWhenReadyTimeoutId = -1;
  7840. return;
  7841. }
  7842. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7843. _this._checkIsReady();
  7844. }, 150);
  7845. };
  7846. // Animations
  7847. /**
  7848. * Will start the animation sequence of a given target
  7849. * @param target - the target
  7850. * @param {number} from - from which frame should animation start
  7851. * @param {number} to - till which frame should animation run.
  7852. * @param {boolean} [loop] - should the animation loop
  7853. * @param {number} [speedRatio] - the speed in which to run the animation
  7854. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  7855. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  7856. * @return {BABYLON.Animatable} the animatable object created for this animation
  7857. * @see BABYLON.Animatable
  7858. * @see http://doc.babylonjs.com/page.php?p=22081
  7859. */
  7860. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7861. if (speedRatio === undefined) {
  7862. speedRatio = 1.0;
  7863. }
  7864. this.stopAnimation(target);
  7865. if (!animatable) {
  7866. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7867. }
  7868. // Local animations
  7869. if (target.animations) {
  7870. animatable.appendAnimations(target, target.animations);
  7871. }
  7872. // Children animations
  7873. if (target.getAnimatables) {
  7874. var animatables = target.getAnimatables();
  7875. for (var index = 0; index < animatables.length; index++) {
  7876. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7877. }
  7878. }
  7879. return animatable;
  7880. };
  7881. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7882. if (speedRatio === undefined) {
  7883. speedRatio = 1.0;
  7884. }
  7885. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7886. return animatable;
  7887. };
  7888. Scene.prototype.getAnimatableByTarget = function (target) {
  7889. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7890. if (this._activeAnimatables[index].target === target) {
  7891. return this._activeAnimatables[index];
  7892. }
  7893. }
  7894. return null;
  7895. };
  7896. /**
  7897. * Will stop the animation of the given target
  7898. * @param target - the target
  7899. * @see beginAnimation
  7900. */
  7901. Scene.prototype.stopAnimation = function (target) {
  7902. var animatable = this.getAnimatableByTarget(target);
  7903. if (animatable) {
  7904. animatable.stop();
  7905. }
  7906. };
  7907. Scene.prototype._animate = function () {
  7908. if (!this.animationsEnabled) {
  7909. return;
  7910. }
  7911. if (!this._animationStartDate) {
  7912. this._animationStartDate = BABYLON.Tools.Now;
  7913. }
  7914. // Getting time
  7915. var now = BABYLON.Tools.Now;
  7916. var delay = now - this._animationStartDate;
  7917. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7918. if (!this._activeAnimatables[index]._animate(delay)) {
  7919. this._activeAnimatables.splice(index, 1);
  7920. index--;
  7921. }
  7922. }
  7923. };
  7924. // Matrix
  7925. Scene.prototype.getViewMatrix = function () {
  7926. return this._viewMatrix;
  7927. };
  7928. Scene.prototype.getProjectionMatrix = function () {
  7929. return this._projectionMatrix;
  7930. };
  7931. Scene.prototype.getTransformMatrix = function () {
  7932. return this._transformMatrix;
  7933. };
  7934. Scene.prototype.setTransformMatrix = function (view, projection) {
  7935. this._viewMatrix = view;
  7936. this._projectionMatrix = projection;
  7937. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  7938. };
  7939. // Methods
  7940. /**
  7941. * sets the active camera of the scene using its ID
  7942. * @param {string} id - the camera's ID
  7943. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  7944. * @see activeCamera
  7945. */
  7946. Scene.prototype.setActiveCameraByID = function (id) {
  7947. var camera = this.getCameraByID(id);
  7948. if (camera) {
  7949. this.activeCamera = camera;
  7950. return camera;
  7951. }
  7952. return null;
  7953. };
  7954. /**
  7955. * sets the active camera of the scene using its name
  7956. * @param {string} name - the camera's name
  7957. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  7958. * @see activeCamera
  7959. */
  7960. Scene.prototype.setActiveCameraByName = function (name) {
  7961. var camera = this.getCameraByName(name);
  7962. if (camera) {
  7963. this.activeCamera = camera;
  7964. return camera;
  7965. }
  7966. return null;
  7967. };
  7968. /**
  7969. * get a material using its id
  7970. * @param {string} the material's ID
  7971. * @return {BABYLON.Material|null} the material or null if none found.
  7972. */
  7973. Scene.prototype.getMaterialByID = function (id) {
  7974. for (var index = 0; index < this.materials.length; index++) {
  7975. if (this.materials[index].id === id) {
  7976. return this.materials[index];
  7977. }
  7978. }
  7979. return null;
  7980. };
  7981. /**
  7982. * get a material using its name
  7983. * @param {string} the material's name
  7984. * @return {BABYLON.Material|null} the material or null if none found.
  7985. */
  7986. Scene.prototype.getMaterialByName = function (name) {
  7987. for (var index = 0; index < this.materials.length; index++) {
  7988. if (this.materials[index].name === name) {
  7989. return this.materials[index];
  7990. }
  7991. }
  7992. return null;
  7993. };
  7994. Scene.prototype.getCameraByID = function (id) {
  7995. for (var index = 0; index < this.cameras.length; index++) {
  7996. if (this.cameras[index].id === id) {
  7997. return this.cameras[index];
  7998. }
  7999. }
  8000. return null;
  8001. };
  8002. /**
  8003. * get a camera using its name
  8004. * @param {string} the camera's name
  8005. * @return {BABYLON.Camera|null} the camera or null if none found.
  8006. */
  8007. Scene.prototype.getCameraByName = function (name) {
  8008. for (var index = 0; index < this.cameras.length; index++) {
  8009. if (this.cameras[index].name === name) {
  8010. return this.cameras[index];
  8011. }
  8012. }
  8013. return null;
  8014. };
  8015. /**
  8016. * get a light node using its name
  8017. * @param {string} the light's name
  8018. * @return {BABYLON.Light|null} the light or null if none found.
  8019. */
  8020. Scene.prototype.getLightByName = function (name) {
  8021. for (var index = 0; index < this.lights.length; index++) {
  8022. if (this.lights[index].name === name) {
  8023. return this.lights[index];
  8024. }
  8025. }
  8026. return null;
  8027. };
  8028. /**
  8029. * get a light node using its ID
  8030. * @param {string} the light's id
  8031. * @return {BABYLON.Light|null} the light or null if none found.
  8032. */
  8033. Scene.prototype.getLightByID = function (id) {
  8034. for (var index = 0; index < this.lights.length; index++) {
  8035. if (this.lights[index].id === id) {
  8036. return this.lights[index];
  8037. }
  8038. }
  8039. return null;
  8040. };
  8041. /**
  8042. * get a geometry using its ID
  8043. * @param {string} the geometry's id
  8044. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8045. */
  8046. Scene.prototype.getGeometryByID = function (id) {
  8047. for (var index = 0; index < this._geometries.length; index++) {
  8048. if (this._geometries[index].id === id) {
  8049. return this._geometries[index];
  8050. }
  8051. }
  8052. return null;
  8053. };
  8054. /**
  8055. * add a new geometry to this scene.
  8056. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8057. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8058. * @return {boolean} was the geometry added or not
  8059. */
  8060. Scene.prototype.pushGeometry = function (geometry, force) {
  8061. if (!force && this.getGeometryByID(geometry.id)) {
  8062. return false;
  8063. }
  8064. this._geometries.push(geometry);
  8065. return true;
  8066. };
  8067. Scene.prototype.getGeometries = function () {
  8068. return this._geometries;
  8069. };
  8070. /**
  8071. * Get a the first added mesh found of a given ID
  8072. * @param {string} id - the id to search for
  8073. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8074. */
  8075. Scene.prototype.getMeshByID = function (id) {
  8076. for (var index = 0; index < this.meshes.length; index++) {
  8077. if (this.meshes[index].id === id) {
  8078. return this.meshes[index];
  8079. }
  8080. }
  8081. return null;
  8082. };
  8083. /**
  8084. * Get a the last added mesh found of a given ID
  8085. * @param {string} id - the id to search for
  8086. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8087. */
  8088. Scene.prototype.getLastMeshByID = function (id) {
  8089. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8090. if (this.meshes[index].id === id) {
  8091. return this.meshes[index];
  8092. }
  8093. }
  8094. return null;
  8095. };
  8096. /**
  8097. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8098. * @param {string} id - the id to search for
  8099. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8100. */
  8101. Scene.prototype.getLastEntryByID = function (id) {
  8102. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8103. if (this.meshes[index].id === id) {
  8104. return this.meshes[index];
  8105. }
  8106. }
  8107. for (index = this.cameras.length - 1; index >= 0; index--) {
  8108. if (this.cameras[index].id === id) {
  8109. return this.cameras[index];
  8110. }
  8111. }
  8112. for (index = this.lights.length - 1; index >= 0; index--) {
  8113. if (this.lights[index].id === id) {
  8114. return this.lights[index];
  8115. }
  8116. }
  8117. return null;
  8118. };
  8119. Scene.prototype.getNodeByName = function (name) {
  8120. var mesh = this.getMeshByName(name);
  8121. if (mesh) {
  8122. return mesh;
  8123. }
  8124. var light = this.getLightByName(name);
  8125. if (light) {
  8126. return light;
  8127. }
  8128. return this.getCameraByName(name);
  8129. };
  8130. Scene.prototype.getMeshByName = function (name) {
  8131. for (var index = 0; index < this.meshes.length; index++) {
  8132. if (this.meshes[index].name === name) {
  8133. return this.meshes[index];
  8134. }
  8135. }
  8136. return null;
  8137. };
  8138. Scene.prototype.getSoundByName = function (name) {
  8139. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8140. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8141. return this.mainSoundTrack.soundCollection[index];
  8142. }
  8143. }
  8144. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8145. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8146. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8147. return this.soundTracks[sdIndex].soundCollection[index];
  8148. }
  8149. }
  8150. }
  8151. return null;
  8152. };
  8153. Scene.prototype.getLastSkeletonByID = function (id) {
  8154. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8155. if (this.skeletons[index].id === id) {
  8156. return this.skeletons[index];
  8157. }
  8158. }
  8159. return null;
  8160. };
  8161. Scene.prototype.getSkeletonById = function (id) {
  8162. for (var index = 0; index < this.skeletons.length; index++) {
  8163. if (this.skeletons[index].id === id) {
  8164. return this.skeletons[index];
  8165. }
  8166. }
  8167. return null;
  8168. };
  8169. Scene.prototype.getSkeletonByName = function (name) {
  8170. for (var index = 0; index < this.skeletons.length; index++) {
  8171. if (this.skeletons[index].name === name) {
  8172. return this.skeletons[index];
  8173. }
  8174. }
  8175. return null;
  8176. };
  8177. Scene.prototype.isActiveMesh = function (mesh) {
  8178. return (this._activeMeshes.indexOf(mesh) !== -1);
  8179. };
  8180. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8181. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8182. var material = subMesh.getMaterial();
  8183. if (mesh.showSubMeshesBoundingBox) {
  8184. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8185. }
  8186. if (material) {
  8187. // Render targets
  8188. if (material.getRenderTargetTextures) {
  8189. if (this._processedMaterials.indexOf(material) === -1) {
  8190. this._processedMaterials.push(material);
  8191. this._renderTargets.concat(material.getRenderTargetTextures());
  8192. }
  8193. }
  8194. // Dispatch
  8195. this._activeVertices += subMesh.indexCount;
  8196. this._renderingManager.dispatch(subMesh);
  8197. }
  8198. }
  8199. };
  8200. Scene.prototype._evaluateActiveMeshes = function () {
  8201. this._activeMeshes.reset();
  8202. this._renderingManager.reset();
  8203. this._processedMaterials.reset();
  8204. this._activeParticleSystems.reset();
  8205. this._activeSkeletons.reset();
  8206. this._boundingBoxRenderer.reset();
  8207. if (!this._frustumPlanes) {
  8208. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8209. }
  8210. else {
  8211. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8212. }
  8213. // Meshes
  8214. var meshes;
  8215. var len;
  8216. if (this._selectionOctree) {
  8217. var selection = this._selectionOctree.select(this._frustumPlanes);
  8218. meshes = selection.data;
  8219. len = selection.length;
  8220. }
  8221. else {
  8222. len = this.meshes.length;
  8223. meshes = this.meshes;
  8224. }
  8225. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8226. var mesh = meshes[meshIndex];
  8227. if (mesh.isBlocked) {
  8228. continue;
  8229. }
  8230. this._totalVertices += mesh.getTotalVertices();
  8231. if (!mesh.isReady()) {
  8232. continue;
  8233. }
  8234. mesh.computeWorldMatrix();
  8235. // Intersections
  8236. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8237. this._meshesForIntersections.pushNoDuplicate(mesh);
  8238. }
  8239. // Switch to current LOD
  8240. var meshLOD = mesh.getLOD(this.activeCamera);
  8241. if (!meshLOD) {
  8242. continue;
  8243. }
  8244. mesh._preActivate();
  8245. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8246. this._activeMeshes.push(mesh);
  8247. mesh._activate(this._renderId);
  8248. this._activeMesh(meshLOD);
  8249. }
  8250. }
  8251. // Particle systems
  8252. var beforeParticlesDate = BABYLON.Tools.Now;
  8253. if (this.particlesEnabled) {
  8254. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8255. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8256. var particleSystem = this.particleSystems[particleIndex];
  8257. if (!particleSystem.isStarted()) {
  8258. continue;
  8259. }
  8260. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8261. this._activeParticleSystems.push(particleSystem);
  8262. particleSystem.animate();
  8263. }
  8264. }
  8265. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8266. }
  8267. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8268. };
  8269. Scene.prototype._activeMesh = function (mesh) {
  8270. if (mesh.skeleton && this.skeletonsEnabled) {
  8271. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8272. }
  8273. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8274. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8275. }
  8276. if (mesh && mesh.subMeshes) {
  8277. // Submeshes Octrees
  8278. var len;
  8279. var subMeshes;
  8280. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8281. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8282. len = intersections.length;
  8283. subMeshes = intersections.data;
  8284. }
  8285. else {
  8286. subMeshes = mesh.subMeshes;
  8287. len = subMeshes.length;
  8288. }
  8289. for (var subIndex = 0; subIndex < len; subIndex++) {
  8290. var subMesh = subMeshes[subIndex];
  8291. this._evaluateSubMesh(subMesh, mesh);
  8292. }
  8293. }
  8294. };
  8295. Scene.prototype.updateTransformMatrix = function (force) {
  8296. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8297. };
  8298. Scene.prototype._renderForCamera = function (camera) {
  8299. var engine = this._engine;
  8300. this.activeCamera = camera;
  8301. if (!this.activeCamera)
  8302. throw new Error("Active camera not set");
  8303. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8304. // Viewport
  8305. engine.setViewport(this.activeCamera.viewport);
  8306. // Camera
  8307. this._renderId++;
  8308. this.updateTransformMatrix();
  8309. if (this.beforeCameraRender) {
  8310. this.beforeCameraRender(this.activeCamera);
  8311. }
  8312. // Meshes
  8313. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8314. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8315. this._evaluateActiveMeshes();
  8316. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8317. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8318. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8319. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8320. skeleton.prepare();
  8321. this._activeBones += skeleton.bones.length;
  8322. }
  8323. // Render targets
  8324. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8325. if (this.renderTargetsEnabled) {
  8326. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8327. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8328. var renderTarget = this._renderTargets.data[renderIndex];
  8329. if (renderTarget._shouldRender()) {
  8330. this._renderId++;
  8331. renderTarget.render();
  8332. }
  8333. }
  8334. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8335. this._renderId++;
  8336. }
  8337. if (this._renderTargets.length > 0) {
  8338. engine.restoreDefaultFramebuffer();
  8339. }
  8340. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8341. // Prepare Frame
  8342. this.postProcessManager._prepareFrame();
  8343. var beforeRenderDate = BABYLON.Tools.Now;
  8344. // Backgrounds
  8345. if (this.layers.length) {
  8346. engine.setDepthBuffer(false);
  8347. var layerIndex;
  8348. var layer;
  8349. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8350. layer = this.layers[layerIndex];
  8351. if (layer.isBackground) {
  8352. layer.render();
  8353. }
  8354. }
  8355. engine.setDepthBuffer(true);
  8356. }
  8357. // Render
  8358. BABYLON.Tools.StartPerformanceCounter("Main render");
  8359. this._renderingManager.render(null, null, true, true);
  8360. BABYLON.Tools.EndPerformanceCounter("Main render");
  8361. // Bounding boxes
  8362. this._boundingBoxRenderer.render();
  8363. // Lens flares
  8364. if (this.lensFlaresEnabled) {
  8365. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8366. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8367. this.lensFlareSystems[lensFlareSystemIndex].render();
  8368. }
  8369. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8370. }
  8371. // Foregrounds
  8372. if (this.layers.length) {
  8373. engine.setDepthBuffer(false);
  8374. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8375. layer = this.layers[layerIndex];
  8376. if (!layer.isBackground) {
  8377. layer.render();
  8378. }
  8379. }
  8380. engine.setDepthBuffer(true);
  8381. }
  8382. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8383. // Finalize frame
  8384. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8385. // Update camera
  8386. this.activeCamera._updateFromScene();
  8387. // Reset some special arrays
  8388. this._renderTargets.reset();
  8389. if (this.afterCameraRender) {
  8390. this.afterCameraRender(this.activeCamera);
  8391. }
  8392. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8393. };
  8394. Scene.prototype._processSubCameras = function (camera) {
  8395. if (camera.subCameras.length === 0) {
  8396. this._renderForCamera(camera);
  8397. return;
  8398. }
  8399. for (var index = 0; index < camera.subCameras.length; index++) {
  8400. this._renderForCamera(camera.subCameras[index]);
  8401. }
  8402. this.activeCamera = camera;
  8403. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8404. // Update camera
  8405. this.activeCamera._updateFromScene();
  8406. };
  8407. Scene.prototype._checkIntersections = function () {
  8408. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8409. var sourceMesh = this._meshesForIntersections.data[index];
  8410. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8411. var action = sourceMesh.actionManager.actions[actionIndex];
  8412. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8413. var parameters = action.getTriggerParameter();
  8414. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  8415. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  8416. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8417. if (areIntersecting && currentIntersectionInProgress === -1) {
  8418. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8419. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8420. sourceMesh._intersectionsInProgress.push(otherMesh);
  8421. }
  8422. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8423. sourceMesh._intersectionsInProgress.push(otherMesh);
  8424. }
  8425. }
  8426. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8427. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8428. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8429. if (indexOfOther > -1) {
  8430. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8431. }
  8432. }
  8433. }
  8434. }
  8435. }
  8436. };
  8437. Scene.prototype.render = function () {
  8438. var startDate = BABYLON.Tools.Now;
  8439. this._particlesDuration = 0;
  8440. this._spritesDuration = 0;
  8441. this._activeParticles = 0;
  8442. this._renderDuration = 0;
  8443. this._renderTargetsDuration = 0;
  8444. this._evaluateActiveMeshesDuration = 0;
  8445. this._totalVertices = 0;
  8446. this._activeVertices = 0;
  8447. this._activeBones = 0;
  8448. this.getEngine().resetDrawCalls();
  8449. this._meshesForIntersections.reset();
  8450. this.resetCachedMaterial();
  8451. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8452. // Actions
  8453. if (this.actionManager) {
  8454. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8455. }
  8456. // Before render
  8457. if (this.beforeRender) {
  8458. this.beforeRender();
  8459. }
  8460. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8461. this._onBeforeRenderCallbacks[callbackIndex]();
  8462. }
  8463. // Animations
  8464. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8465. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8466. this._animate();
  8467. // Physics
  8468. if (this._physicsEngine) {
  8469. BABYLON.Tools.StartPerformanceCounter("Physics");
  8470. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8471. BABYLON.Tools.EndPerformanceCounter("Physics");
  8472. }
  8473. // Customs render targets
  8474. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8475. var engine = this.getEngine();
  8476. if (this.renderTargetsEnabled) {
  8477. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8478. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8479. var renderTarget = this.customRenderTargets[customIndex];
  8480. if (renderTarget._shouldRender()) {
  8481. this._renderId++;
  8482. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8483. if (!this.activeCamera)
  8484. throw new Error("Active camera not set");
  8485. // Viewport
  8486. engine.setViewport(this.activeCamera.viewport);
  8487. // Camera
  8488. this.updateTransformMatrix();
  8489. renderTarget.render();
  8490. }
  8491. }
  8492. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8493. this._renderId++;
  8494. }
  8495. if (this.customRenderTargets.length > 0) {
  8496. engine.restoreDefaultFramebuffer();
  8497. }
  8498. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8499. // Procedural textures
  8500. if (this.proceduralTexturesEnabled) {
  8501. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8502. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8503. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8504. if (proceduralTexture._shouldRender()) {
  8505. proceduralTexture.render();
  8506. }
  8507. }
  8508. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8509. }
  8510. // Clear
  8511. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8512. // Shadows
  8513. if (this.shadowsEnabled) {
  8514. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8515. var light = this.lights[lightIndex];
  8516. var shadowGenerator = light.getShadowGenerator();
  8517. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8518. this._renderTargets.push(shadowGenerator.getShadowMap());
  8519. }
  8520. }
  8521. }
  8522. // Depth renderer
  8523. if (this._depthRenderer) {
  8524. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8525. }
  8526. // RenderPipeline
  8527. this.postProcessRenderPipelineManager.update();
  8528. // Multi-cameras?
  8529. if (this.activeCameras.length > 0) {
  8530. var currentRenderId = this._renderId;
  8531. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8532. this._renderId = currentRenderId;
  8533. this._processSubCameras(this.activeCameras[cameraIndex]);
  8534. }
  8535. }
  8536. else {
  8537. if (!this.activeCamera) {
  8538. throw new Error("No camera defined");
  8539. }
  8540. this._processSubCameras(this.activeCamera);
  8541. }
  8542. // Intersection checks
  8543. this._checkIntersections();
  8544. // Update the audio listener attached to the camera
  8545. this._updateAudioParameters();
  8546. // After render
  8547. if (this.afterRender) {
  8548. this.afterRender();
  8549. }
  8550. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8551. this._onAfterRenderCallbacks[callbackIndex]();
  8552. }
  8553. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8554. this._toBeDisposed.data[index].dispose();
  8555. this._toBeDisposed[index] = null;
  8556. }
  8557. this._toBeDisposed.reset();
  8558. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8559. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8560. };
  8561. Scene.prototype._updateAudioParameters = function () {
  8562. var listeningCamera;
  8563. var audioEngine = BABYLON.Engine.audioEngine;
  8564. if (this.activeCameras.length > 0) {
  8565. listeningCamera = this.activeCameras[0];
  8566. }
  8567. else {
  8568. listeningCamera = this.activeCamera;
  8569. }
  8570. if (listeningCamera && audioEngine.canUseWebAudio) {
  8571. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8572. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8573. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8574. cameraDirection.normalize();
  8575. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8576. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8577. var sound = this.mainSoundTrack.soundCollection[i];
  8578. if (sound.useCustomAttenuation) {
  8579. sound.updateDistanceFromListener();
  8580. }
  8581. }
  8582. for (i = 0; i < this.soundTracks.length; i++) {
  8583. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8584. sound = this.soundTracks[i].soundCollection[j];
  8585. if (sound.useCustomAttenuation) {
  8586. sound.updateDistanceFromListener();
  8587. }
  8588. }
  8589. }
  8590. }
  8591. };
  8592. Scene.prototype.enableDepthRenderer = function () {
  8593. if (this._depthRenderer) {
  8594. return this._depthRenderer;
  8595. }
  8596. this._depthRenderer = new BABYLON.DepthRenderer(this);
  8597. return this._depthRenderer;
  8598. };
  8599. Scene.prototype.disableDepthRenderer = function () {
  8600. if (!this._depthRenderer) {
  8601. return;
  8602. }
  8603. this._depthRenderer.dispose();
  8604. this._depthRenderer = null;
  8605. };
  8606. Scene.prototype.dispose = function () {
  8607. this.beforeRender = null;
  8608. this.afterRender = null;
  8609. this.skeletons = [];
  8610. this._boundingBoxRenderer.dispose();
  8611. if (this._depthRenderer) {
  8612. this._depthRenderer.dispose();
  8613. }
  8614. // Debug layer
  8615. this.debugLayer.hide();
  8616. // Events
  8617. if (this.onDispose) {
  8618. this.onDispose();
  8619. }
  8620. this._onBeforeRenderCallbacks = [];
  8621. this._onAfterRenderCallbacks = [];
  8622. this.detachControl();
  8623. // Release sounds & sounds tracks
  8624. this.mainSoundTrack.dispose();
  8625. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  8626. this.soundTracks[scIndex].dispose();
  8627. }
  8628. // Detach cameras
  8629. var canvas = this._engine.getRenderingCanvas();
  8630. var index;
  8631. for (index = 0; index < this.cameras.length; index++) {
  8632. this.cameras[index].detachControl(canvas);
  8633. }
  8634. while (this.lights.length) {
  8635. this.lights[0].dispose();
  8636. }
  8637. while (this.meshes.length) {
  8638. this.meshes[0].dispose(true);
  8639. }
  8640. while (this.cameras.length) {
  8641. this.cameras[0].dispose();
  8642. }
  8643. while (this.materials.length) {
  8644. this.materials[0].dispose();
  8645. }
  8646. while (this.particleSystems.length) {
  8647. this.particleSystems[0].dispose();
  8648. }
  8649. while (this.spriteManagers.length) {
  8650. this.spriteManagers[0].dispose();
  8651. }
  8652. while (this.layers.length) {
  8653. this.layers[0].dispose();
  8654. }
  8655. while (this.textures.length) {
  8656. this.textures[0].dispose();
  8657. }
  8658. // Post-processes
  8659. this.postProcessManager.dispose();
  8660. // Physics
  8661. if (this._physicsEngine) {
  8662. this.disablePhysicsEngine();
  8663. }
  8664. // Remove from engine
  8665. index = this._engine.scenes.indexOf(this);
  8666. if (index > -1) {
  8667. this._engine.scenes.splice(index, 1);
  8668. }
  8669. this._engine.wipeCaches();
  8670. };
  8671. // Collisions
  8672. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8673. if (excludedMesh === void 0) { excludedMesh = null; }
  8674. position.divideToRef(collider.radius, this._scaledPosition);
  8675. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8676. collider.retry = 0;
  8677. collider.initialVelocity = this._scaledVelocity;
  8678. collider.initialPosition = this._scaledPosition;
  8679. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8680. finalPosition.multiplyInPlace(collider.radius);
  8681. };
  8682. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8683. if (excludedMesh === void 0) { excludedMesh = null; }
  8684. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8685. if (collider.retry >= maximumRetry) {
  8686. finalPosition.copyFrom(position);
  8687. return;
  8688. }
  8689. collider._initialize(position, velocity, closeDistance);
  8690. for (var index = 0; index < this.meshes.length; index++) {
  8691. var mesh = this.meshes[index];
  8692. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8693. mesh._checkCollision(collider);
  8694. }
  8695. }
  8696. if (!collider.collisionFound) {
  8697. position.addToRef(velocity, finalPosition);
  8698. return;
  8699. }
  8700. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8701. collider._getResponse(position, velocity);
  8702. }
  8703. if (velocity.length() <= closeDistance) {
  8704. finalPosition.copyFrom(position);
  8705. return;
  8706. }
  8707. collider.retry++;
  8708. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8709. };
  8710. // Octrees
  8711. Scene.prototype.getWorldExtends = function () {
  8712. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8713. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8714. for (var index = 0; index < this.meshes.length; index++) {
  8715. var mesh = this.meshes[index];
  8716. mesh.computeWorldMatrix(true);
  8717. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8718. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8719. BABYLON.Tools.CheckExtends(minBox, min, max);
  8720. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8721. }
  8722. return {
  8723. min: min,
  8724. max: max
  8725. };
  8726. };
  8727. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8728. if (maxCapacity === void 0) { maxCapacity = 64; }
  8729. if (maxDepth === void 0) { maxDepth = 2; }
  8730. if (!this._selectionOctree) {
  8731. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8732. }
  8733. var worldExtends = this.getWorldExtends();
  8734. // Update octree
  8735. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  8736. return this._selectionOctree;
  8737. };
  8738. // Picking
  8739. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8740. var engine = this._engine;
  8741. if (!camera) {
  8742. if (!this.activeCamera)
  8743. throw new Error("Active camera not set");
  8744. camera = this.activeCamera;
  8745. }
  8746. var cameraViewport = camera.viewport;
  8747. var viewport = cameraViewport.toGlobal(engine);
  8748. // Moving coordinates to local viewport world
  8749. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8750. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8751. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8752. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8753. };
  8754. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8755. var pickingInfo = null;
  8756. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8757. var mesh = this.meshes[meshIndex];
  8758. if (predicate) {
  8759. if (!predicate(mesh)) {
  8760. continue;
  8761. }
  8762. }
  8763. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8764. continue;
  8765. }
  8766. var world = mesh.getWorldMatrix();
  8767. var ray = rayFunction(world);
  8768. var result = mesh.intersects(ray, fastCheck);
  8769. if (!result || !result.hit)
  8770. continue;
  8771. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8772. continue;
  8773. pickingInfo = result;
  8774. if (fastCheck) {
  8775. break;
  8776. }
  8777. }
  8778. return pickingInfo || new BABYLON.PickingInfo();
  8779. };
  8780. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8781. var _this = this;
  8782. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8783. /// <param name="x">X position on screen</param>
  8784. /// <param name="y">Y position on screen</param>
  8785. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  8786. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8787. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  8788. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  8789. };
  8790. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8791. var _this = this;
  8792. return this._internalPick(function (world) {
  8793. if (!_this._pickWithRayInverseMatrix) {
  8794. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8795. }
  8796. world.invertToRef(_this._pickWithRayInverseMatrix);
  8797. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8798. }, predicate, fastCheck);
  8799. };
  8800. Scene.prototype.setPointerOverMesh = function (mesh) {
  8801. if (this._pointerOverMesh === mesh) {
  8802. return;
  8803. }
  8804. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8805. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8806. }
  8807. this._pointerOverMesh = mesh;
  8808. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8809. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8810. }
  8811. };
  8812. Scene.prototype.getPointerOverMesh = function () {
  8813. return this._pointerOverMesh;
  8814. };
  8815. // Physics
  8816. Scene.prototype.getPhysicsEngine = function () {
  8817. return this._physicsEngine;
  8818. };
  8819. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8820. if (this._physicsEngine) {
  8821. return true;
  8822. }
  8823. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8824. if (!this._physicsEngine.isSupported()) {
  8825. this._physicsEngine = null;
  8826. return false;
  8827. }
  8828. this._physicsEngine._initialize(gravity);
  8829. return true;
  8830. };
  8831. Scene.prototype.disablePhysicsEngine = function () {
  8832. if (!this._physicsEngine) {
  8833. return;
  8834. }
  8835. this._physicsEngine.dispose();
  8836. this._physicsEngine = undefined;
  8837. };
  8838. Scene.prototype.isPhysicsEnabled = function () {
  8839. return this._physicsEngine !== undefined;
  8840. };
  8841. Scene.prototype.setGravity = function (gravity) {
  8842. if (!this._physicsEngine) {
  8843. return;
  8844. }
  8845. this._physicsEngine._setGravity(gravity);
  8846. };
  8847. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8848. if (parts.parts) {
  8849. options = parts;
  8850. parts = parts.parts;
  8851. }
  8852. if (!this._physicsEngine) {
  8853. return null;
  8854. }
  8855. for (var index = 0; index < parts.length; index++) {
  8856. var mesh = parts[index].mesh;
  8857. mesh._physicImpostor = parts[index].impostor;
  8858. mesh._physicsMass = options.mass / parts.length;
  8859. mesh._physicsFriction = options.friction;
  8860. mesh._physicRestitution = options.restitution;
  8861. }
  8862. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8863. };
  8864. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8865. for (var index = 0; index < compound.parts.length; index++) {
  8866. var mesh = compound.parts[index].mesh;
  8867. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8868. this._physicsEngine._unregisterMesh(mesh);
  8869. }
  8870. };
  8871. // Misc.
  8872. Scene.prototype.createDefaultCameraOrLight = function () {
  8873. // Light
  8874. if (this.lights.length === 0) {
  8875. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  8876. }
  8877. // Camera
  8878. if (!this.activeCamera) {
  8879. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  8880. // Compute position
  8881. var worldExtends = this.getWorldExtends();
  8882. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  8883. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  8884. camera.setTarget(worldCenter);
  8885. this.activeCamera = camera;
  8886. }
  8887. };
  8888. // Tags
  8889. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  8890. if (tagsQuery === undefined) {
  8891. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8892. return list;
  8893. }
  8894. var listByTags = [];
  8895. forEach = forEach || (function (item) {
  8896. return;
  8897. });
  8898. for (var i in list) {
  8899. var item = list[i];
  8900. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8901. listByTags.push(item);
  8902. forEach(item);
  8903. }
  8904. }
  8905. return listByTags;
  8906. };
  8907. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  8908. return this._getByTags(this.meshes, tagsQuery, forEach);
  8909. };
  8910. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  8911. return this._getByTags(this.cameras, tagsQuery, forEach);
  8912. };
  8913. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  8914. return this._getByTags(this.lights, tagsQuery, forEach);
  8915. };
  8916. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  8917. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  8918. };
  8919. // Statics
  8920. Scene._FOGMODE_NONE = 0;
  8921. Scene._FOGMODE_EXP = 1;
  8922. Scene._FOGMODE_EXP2 = 2;
  8923. Scene._FOGMODE_LINEAR = 3;
  8924. Scene.MinDeltaTime = 1.0;
  8925. Scene.MaxDeltaTime = 1000.0;
  8926. return Scene;
  8927. })();
  8928. BABYLON.Scene = Scene;
  8929. })(BABYLON || (BABYLON = {}));
  8930. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  8931. (function (BABYLON) {
  8932. var VertexBuffer = (function () {
  8933. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8934. if (engine instanceof BABYLON.Mesh) {
  8935. this._engine = engine.getScene().getEngine();
  8936. }
  8937. else {
  8938. this._engine = engine;
  8939. }
  8940. this._updatable = updatable;
  8941. this._data = data;
  8942. if (!postponeInternalCreation) {
  8943. this.create();
  8944. }
  8945. this._kind = kind;
  8946. if (stride) {
  8947. this._strideSize = stride;
  8948. return;
  8949. }
  8950. switch (kind) {
  8951. case VertexBuffer.PositionKind:
  8952. this._strideSize = 3;
  8953. break;
  8954. case VertexBuffer.NormalKind:
  8955. this._strideSize = 3;
  8956. break;
  8957. case VertexBuffer.UVKind:
  8958. this._strideSize = 2;
  8959. break;
  8960. case VertexBuffer.UV2Kind:
  8961. this._strideSize = 2;
  8962. break;
  8963. case VertexBuffer.ColorKind:
  8964. this._strideSize = 4;
  8965. break;
  8966. case VertexBuffer.MatricesIndicesKind:
  8967. this._strideSize = 4;
  8968. break;
  8969. case VertexBuffer.MatricesWeightsKind:
  8970. this._strideSize = 4;
  8971. break;
  8972. }
  8973. }
  8974. // Properties
  8975. VertexBuffer.prototype.isUpdatable = function () {
  8976. return this._updatable;
  8977. };
  8978. VertexBuffer.prototype.getData = function () {
  8979. return this._data;
  8980. };
  8981. VertexBuffer.prototype.getBuffer = function () {
  8982. return this._buffer;
  8983. };
  8984. VertexBuffer.prototype.getStrideSize = function () {
  8985. return this._strideSize;
  8986. };
  8987. // Methods
  8988. VertexBuffer.prototype.create = function (data) {
  8989. if (!data && this._buffer) {
  8990. return; // nothing to do
  8991. }
  8992. data = data || this._data;
  8993. if (!this._buffer) {
  8994. if (this._updatable) {
  8995. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8996. }
  8997. else {
  8998. this._buffer = this._engine.createVertexBuffer(data);
  8999. }
  9000. }
  9001. if (this._updatable) {
  9002. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9003. this._data = data;
  9004. }
  9005. };
  9006. VertexBuffer.prototype.update = function (data) {
  9007. this.create(data);
  9008. };
  9009. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9010. if (!this._buffer) {
  9011. return;
  9012. }
  9013. if (this._updatable) {
  9014. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9015. this._data = null;
  9016. }
  9017. };
  9018. VertexBuffer.prototype.dispose = function () {
  9019. if (!this._buffer) {
  9020. return;
  9021. }
  9022. if (this._engine._releaseBuffer(this._buffer)) {
  9023. this._buffer = null;
  9024. }
  9025. };
  9026. Object.defineProperty(VertexBuffer, "PositionKind", {
  9027. get: function () {
  9028. return VertexBuffer._PositionKind;
  9029. },
  9030. enumerable: true,
  9031. configurable: true
  9032. });
  9033. Object.defineProperty(VertexBuffer, "NormalKind", {
  9034. get: function () {
  9035. return VertexBuffer._NormalKind;
  9036. },
  9037. enumerable: true,
  9038. configurable: true
  9039. });
  9040. Object.defineProperty(VertexBuffer, "UVKind", {
  9041. get: function () {
  9042. return VertexBuffer._UVKind;
  9043. },
  9044. enumerable: true,
  9045. configurable: true
  9046. });
  9047. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9048. get: function () {
  9049. return VertexBuffer._UV2Kind;
  9050. },
  9051. enumerable: true,
  9052. configurable: true
  9053. });
  9054. Object.defineProperty(VertexBuffer, "ColorKind", {
  9055. get: function () {
  9056. return VertexBuffer._ColorKind;
  9057. },
  9058. enumerable: true,
  9059. configurable: true
  9060. });
  9061. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9062. get: function () {
  9063. return VertexBuffer._MatricesIndicesKind;
  9064. },
  9065. enumerable: true,
  9066. configurable: true
  9067. });
  9068. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9069. get: function () {
  9070. return VertexBuffer._MatricesWeightsKind;
  9071. },
  9072. enumerable: true,
  9073. configurable: true
  9074. });
  9075. // Enums
  9076. VertexBuffer._PositionKind = "position";
  9077. VertexBuffer._NormalKind = "normal";
  9078. VertexBuffer._UVKind = "uv";
  9079. VertexBuffer._UV2Kind = "uv2";
  9080. VertexBuffer._ColorKind = "color";
  9081. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9082. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9083. return VertexBuffer;
  9084. })();
  9085. BABYLON.VertexBuffer = VertexBuffer;
  9086. })(BABYLON || (BABYLON = {}));
  9087. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9088. var BABYLON;
  9089. (function (BABYLON) {
  9090. var AbstractMesh = (function (_super) {
  9091. __extends(AbstractMesh, _super);
  9092. function AbstractMesh(name, scene) {
  9093. _super.call(this, name, scene);
  9094. // Properties
  9095. this.definedFacingForward = true; // orientation for POV movement & rotation
  9096. this.position = new BABYLON.Vector3(0, 0, 0);
  9097. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9098. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9099. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9100. this.visibility = 1.0;
  9101. this.alphaIndex = Number.MAX_VALUE;
  9102. this.infiniteDistance = false;
  9103. this.isVisible = true;
  9104. this.isPickable = true;
  9105. this.showBoundingBox = false;
  9106. this.showSubMeshesBoundingBox = false;
  9107. this.onDispose = null;
  9108. this.checkCollisions = false;
  9109. this.isBlocker = false;
  9110. this.renderingGroupId = 0;
  9111. this.receiveShadows = false;
  9112. this.renderOutline = false;
  9113. this.outlineColor = BABYLON.Color3.Red();
  9114. this.outlineWidth = 0.02;
  9115. this.renderOverlay = false;
  9116. this.overlayColor = BABYLON.Color3.Red();
  9117. this.overlayAlpha = 0.5;
  9118. this.hasVertexAlpha = false;
  9119. this.useVertexColors = true;
  9120. this.applyFog = true;
  9121. this.useOctreeForRenderingSelection = true;
  9122. this.useOctreeForPicking = true;
  9123. this.useOctreeForCollisions = true;
  9124. this.layerMask = 0xFFFFFFFF;
  9125. // Physics
  9126. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9127. // Collisions
  9128. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9129. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9130. this._collider = new BABYLON.Collider();
  9131. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9132. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9133. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9134. // Cache
  9135. this._localScaling = BABYLON.Matrix.Zero();
  9136. this._localRotation = BABYLON.Matrix.Zero();
  9137. this._localTranslation = BABYLON.Matrix.Zero();
  9138. this._localBillboard = BABYLON.Matrix.Zero();
  9139. this._localPivotScaling = BABYLON.Matrix.Zero();
  9140. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9141. this._localWorld = BABYLON.Matrix.Zero();
  9142. this._worldMatrix = BABYLON.Matrix.Zero();
  9143. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9144. this._absolutePosition = BABYLON.Vector3.Zero();
  9145. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9146. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9147. this._isDirty = false;
  9148. this._pivotMatrix = BABYLON.Matrix.Identity();
  9149. this._isDisposed = false;
  9150. this._renderId = 0;
  9151. this._intersectionsInProgress = new Array();
  9152. this._onAfterWorldMatrixUpdate = new Array();
  9153. scene.meshes.push(this);
  9154. }
  9155. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9156. get: function () {
  9157. return AbstractMesh._BILLBOARDMODE_NONE;
  9158. },
  9159. enumerable: true,
  9160. configurable: true
  9161. });
  9162. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9163. get: function () {
  9164. return AbstractMesh._BILLBOARDMODE_X;
  9165. },
  9166. enumerable: true,
  9167. configurable: true
  9168. });
  9169. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9170. get: function () {
  9171. return AbstractMesh._BILLBOARDMODE_Y;
  9172. },
  9173. enumerable: true,
  9174. configurable: true
  9175. });
  9176. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9177. get: function () {
  9178. return AbstractMesh._BILLBOARDMODE_Z;
  9179. },
  9180. enumerable: true,
  9181. configurable: true
  9182. });
  9183. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9184. get: function () {
  9185. return AbstractMesh._BILLBOARDMODE_ALL;
  9186. },
  9187. enumerable: true,
  9188. configurable: true
  9189. });
  9190. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9191. // Methods
  9192. get: function () {
  9193. return false;
  9194. },
  9195. enumerable: true,
  9196. configurable: true
  9197. });
  9198. AbstractMesh.prototype.getLOD = function (camera) {
  9199. return this;
  9200. };
  9201. AbstractMesh.prototype.getTotalVertices = function () {
  9202. return 0;
  9203. };
  9204. AbstractMesh.prototype.getIndices = function () {
  9205. return null;
  9206. };
  9207. AbstractMesh.prototype.getVerticesData = function (kind) {
  9208. return null;
  9209. };
  9210. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9211. return false;
  9212. };
  9213. AbstractMesh.prototype.getBoundingInfo = function () {
  9214. if (this._masterMesh) {
  9215. return this._masterMesh.getBoundingInfo();
  9216. }
  9217. if (!this._boundingInfo) {
  9218. this._updateBoundingInfo();
  9219. }
  9220. return this._boundingInfo;
  9221. };
  9222. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9223. get: function () {
  9224. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9225. },
  9226. enumerable: true,
  9227. configurable: true
  9228. });
  9229. AbstractMesh.prototype._preActivate = function () {
  9230. };
  9231. AbstractMesh.prototype._activate = function (renderId) {
  9232. this._renderId = renderId;
  9233. };
  9234. AbstractMesh.prototype.getWorldMatrix = function () {
  9235. if (this._masterMesh) {
  9236. return this._masterMesh.getWorldMatrix();
  9237. }
  9238. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9239. this.computeWorldMatrix();
  9240. }
  9241. return this._worldMatrix;
  9242. };
  9243. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9244. get: function () {
  9245. return this._worldMatrix;
  9246. },
  9247. enumerable: true,
  9248. configurable: true
  9249. });
  9250. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9251. get: function () {
  9252. return this._absolutePosition;
  9253. },
  9254. enumerable: true,
  9255. configurable: true
  9256. });
  9257. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9258. if (!this.rotationQuaternion) {
  9259. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9260. this.rotation = BABYLON.Vector3.Zero();
  9261. }
  9262. if (!space || space == 0 /* LOCAL */) {
  9263. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9264. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9265. }
  9266. else {
  9267. if (this.parent) {
  9268. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9269. invertParentWorldMatrix.invert();
  9270. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9271. }
  9272. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9273. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9274. }
  9275. };
  9276. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9277. var displacementVector = axis.scale(distance);
  9278. if (!space || space == 0 /* LOCAL */) {
  9279. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9280. this.setPositionWithLocalVector(tempV3);
  9281. }
  9282. else {
  9283. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9284. }
  9285. };
  9286. AbstractMesh.prototype.getAbsolutePosition = function () {
  9287. this.computeWorldMatrix();
  9288. return this._absolutePosition;
  9289. };
  9290. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9291. if (!absolutePosition) {
  9292. return;
  9293. }
  9294. var absolutePositionX;
  9295. var absolutePositionY;
  9296. var absolutePositionZ;
  9297. if (absolutePosition.x === undefined) {
  9298. if (arguments.length < 3) {
  9299. return;
  9300. }
  9301. absolutePositionX = arguments[0];
  9302. absolutePositionY = arguments[1];
  9303. absolutePositionZ = arguments[2];
  9304. }
  9305. else {
  9306. absolutePositionX = absolutePosition.x;
  9307. absolutePositionY = absolutePosition.y;
  9308. absolutePositionZ = absolutePosition.z;
  9309. }
  9310. if (this.parent) {
  9311. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9312. invertParentWorldMatrix.invert();
  9313. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9314. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9315. }
  9316. else {
  9317. this.position.x = absolutePositionX;
  9318. this.position.y = absolutePositionY;
  9319. this.position.z = absolutePositionZ;
  9320. }
  9321. };
  9322. // ================================== Point of View Movement =================================
  9323. /**
  9324. * Perform relative position change from the point of view of behind the front of the mesh.
  9325. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9326. * Supports definition of mesh facing forward or backward.
  9327. * @param {number} amountRight
  9328. * @param {number} amountUp
  9329. * @param {number} amountForward
  9330. */
  9331. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9332. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9333. };
  9334. /**
  9335. * Calculate relative position change from the point of view of behind the front of the mesh.
  9336. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9337. * Supports definition of mesh facing forward or backward.
  9338. * @param {number} amountRight
  9339. * @param {number} amountUp
  9340. * @param {number} amountForward
  9341. */
  9342. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9343. var rotMatrix = new BABYLON.Matrix();
  9344. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9345. rotQuaternion.toRotationMatrix(rotMatrix);
  9346. var translationDelta = BABYLON.Vector3.Zero();
  9347. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9348. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9349. return translationDelta;
  9350. };
  9351. // ================================== Point of View Rotation =================================
  9352. /**
  9353. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9354. * Supports definition of mesh facing forward or backward.
  9355. * @param {number} flipBack
  9356. * @param {number} twirlClockwise
  9357. * @param {number} tiltRight
  9358. */
  9359. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9360. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9361. };
  9362. /**
  9363. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9364. * Supports definition of mesh facing forward or backward.
  9365. * @param {number} flipBack
  9366. * @param {number} twirlClockwise
  9367. * @param {number} tiltRight
  9368. */
  9369. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9370. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9371. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9372. };
  9373. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9374. this._pivotMatrix = matrix;
  9375. this._cache.pivotMatrixUpdated = true;
  9376. };
  9377. AbstractMesh.prototype.getPivotMatrix = function () {
  9378. return this._pivotMatrix;
  9379. };
  9380. AbstractMesh.prototype._isSynchronized = function () {
  9381. if (this._isDirty) {
  9382. return false;
  9383. }
  9384. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9385. return false;
  9386. if (this._cache.pivotMatrixUpdated) {
  9387. return false;
  9388. }
  9389. if (this.infiniteDistance) {
  9390. return false;
  9391. }
  9392. if (!this._cache.position.equals(this.position))
  9393. return false;
  9394. if (this.rotationQuaternion) {
  9395. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9396. return false;
  9397. }
  9398. else {
  9399. if (!this._cache.rotation.equals(this.rotation))
  9400. return false;
  9401. }
  9402. if (!this._cache.scaling.equals(this.scaling))
  9403. return false;
  9404. return true;
  9405. };
  9406. AbstractMesh.prototype._initCache = function () {
  9407. _super.prototype._initCache.call(this);
  9408. this._cache.localMatrixUpdated = false;
  9409. this._cache.position = BABYLON.Vector3.Zero();
  9410. this._cache.scaling = BABYLON.Vector3.Zero();
  9411. this._cache.rotation = BABYLON.Vector3.Zero();
  9412. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9413. };
  9414. AbstractMesh.prototype.markAsDirty = function (property) {
  9415. if (property === "rotation") {
  9416. this.rotationQuaternion = null;
  9417. }
  9418. this._currentRenderId = Number.MAX_VALUE;
  9419. this._isDirty = true;
  9420. };
  9421. AbstractMesh.prototype._updateBoundingInfo = function () {
  9422. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9423. this._boundingInfo._update(this.worldMatrixFromCache);
  9424. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9425. };
  9426. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9427. if (!this.subMeshes) {
  9428. return;
  9429. }
  9430. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9431. var subMesh = this.subMeshes[subIndex];
  9432. subMesh.updateBoundingInfo(matrix);
  9433. }
  9434. };
  9435. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9436. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9437. return this._worldMatrix;
  9438. }
  9439. this._cache.position.copyFrom(this.position);
  9440. this._cache.scaling.copyFrom(this.scaling);
  9441. this._cache.pivotMatrixUpdated = false;
  9442. this._currentRenderId = this.getScene().getRenderId();
  9443. this._isDirty = false;
  9444. // Scaling
  9445. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9446. // Rotation
  9447. if (this.rotationQuaternion) {
  9448. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9449. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9450. }
  9451. else {
  9452. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9453. this._cache.rotation.copyFrom(this.rotation);
  9454. }
  9455. // Translation
  9456. if (this.infiniteDistance && !this.parent) {
  9457. var camera = this.getScene().activeCamera;
  9458. var cameraWorldMatrix = camera.getWorldMatrix();
  9459. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9460. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9461. }
  9462. else {
  9463. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9464. }
  9465. // Composing transformations
  9466. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9467. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9468. // Billboarding
  9469. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9470. var localPosition = this.position.clone();
  9471. var zero = this.getScene().activeCamera.position.clone();
  9472. if (this.parent && this.parent.position) {
  9473. localPosition.addInPlace(this.parent.position);
  9474. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9475. }
  9476. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9477. zero = this.getScene().activeCamera.position;
  9478. }
  9479. else {
  9480. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9481. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9482. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9483. zero.y = localPosition.y + 0.001;
  9484. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9485. zero.z = localPosition.z + 0.001;
  9486. }
  9487. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9488. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9489. this._localBillboard.invert();
  9490. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9491. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9492. }
  9493. // Local world
  9494. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9495. // Parent
  9496. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9497. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9498. }
  9499. else {
  9500. this._worldMatrix.copyFrom(this._localWorld);
  9501. }
  9502. // Bounding info
  9503. this._updateBoundingInfo();
  9504. // Absolute position
  9505. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9506. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9507. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9508. }
  9509. return this._worldMatrix;
  9510. };
  9511. /**
  9512. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9513. * @param func: callback function to add
  9514. */
  9515. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9516. this._onAfterWorldMatrixUpdate.push(func);
  9517. };
  9518. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9519. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  9520. if (index > -1) {
  9521. this._onAfterWorldMatrixUpdate.splice(index, 1);
  9522. }
  9523. };
  9524. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9525. this.computeWorldMatrix();
  9526. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9527. };
  9528. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9529. this.computeWorldMatrix();
  9530. var invLocalWorldMatrix = this._localWorld.clone();
  9531. invLocalWorldMatrix.invert();
  9532. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9533. };
  9534. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9535. this.computeWorldMatrix();
  9536. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9537. };
  9538. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9539. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9540. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9541. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9542. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9543. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9544. /// <returns>Mesh oriented towards targetMesh</returns>
  9545. yawCor = yawCor || 0; // default to zero if undefined
  9546. pitchCor = pitchCor || 0;
  9547. rollCor = rollCor || 0;
  9548. var dv = targetPoint.subtract(this.position);
  9549. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9550. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9551. var pitch = Math.atan2(dv.y, len);
  9552. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9553. };
  9554. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9555. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9556. return false;
  9557. }
  9558. return true;
  9559. };
  9560. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9561. if (!camera) {
  9562. camera = this.getScene().activeCamera;
  9563. }
  9564. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9565. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9566. return false;
  9567. }
  9568. return true;
  9569. };
  9570. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9571. if (!this._boundingInfo || !mesh._boundingInfo) {
  9572. return false;
  9573. }
  9574. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9575. };
  9576. AbstractMesh.prototype.intersectsPoint = function (point) {
  9577. if (!this._boundingInfo) {
  9578. return false;
  9579. }
  9580. return this._boundingInfo.intersectsPoint(point);
  9581. };
  9582. // Physics
  9583. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9584. var physicsEngine = this.getScene().getPhysicsEngine();
  9585. if (!physicsEngine) {
  9586. return;
  9587. }
  9588. if (impostor.impostor) {
  9589. // Old API
  9590. options = impostor;
  9591. impostor = impostor.impostor;
  9592. }
  9593. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9594. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9595. physicsEngine._unregisterMesh(this);
  9596. return;
  9597. }
  9598. options.mass = options.mass || 0;
  9599. options.friction = options.friction || 0.2;
  9600. options.restitution = options.restitution || 0.2;
  9601. this._physicImpostor = impostor;
  9602. this._physicsMass = options.mass;
  9603. this._physicsFriction = options.friction;
  9604. this._physicRestitution = options.restitution;
  9605. return physicsEngine._registerMesh(this, impostor, options);
  9606. };
  9607. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9608. if (!this._physicImpostor) {
  9609. return BABYLON.PhysicsEngine.NoImpostor;
  9610. }
  9611. return this._physicImpostor;
  9612. };
  9613. AbstractMesh.prototype.getPhysicsMass = function () {
  9614. if (!this._physicsMass) {
  9615. return 0;
  9616. }
  9617. return this._physicsMass;
  9618. };
  9619. AbstractMesh.prototype.getPhysicsFriction = function () {
  9620. if (!this._physicsFriction) {
  9621. return 0;
  9622. }
  9623. return this._physicsFriction;
  9624. };
  9625. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9626. if (!this._physicRestitution) {
  9627. return 0;
  9628. }
  9629. return this._physicRestitution;
  9630. };
  9631. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9632. if (!camera) {
  9633. camera = this.getScene().activeCamera;
  9634. }
  9635. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9636. };
  9637. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9638. if (!camera) {
  9639. camera = this.getScene().activeCamera;
  9640. }
  9641. return this.absolutePosition.subtract(camera.position).length();
  9642. };
  9643. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9644. if (!this._physicImpostor) {
  9645. return;
  9646. }
  9647. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9648. };
  9649. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9650. if (!this._physicImpostor) {
  9651. return;
  9652. }
  9653. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9654. };
  9655. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9656. if (!this._physicImpostor) {
  9657. return;
  9658. }
  9659. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9660. };
  9661. // Collisions
  9662. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9663. var globalPosition = this.getAbsolutePosition();
  9664. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9665. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9666. this._collider.radius = this.ellipsoid;
  9667. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  9668. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  9669. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9670. this.position.addInPlace(this._diffPositionForCollisions);
  9671. }
  9672. };
  9673. // Submeshes octree
  9674. /**
  9675. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9676. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9677. */
  9678. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9679. if (maxCapacity === void 0) { maxCapacity = 64; }
  9680. if (maxDepth === void 0) { maxDepth = 2; }
  9681. if (!this._submeshesOctree) {
  9682. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9683. }
  9684. this.computeWorldMatrix(true);
  9685. // Update octree
  9686. var bbox = this.getBoundingInfo().boundingBox;
  9687. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9688. return this._submeshesOctree;
  9689. };
  9690. // Collisions
  9691. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9692. this._generatePointsArray();
  9693. // Transformation
  9694. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9695. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9696. subMesh._lastColliderWorldVertices = [];
  9697. subMesh._trianglePlanes = [];
  9698. var start = subMesh.verticesStart;
  9699. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9700. for (var i = start; i < end; i++) {
  9701. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9702. }
  9703. }
  9704. // Collide
  9705. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  9706. };
  9707. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9708. var subMeshes;
  9709. var len;
  9710. // Octrees
  9711. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9712. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9713. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9714. len = intersections.length;
  9715. subMeshes = intersections.data;
  9716. }
  9717. else {
  9718. subMeshes = this.subMeshes;
  9719. len = subMeshes.length;
  9720. }
  9721. for (var index = 0; index < len; index++) {
  9722. var subMesh = subMeshes[index];
  9723. // Bounding test
  9724. if (len > 1 && !subMesh._checkCollision(collider))
  9725. continue;
  9726. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9727. }
  9728. };
  9729. AbstractMesh.prototype._checkCollision = function (collider) {
  9730. // Bounding box test
  9731. if (!this._boundingInfo._checkCollision(collider))
  9732. return;
  9733. // Transformation matrix
  9734. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9735. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9736. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9737. };
  9738. // Picking
  9739. AbstractMesh.prototype._generatePointsArray = function () {
  9740. return false;
  9741. };
  9742. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9743. var pickingInfo = new BABYLON.PickingInfo();
  9744. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9745. return pickingInfo;
  9746. }
  9747. if (!this._generatePointsArray()) {
  9748. return pickingInfo;
  9749. }
  9750. var intersectInfo = null;
  9751. // Octrees
  9752. var subMeshes;
  9753. var len;
  9754. if (this._submeshesOctree && this.useOctreeForPicking) {
  9755. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9756. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9757. len = intersections.length;
  9758. subMeshes = intersections.data;
  9759. }
  9760. else {
  9761. subMeshes = this.subMeshes;
  9762. len = subMeshes.length;
  9763. }
  9764. for (var index = 0; index < len; index++) {
  9765. var subMesh = subMeshes[index];
  9766. // Bounding test
  9767. if (len > 1 && !subMesh.canIntersects(ray))
  9768. continue;
  9769. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9770. if (currentIntersectInfo) {
  9771. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9772. intersectInfo = currentIntersectInfo;
  9773. if (fastCheck) {
  9774. break;
  9775. }
  9776. }
  9777. }
  9778. }
  9779. if (intersectInfo) {
  9780. // Get picked point
  9781. var world = this.getWorldMatrix();
  9782. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9783. var direction = ray.direction.clone();
  9784. direction = direction.scale(intersectInfo.distance);
  9785. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9786. var pickedPoint = worldOrigin.add(worldDirection);
  9787. // Return result
  9788. pickingInfo.hit = true;
  9789. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9790. pickingInfo.pickedPoint = pickedPoint;
  9791. pickingInfo.pickedMesh = this;
  9792. pickingInfo.bu = intersectInfo.bu;
  9793. pickingInfo.bv = intersectInfo.bv;
  9794. pickingInfo.faceId = intersectInfo.faceId;
  9795. return pickingInfo;
  9796. }
  9797. return pickingInfo;
  9798. };
  9799. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9800. return null;
  9801. };
  9802. AbstractMesh.prototype.releaseSubMeshes = function () {
  9803. if (this.subMeshes) {
  9804. while (this.subMeshes.length) {
  9805. this.subMeshes[0].dispose();
  9806. }
  9807. }
  9808. else {
  9809. this.subMeshes = new Array();
  9810. }
  9811. };
  9812. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9813. // Physics
  9814. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9815. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9816. }
  9817. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9818. var other = this._intersectionsInProgress[index];
  9819. var pos = other._intersectionsInProgress.indexOf(this);
  9820. other._intersectionsInProgress.splice(pos, 1);
  9821. }
  9822. this._intersectionsInProgress = [];
  9823. // SubMeshes
  9824. this.releaseSubMeshes();
  9825. // Remove from scene
  9826. var index = this.getScene().meshes.indexOf(this);
  9827. if (index != -1) {
  9828. // Remove from the scene if mesh found
  9829. this.getScene().meshes.splice(index, 1);
  9830. }
  9831. if (!doNotRecurse) {
  9832. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9833. if (this.getScene().particleSystems[index].emitter == this) {
  9834. this.getScene().particleSystems[index].dispose();
  9835. index--;
  9836. }
  9837. }
  9838. // Children
  9839. var objects = this.getScene().meshes.slice(0);
  9840. for (index = 0; index < objects.length; index++) {
  9841. if (objects[index].parent == this) {
  9842. objects[index].dispose();
  9843. }
  9844. }
  9845. }
  9846. else {
  9847. for (index = 0; index < this.getScene().meshes.length; index++) {
  9848. var obj = this.getScene().meshes[index];
  9849. if (obj.parent === this) {
  9850. obj.parent = null;
  9851. obj.computeWorldMatrix(true);
  9852. }
  9853. }
  9854. }
  9855. this._onAfterWorldMatrixUpdate = [];
  9856. this._isDisposed = true;
  9857. // Callback
  9858. if (this.onDispose) {
  9859. this.onDispose();
  9860. }
  9861. };
  9862. // Statics
  9863. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9864. AbstractMesh._BILLBOARDMODE_X = 1;
  9865. AbstractMesh._BILLBOARDMODE_Y = 2;
  9866. AbstractMesh._BILLBOARDMODE_Z = 4;
  9867. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9868. return AbstractMesh;
  9869. })(BABYLON.Node);
  9870. BABYLON.AbstractMesh = AbstractMesh;
  9871. })(BABYLON || (BABYLON = {}));
  9872. //# sourceMappingURL=babylon.abstractMesh.js.map
  9873. var BABYLON;
  9874. (function (BABYLON) {
  9875. var _InstancesBatch = (function () {
  9876. function _InstancesBatch() {
  9877. this.mustReturn = false;
  9878. this.visibleInstances = new Array();
  9879. this.renderSelf = new Array();
  9880. }
  9881. return _InstancesBatch;
  9882. })();
  9883. BABYLON._InstancesBatch = _InstancesBatch;
  9884. var Mesh = (function (_super) {
  9885. __extends(Mesh, _super);
  9886. /**
  9887. * @constructor
  9888. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9889. * @param {Scene} scene - The scene to add this mesh to.
  9890. * @param {Node} parent - The parent of this mesh, if it has one
  9891. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9892. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9893. * When false, achieved by calling a clone(), also passing False.
  9894. * This will make creation of children, recursive.
  9895. */
  9896. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9897. if (parent === void 0) { parent = null; }
  9898. _super.call(this, name, scene);
  9899. // Members
  9900. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9901. this.instances = new Array();
  9902. this._LODLevels = new Array();
  9903. this._onBeforeRenderCallbacks = new Array();
  9904. this._onAfterRenderCallbacks = new Array();
  9905. this._visibleInstances = {};
  9906. this._renderIdForInstances = new Array();
  9907. this._batchCache = new _InstancesBatch();
  9908. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  9909. if (source) {
  9910. // Geometry
  9911. if (source._geometry) {
  9912. source._geometry.applyToMesh(this);
  9913. }
  9914. // Deep copy
  9915. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9916. // Material
  9917. this.material = source.material;
  9918. if (!doNotCloneChildren) {
  9919. for (var index = 0; index < scene.meshes.length; index++) {
  9920. var mesh = scene.meshes[index];
  9921. if (mesh.parent === source) {
  9922. // doNotCloneChildren is always going to be False
  9923. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  9924. }
  9925. }
  9926. }
  9927. for (index = 0; index < scene.particleSystems.length; index++) {
  9928. var system = scene.particleSystems[index];
  9929. if (system.emitter === source) {
  9930. system.clone(system.name, this);
  9931. }
  9932. }
  9933. this.computeWorldMatrix(true);
  9934. }
  9935. // Parent
  9936. if (parent !== null) {
  9937. this.parent = parent;
  9938. }
  9939. }
  9940. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  9941. // Methods
  9942. get: function () {
  9943. return this._LODLevels.length > 0;
  9944. },
  9945. enumerable: true,
  9946. configurable: true
  9947. });
  9948. Mesh.prototype._sortLODLevels = function () {
  9949. this._LODLevels.sort(function (a, b) {
  9950. if (a.distance < b.distance) {
  9951. return 1;
  9952. }
  9953. if (a.distance > b.distance) {
  9954. return -1;
  9955. }
  9956. return 0;
  9957. });
  9958. };
  9959. /**
  9960. * Add a mesh as LOD level triggered at the given distance.
  9961. * @param {number} distance - the distance from the center of the object to show this level
  9962. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  9963. * @return {BABYLON.Mesh} this mesh (for chaining)
  9964. */
  9965. Mesh.prototype.addLODLevel = function (distance, mesh) {
  9966. if (mesh && mesh._masterMesh) {
  9967. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  9968. return this;
  9969. }
  9970. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  9971. this._LODLevels.push(level);
  9972. if (mesh) {
  9973. mesh._masterMesh = this;
  9974. }
  9975. this._sortLODLevels();
  9976. return this;
  9977. };
  9978. /**
  9979. * Remove a mesh from the LOD array
  9980. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  9981. * @return {BABYLON.Mesh} this mesh (for chaining)
  9982. */
  9983. Mesh.prototype.removeLODLevel = function (mesh) {
  9984. for (var index = 0; index < this._LODLevels.length; index++) {
  9985. if (this._LODLevels[index].mesh === mesh) {
  9986. this._LODLevels.splice(index, 1);
  9987. if (mesh) {
  9988. mesh._masterMesh = null;
  9989. }
  9990. }
  9991. }
  9992. this._sortLODLevels();
  9993. return this;
  9994. };
  9995. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9996. if (!this._LODLevels || this._LODLevels.length === 0) {
  9997. return this;
  9998. }
  9999. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10000. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10001. return this;
  10002. }
  10003. for (var index = 0; index < this._LODLevels.length; index++) {
  10004. var level = this._LODLevels[index];
  10005. if (level.distance < distanceToCamera) {
  10006. if (level.mesh) {
  10007. level.mesh._preActivate();
  10008. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10009. }
  10010. return level.mesh;
  10011. }
  10012. }
  10013. return this;
  10014. };
  10015. Object.defineProperty(Mesh.prototype, "geometry", {
  10016. get: function () {
  10017. return this._geometry;
  10018. },
  10019. enumerable: true,
  10020. configurable: true
  10021. });
  10022. Mesh.prototype.getTotalVertices = function () {
  10023. if (!this._geometry) {
  10024. return 0;
  10025. }
  10026. return this._geometry.getTotalVertices();
  10027. };
  10028. Mesh.prototype.getVerticesData = function (kind) {
  10029. if (!this._geometry) {
  10030. return null;
  10031. }
  10032. return this._geometry.getVerticesData(kind);
  10033. };
  10034. Mesh.prototype.getVertexBuffer = function (kind) {
  10035. if (!this._geometry) {
  10036. return undefined;
  10037. }
  10038. return this._geometry.getVertexBuffer(kind);
  10039. };
  10040. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10041. if (!this._geometry) {
  10042. if (this._delayInfo) {
  10043. return this._delayInfo.indexOf(kind) !== -1;
  10044. }
  10045. return false;
  10046. }
  10047. return this._geometry.isVerticesDataPresent(kind);
  10048. };
  10049. Mesh.prototype.getVerticesDataKinds = function () {
  10050. if (!this._geometry) {
  10051. var result = [];
  10052. if (this._delayInfo) {
  10053. for (var kind in this._delayInfo) {
  10054. result.push(kind);
  10055. }
  10056. }
  10057. return result;
  10058. }
  10059. return this._geometry.getVerticesDataKinds();
  10060. };
  10061. Mesh.prototype.getTotalIndices = function () {
  10062. if (!this._geometry) {
  10063. return 0;
  10064. }
  10065. return this._geometry.getTotalIndices();
  10066. };
  10067. Mesh.prototype.getIndices = function () {
  10068. if (!this._geometry) {
  10069. return [];
  10070. }
  10071. return this._geometry.getIndices();
  10072. };
  10073. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10074. get: function () {
  10075. return this._masterMesh !== null && this._masterMesh !== undefined;
  10076. },
  10077. enumerable: true,
  10078. configurable: true
  10079. });
  10080. Mesh.prototype.isReady = function () {
  10081. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10082. return false;
  10083. }
  10084. return _super.prototype.isReady.call(this);
  10085. };
  10086. Mesh.prototype.isDisposed = function () {
  10087. return this._isDisposed;
  10088. };
  10089. // Methods
  10090. Mesh.prototype._preActivate = function () {
  10091. var sceneRenderId = this.getScene().getRenderId();
  10092. if (this._preActivateId == sceneRenderId) {
  10093. return;
  10094. }
  10095. this._preActivateId = sceneRenderId;
  10096. this._visibleInstances = null;
  10097. };
  10098. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10099. if (!this._visibleInstances) {
  10100. this._visibleInstances = {};
  10101. this._visibleInstances.defaultRenderId = renderId;
  10102. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10103. }
  10104. if (!this._visibleInstances[renderId]) {
  10105. this._visibleInstances[renderId] = new Array();
  10106. }
  10107. this._visibleInstances[renderId].push(instance);
  10108. };
  10109. Mesh.prototype.refreshBoundingInfo = function () {
  10110. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10111. if (data) {
  10112. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10113. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10114. }
  10115. if (this.subMeshes) {
  10116. for (var index = 0; index < this.subMeshes.length; index++) {
  10117. this.subMeshes[index].refreshBoundingInfo();
  10118. }
  10119. }
  10120. this._updateBoundingInfo();
  10121. };
  10122. Mesh.prototype._createGlobalSubMesh = function () {
  10123. var totalVertices = this.getTotalVertices();
  10124. if (!totalVertices || !this.getIndices()) {
  10125. return null;
  10126. }
  10127. this.releaseSubMeshes();
  10128. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10129. };
  10130. Mesh.prototype.subdivide = function (count) {
  10131. if (count < 1) {
  10132. return;
  10133. }
  10134. var totalIndices = this.getTotalIndices();
  10135. var subdivisionSize = (totalIndices / count) | 0;
  10136. var offset = 0;
  10137. while (subdivisionSize % 3 != 0) {
  10138. subdivisionSize++;
  10139. }
  10140. this.releaseSubMeshes();
  10141. for (var index = 0; index < count; index++) {
  10142. if (offset >= totalIndices) {
  10143. break;
  10144. }
  10145. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10146. offset += subdivisionSize;
  10147. }
  10148. this.synchronizeInstances();
  10149. };
  10150. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10151. if (kind instanceof Array) {
  10152. var temp = data;
  10153. data = kind;
  10154. kind = temp;
  10155. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10156. }
  10157. if (!this._geometry) {
  10158. var vertexData = new BABYLON.VertexData();
  10159. vertexData.set(data, kind);
  10160. var scene = this.getScene();
  10161. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10162. }
  10163. else {
  10164. this._geometry.setVerticesData(kind, data, updatable, stride);
  10165. }
  10166. };
  10167. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10168. if (!this._geometry) {
  10169. return;
  10170. }
  10171. if (!makeItUnique) {
  10172. this._geometry.updateVerticesData(kind, data, updateExtends);
  10173. }
  10174. else {
  10175. this.makeGeometryUnique();
  10176. this.updateVerticesData(kind, data, updateExtends, false);
  10177. }
  10178. };
  10179. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10180. if (!this._geometry) {
  10181. return;
  10182. }
  10183. if (!makeItUnique) {
  10184. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10185. }
  10186. else {
  10187. this.makeGeometryUnique();
  10188. this.updateVerticesDataDirectly(kind, data, offset, false);
  10189. }
  10190. };
  10191. Mesh.prototype.makeGeometryUnique = function () {
  10192. if (!this._geometry) {
  10193. return;
  10194. }
  10195. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10196. geometry.applyToMesh(this);
  10197. };
  10198. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10199. if (!this._geometry) {
  10200. var vertexData = new BABYLON.VertexData();
  10201. vertexData.indices = indices;
  10202. var scene = this.getScene();
  10203. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10204. }
  10205. else {
  10206. this._geometry.setIndices(indices, totalVertices);
  10207. }
  10208. };
  10209. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10210. var engine = this.getScene().getEngine();
  10211. // Wireframe
  10212. var indexToBind;
  10213. switch (fillMode) {
  10214. case BABYLON.Material.PointFillMode:
  10215. indexToBind = null;
  10216. break;
  10217. case BABYLON.Material.WireFrameFillMode:
  10218. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10219. break;
  10220. default:
  10221. case BABYLON.Material.TriangleFillMode:
  10222. indexToBind = this._geometry.getIndexBuffer();
  10223. break;
  10224. }
  10225. // VBOs
  10226. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10227. };
  10228. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10229. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10230. return;
  10231. }
  10232. var engine = this.getScene().getEngine();
  10233. switch (fillMode) {
  10234. case BABYLON.Material.PointFillMode:
  10235. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10236. break;
  10237. case BABYLON.Material.WireFrameFillMode:
  10238. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10239. break;
  10240. default:
  10241. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10242. }
  10243. };
  10244. Mesh.prototype.registerBeforeRender = function (func) {
  10245. this._onBeforeRenderCallbacks.push(func);
  10246. };
  10247. Mesh.prototype.unregisterBeforeRender = function (func) {
  10248. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10249. if (index > -1) {
  10250. this._onBeforeRenderCallbacks.splice(index, 1);
  10251. }
  10252. };
  10253. Mesh.prototype.registerAfterRender = function (func) {
  10254. this._onAfterRenderCallbacks.push(func);
  10255. };
  10256. Mesh.prototype.unregisterAfterRender = function (func) {
  10257. var index = this._onAfterRenderCallbacks.indexOf(func);
  10258. if (index > -1) {
  10259. this._onAfterRenderCallbacks.splice(index, 1);
  10260. }
  10261. };
  10262. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10263. var scene = this.getScene();
  10264. this._batchCache.mustReturn = false;
  10265. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10266. this._batchCache.visibleInstances[subMeshId] = null;
  10267. if (this._visibleInstances) {
  10268. var currentRenderId = scene.getRenderId();
  10269. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10270. var selfRenderId = this._renderId;
  10271. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10272. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10273. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10274. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10275. }
  10276. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10277. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10278. this._batchCache.mustReturn = true;
  10279. return this._batchCache;
  10280. }
  10281. if (currentRenderId !== selfRenderId) {
  10282. this._batchCache.renderSelf[subMeshId] = false;
  10283. }
  10284. }
  10285. this._renderIdForInstances[subMeshId] = currentRenderId;
  10286. }
  10287. return this._batchCache;
  10288. };
  10289. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10290. var visibleInstances = batch.visibleInstances[subMesh._id];
  10291. var matricesCount = visibleInstances.length + 1;
  10292. var bufferSize = matricesCount * 16 * 4;
  10293. while (this._instancesBufferSize < bufferSize) {
  10294. this._instancesBufferSize *= 2;
  10295. }
  10296. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10297. if (this._worldMatricesInstancesBuffer) {
  10298. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10299. }
  10300. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10301. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10302. }
  10303. var offset = 0;
  10304. var instancesCount = 0;
  10305. var world = this.getWorldMatrix();
  10306. if (batch.renderSelf[subMesh._id]) {
  10307. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10308. offset += 16;
  10309. instancesCount++;
  10310. }
  10311. if (visibleInstances) {
  10312. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10313. var instance = visibleInstances[instanceIndex];
  10314. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10315. offset += 16;
  10316. instancesCount++;
  10317. }
  10318. }
  10319. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10320. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10321. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10322. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10323. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10324. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10325. this._draw(subMesh, fillMode, instancesCount);
  10326. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10327. };
  10328. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  10329. var scene = this.getScene();
  10330. var engine = scene.getEngine();
  10331. if (hardwareInstancedRendering) {
  10332. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10333. }
  10334. else {
  10335. if (batch.renderSelf[subMesh._id]) {
  10336. // Draw
  10337. if (onBeforeDraw) {
  10338. onBeforeDraw(false, this.getWorldMatrix());
  10339. }
  10340. this._draw(subMesh, fillMode);
  10341. }
  10342. if (batch.visibleInstances[subMesh._id]) {
  10343. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10344. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10345. // World
  10346. var world = instance.getWorldMatrix();
  10347. if (onBeforeDraw) {
  10348. onBeforeDraw(true, world);
  10349. }
  10350. // Draw
  10351. this._draw(subMesh, fillMode);
  10352. }
  10353. }
  10354. }
  10355. };
  10356. Mesh.prototype.render = function (subMesh) {
  10357. var scene = this.getScene();
  10358. // Managing instances
  10359. var batch = this._getInstancesRenderList(subMesh._id);
  10360. if (batch.mustReturn) {
  10361. return;
  10362. }
  10363. // Checking geometry state
  10364. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10365. return;
  10366. }
  10367. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10368. this._onBeforeRenderCallbacks[callbackIndex]();
  10369. }
  10370. var engine = scene.getEngine();
  10371. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10372. // Material
  10373. var effectiveMaterial = subMesh.getMaterial();
  10374. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10375. return;
  10376. }
  10377. // Outline - step 1
  10378. var savedDepthWrite = engine.getDepthWrite();
  10379. if (this.renderOutline) {
  10380. engine.setDepthWrite(false);
  10381. scene.getOutlineRenderer().render(subMesh, batch);
  10382. engine.setDepthWrite(savedDepthWrite);
  10383. }
  10384. effectiveMaterial._preBind();
  10385. var effect = effectiveMaterial.getEffect();
  10386. // Bind
  10387. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10388. this._bind(subMesh, effect, fillMode);
  10389. var world = this.getWorldMatrix();
  10390. effectiveMaterial.bind(world, this);
  10391. // Draw
  10392. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  10393. if (isInstance) {
  10394. effectiveMaterial.bindOnlyWorldMatrix(world);
  10395. }
  10396. });
  10397. // Unbind
  10398. effectiveMaterial.unbind();
  10399. // Outline - step 2
  10400. if (this.renderOutline && savedDepthWrite) {
  10401. engine.setDepthWrite(true);
  10402. engine.setColorWrite(false);
  10403. scene.getOutlineRenderer().render(subMesh, batch);
  10404. engine.setColorWrite(true);
  10405. }
  10406. // Overlay
  10407. if (this.renderOverlay) {
  10408. var currentMode = engine.getAlphaMode();
  10409. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10410. scene.getOutlineRenderer().render(subMesh, batch, true);
  10411. engine.setAlphaMode(currentMode);
  10412. }
  10413. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10414. this._onAfterRenderCallbacks[callbackIndex]();
  10415. }
  10416. };
  10417. Mesh.prototype.getEmittedParticleSystems = function () {
  10418. var results = new Array();
  10419. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10420. var particleSystem = this.getScene().particleSystems[index];
  10421. if (particleSystem.emitter === this) {
  10422. results.push(particleSystem);
  10423. }
  10424. }
  10425. return results;
  10426. };
  10427. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10428. var results = new Array();
  10429. var descendants = this.getDescendants();
  10430. descendants.push(this);
  10431. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10432. var particleSystem = this.getScene().particleSystems[index];
  10433. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10434. results.push(particleSystem);
  10435. }
  10436. }
  10437. return results;
  10438. };
  10439. Mesh.prototype.getChildren = function () {
  10440. var results = [];
  10441. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10442. var mesh = this.getScene().meshes[index];
  10443. if (mesh.parent === this) {
  10444. results.push(mesh);
  10445. }
  10446. }
  10447. return results;
  10448. };
  10449. Mesh.prototype._checkDelayState = function () {
  10450. var _this = this;
  10451. var that = this;
  10452. var scene = this.getScene();
  10453. if (this._geometry) {
  10454. this._geometry.load(scene);
  10455. }
  10456. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10457. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10458. scene._addPendingData(that);
  10459. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  10460. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  10461. if (data instanceof ArrayBuffer) {
  10462. _this._delayLoadingFunction(data, _this);
  10463. }
  10464. else {
  10465. _this._delayLoadingFunction(JSON.parse(data), _this);
  10466. }
  10467. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10468. scene._removePendingData(_this);
  10469. }, function () {
  10470. }, scene.database, getBinaryData);
  10471. }
  10472. };
  10473. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  10474. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10475. return false;
  10476. }
  10477. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  10478. return false;
  10479. }
  10480. this._checkDelayState();
  10481. return true;
  10482. };
  10483. Mesh.prototype.setMaterialByID = function (id) {
  10484. var materials = this.getScene().materials;
  10485. for (var index = 0; index < materials.length; index++) {
  10486. if (materials[index].id === id) {
  10487. this.material = materials[index];
  10488. return;
  10489. }
  10490. }
  10491. // Multi
  10492. var multiMaterials = this.getScene().multiMaterials;
  10493. for (index = 0; index < multiMaterials.length; index++) {
  10494. if (multiMaterials[index].id === id) {
  10495. this.material = multiMaterials[index];
  10496. return;
  10497. }
  10498. }
  10499. };
  10500. Mesh.prototype.getAnimatables = function () {
  10501. var results = [];
  10502. if (this.material) {
  10503. results.push(this.material);
  10504. }
  10505. if (this.skeleton) {
  10506. results.push(this.skeleton);
  10507. }
  10508. return results;
  10509. };
  10510. // Geometry
  10511. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  10512. // Position
  10513. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  10514. return;
  10515. }
  10516. this._resetPointsArrayCache();
  10517. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10518. var temp = [];
  10519. for (var index = 0; index < data.length; index += 3) {
  10520. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10521. }
  10522. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  10523. // Normals
  10524. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  10525. return;
  10526. }
  10527. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10528. for (index = 0; index < data.length; index += 3) {
  10529. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10530. }
  10531. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  10532. };
  10533. // Cache
  10534. Mesh.prototype._resetPointsArrayCache = function () {
  10535. this._positions = null;
  10536. };
  10537. Mesh.prototype._generatePointsArray = function () {
  10538. if (this._positions)
  10539. return true;
  10540. this._positions = [];
  10541. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10542. if (!data) {
  10543. return false;
  10544. }
  10545. for (var index = 0; index < data.length; index += 3) {
  10546. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  10547. }
  10548. return true;
  10549. };
  10550. // Clone
  10551. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10552. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  10553. };
  10554. // Dispose
  10555. Mesh.prototype.dispose = function (doNotRecurse) {
  10556. if (this._geometry) {
  10557. this._geometry.releaseForMesh(this, true);
  10558. }
  10559. // Instances
  10560. if (this._worldMatricesInstancesBuffer) {
  10561. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10562. this._worldMatricesInstancesBuffer = null;
  10563. }
  10564. while (this.instances.length) {
  10565. this.instances[0].dispose();
  10566. }
  10567. _super.prototype.dispose.call(this, doNotRecurse);
  10568. };
  10569. // Geometric tools
  10570. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  10571. var _this = this;
  10572. var scene = this.getScene();
  10573. var onload = function (img) {
  10574. // Getting height map data
  10575. var canvas = document.createElement("canvas");
  10576. var context = canvas.getContext("2d");
  10577. var heightMapWidth = img.width;
  10578. var heightMapHeight = img.height;
  10579. canvas.width = heightMapWidth;
  10580. canvas.height = heightMapHeight;
  10581. context.drawImage(img, 0, 0);
  10582. // Create VertexData from map data
  10583. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10584. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  10585. //execute success callback, if set
  10586. if (onSuccess) {
  10587. onSuccess(_this);
  10588. }
  10589. };
  10590. BABYLON.Tools.LoadImage(url, onload, function () {
  10591. }, scene.database);
  10592. };
  10593. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  10594. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10595. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  10596. return;
  10597. }
  10598. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10599. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10600. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  10601. var position = BABYLON.Vector3.Zero();
  10602. var normal = BABYLON.Vector3.Zero();
  10603. var uv = BABYLON.Vector2.Zero();
  10604. for (var index = 0; index < positions.length; index += 3) {
  10605. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  10606. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  10607. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  10608. // Compute height
  10609. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  10610. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  10611. var pos = (u + v * heightMapWidth) * 4;
  10612. var r = buffer[pos] / 255.0;
  10613. var g = buffer[pos + 1] / 255.0;
  10614. var b = buffer[pos + 2] / 255.0;
  10615. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  10616. normal.normalize();
  10617. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  10618. position = position.add(normal);
  10619. position.toArray(positions, index);
  10620. }
  10621. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  10622. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  10623. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  10624. };
  10625. Mesh.prototype.convertToFlatShadedMesh = function () {
  10626. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  10627. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  10628. var kinds = this.getVerticesDataKinds();
  10629. var vbs = [];
  10630. var data = [];
  10631. var newdata = [];
  10632. var updatableNormals = false;
  10633. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10634. var kind = kinds[kindIndex];
  10635. var vertexBuffer = this.getVertexBuffer(kind);
  10636. if (kind === BABYLON.VertexBuffer.NormalKind) {
  10637. updatableNormals = vertexBuffer.isUpdatable();
  10638. kinds.splice(kindIndex, 1);
  10639. kindIndex--;
  10640. continue;
  10641. }
  10642. vbs[kind] = vertexBuffer;
  10643. data[kind] = vbs[kind].getData();
  10644. newdata[kind] = [];
  10645. }
  10646. // Save previous submeshes
  10647. var previousSubmeshes = this.subMeshes.slice(0);
  10648. var indices = this.getIndices();
  10649. var totalIndices = this.getTotalIndices();
  10650. for (var index = 0; index < totalIndices; index++) {
  10651. var vertexIndex = indices[index];
  10652. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10653. kind = kinds[kindIndex];
  10654. var stride = vbs[kind].getStrideSize();
  10655. for (var offset = 0; offset < stride; offset++) {
  10656. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  10657. }
  10658. }
  10659. }
  10660. // Updating faces & normal
  10661. var normals = [];
  10662. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  10663. for (index = 0; index < totalIndices; index += 3) {
  10664. indices[index] = index;
  10665. indices[index + 1] = index + 1;
  10666. indices[index + 2] = index + 2;
  10667. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  10668. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  10669. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  10670. var p1p2 = p1.subtract(p2);
  10671. var p3p2 = p3.subtract(p2);
  10672. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  10673. for (var localIndex = 0; localIndex < 3; localIndex++) {
  10674. normals.push(normal.x);
  10675. normals.push(normal.y);
  10676. normals.push(normal.z);
  10677. }
  10678. }
  10679. this.setIndices(indices);
  10680. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  10681. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10682. kind = kinds[kindIndex];
  10683. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  10684. }
  10685. // Updating submeshes
  10686. this.releaseSubMeshes();
  10687. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  10688. var previousOne = previousSubmeshes[submeshIndex];
  10689. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  10690. }
  10691. this.synchronizeInstances();
  10692. };
  10693. // Instances
  10694. Mesh.prototype.createInstance = function (name) {
  10695. return new BABYLON.InstancedMesh(name, this);
  10696. };
  10697. Mesh.prototype.synchronizeInstances = function () {
  10698. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  10699. var instance = this.instances[instanceIndex];
  10700. instance._syncSubMeshes();
  10701. }
  10702. };
  10703. /**
  10704. * Simplify the mesh according to the given array of settings.
  10705. * Function will return immediately and will simplify async.
  10706. * @param settings a collection of simplification settings.
  10707. * @param parallelProcessing should all levels calculate parallel or one after the other.
  10708. * @param type the type of simplification to run.
  10709. * successCallback optional success callback to be called after the simplification finished processing all settings.
  10710. */
  10711. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  10712. var _this = this;
  10713. if (parallelProcessing === void 0) { parallelProcessing = true; }
  10714. if (type === void 0) { type = 0 /* QUADRATIC */; }
  10715. var getSimplifier = function () {
  10716. switch (type) {
  10717. case 0 /* QUADRATIC */:
  10718. default:
  10719. return new BABYLON.QuadraticErrorSimplification(_this);
  10720. }
  10721. };
  10722. if (parallelProcessing) {
  10723. //parallel simplifier
  10724. settings.forEach(function (setting) {
  10725. var simplifier = getSimplifier();
  10726. simplifier.simplify(setting, function (newMesh) {
  10727. _this.addLODLevel(setting.distance, newMesh);
  10728. //check if it is the last
  10729. if (setting.quality === settings[settings.length - 1].quality && successCallback) {
  10730. //all done, run the success callback.
  10731. successCallback();
  10732. }
  10733. });
  10734. });
  10735. }
  10736. else {
  10737. //single simplifier.
  10738. var simplifier = getSimplifier();
  10739. var runDecimation = function (setting, callback) {
  10740. simplifier.simplify(setting, function (newMesh) {
  10741. _this.addLODLevel(setting.distance, newMesh);
  10742. //run the next quality level
  10743. callback();
  10744. });
  10745. };
  10746. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  10747. runDecimation(settings[loop.index], function () {
  10748. loop.executeNext();
  10749. });
  10750. }, function () {
  10751. //execution ended, run the success callback.
  10752. if (successCallback) {
  10753. successCallback();
  10754. }
  10755. });
  10756. }
  10757. };
  10758. // Statics
  10759. Mesh.CreateBox = function (name, size, scene, updatable) {
  10760. var box = new Mesh(name, scene);
  10761. var vertexData = BABYLON.VertexData.CreateBox(size);
  10762. vertexData.applyToMesh(box, updatable);
  10763. return box;
  10764. };
  10765. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  10766. var sphere = new Mesh(name, scene);
  10767. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  10768. vertexData.applyToMesh(sphere, updatable);
  10769. return sphere;
  10770. };
  10771. // Cylinder and cone (Code inspired by SharpDX.org)
  10772. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  10773. // subdivisions is a new parameter, we need to support old signature
  10774. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  10775. if (scene !== undefined) {
  10776. updatable = scene;
  10777. }
  10778. scene = subdivisions;
  10779. subdivisions = 1;
  10780. }
  10781. var cylinder = new Mesh(name, scene);
  10782. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  10783. vertexData.applyToMesh(cylinder, updatable);
  10784. return cylinder;
  10785. };
  10786. // Torus (Code from SharpDX.org)
  10787. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  10788. var torus = new Mesh(name, scene);
  10789. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  10790. vertexData.applyToMesh(torus, updatable);
  10791. return torus;
  10792. };
  10793. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  10794. var torusKnot = new Mesh(name, scene);
  10795. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  10796. vertexData.applyToMesh(torusKnot, updatable);
  10797. return torusKnot;
  10798. };
  10799. // Lines
  10800. Mesh.CreateLines = function (name, points, scene, updatable) {
  10801. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  10802. var vertexData = BABYLON.VertexData.CreateLines(points);
  10803. vertexData.applyToMesh(lines, updatable);
  10804. return lines;
  10805. };
  10806. // Plane & ground
  10807. Mesh.CreatePlane = function (name, size, scene, updatable) {
  10808. var plane = new Mesh(name, scene);
  10809. var vertexData = BABYLON.VertexData.CreatePlane(size);
  10810. vertexData.applyToMesh(plane, updatable);
  10811. return plane;
  10812. };
  10813. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10814. var ground = new BABYLON.GroundMesh(name, scene);
  10815. ground._setReady(false);
  10816. ground._subdivisions = subdivisions;
  10817. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10818. vertexData.applyToMesh(ground, updatable);
  10819. ground._setReady(true);
  10820. return ground;
  10821. };
  10822. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10823. var tiledGround = new Mesh(name, scene);
  10824. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10825. vertexData.applyToMesh(tiledGround, updatable);
  10826. return tiledGround;
  10827. };
  10828. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  10829. var ground = new BABYLON.GroundMesh(name, scene);
  10830. ground._subdivisions = subdivisions;
  10831. ground._setReady(false);
  10832. var onload = function (img) {
  10833. // Getting height map data
  10834. var canvas = document.createElement("canvas");
  10835. var context = canvas.getContext("2d");
  10836. var heightMapWidth = img.width;
  10837. var heightMapHeight = img.height;
  10838. canvas.width = heightMapWidth;
  10839. canvas.height = heightMapHeight;
  10840. context.drawImage(img, 0, 0);
  10841. // Create VertexData from map data
  10842. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10843. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10844. vertexData.applyToMesh(ground, updatable);
  10845. ground._setReady(true);
  10846. //execute ready callback, if set
  10847. if (onReady) {
  10848. onReady(ground);
  10849. }
  10850. };
  10851. BABYLON.Tools.LoadImage(url, onload, function () {
  10852. }, scene.database);
  10853. return ground;
  10854. };
  10855. // Tools
  10856. Mesh.MinMax = function (meshes) {
  10857. var minVector = null;
  10858. var maxVector = null;
  10859. for (var i in meshes) {
  10860. var mesh = meshes[i];
  10861. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10862. if (!minVector) {
  10863. minVector = boundingBox.minimumWorld;
  10864. maxVector = boundingBox.maximumWorld;
  10865. continue;
  10866. }
  10867. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10868. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10869. }
  10870. return {
  10871. min: minVector,
  10872. max: maxVector
  10873. };
  10874. };
  10875. Mesh.Center = function (meshesOrMinMaxVector) {
  10876. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  10877. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10878. };
  10879. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10880. if (disposeSource === void 0) { disposeSource = true; }
  10881. var source = meshes[0];
  10882. var material = source.material;
  10883. var scene = source.getScene();
  10884. if (!allow32BitsIndices) {
  10885. var totalVertices = 0;
  10886. for (var index = 0; index < meshes.length; index++) {
  10887. totalVertices += meshes[index].getTotalVertices();
  10888. if (totalVertices > 65536) {
  10889. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  10890. return null;
  10891. }
  10892. }
  10893. }
  10894. // Merge
  10895. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  10896. vertexData.transform(source.getWorldMatrix());
  10897. for (index = 1; index < meshes.length; index++) {
  10898. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  10899. otherVertexData.transform(meshes[index].getWorldMatrix());
  10900. vertexData.merge(otherVertexData);
  10901. }
  10902. var newMesh = new Mesh(source.name + "_merged", scene);
  10903. vertexData.applyToMesh(newMesh);
  10904. // Setting properties
  10905. newMesh.material = material;
  10906. newMesh.checkCollisions = source.checkCollisions;
  10907. // Cleaning
  10908. if (disposeSource) {
  10909. for (index = 0; index < meshes.length; index++) {
  10910. meshes[index].dispose();
  10911. }
  10912. }
  10913. return newMesh;
  10914. };
  10915. return Mesh;
  10916. })(BABYLON.AbstractMesh);
  10917. BABYLON.Mesh = Mesh;
  10918. })(BABYLON || (BABYLON = {}));
  10919. //# sourceMappingURL=babylon.mesh.js.map
  10920. var BABYLON;
  10921. (function (BABYLON) {
  10922. var GroundMesh = (function (_super) {
  10923. __extends(GroundMesh, _super);
  10924. function GroundMesh(name, scene) {
  10925. _super.call(this, name, scene);
  10926. this.generateOctree = false;
  10927. this._worldInverse = new BABYLON.Matrix();
  10928. }
  10929. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  10930. get: function () {
  10931. return this._subdivisions;
  10932. },
  10933. enumerable: true,
  10934. configurable: true
  10935. });
  10936. GroundMesh.prototype.optimize = function (chunksCount) {
  10937. this.subdivide(this._subdivisions);
  10938. this.createOrUpdateSubmeshesOctree(32);
  10939. };
  10940. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  10941. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  10942. this.getWorldMatrix().invertToRef(this._worldInverse);
  10943. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  10944. var pickInfo = this.intersects(ray);
  10945. if (pickInfo.hit) {
  10946. return pickInfo.pickedPoint.y;
  10947. }
  10948. return 0;
  10949. };
  10950. return GroundMesh;
  10951. })(BABYLON.Mesh);
  10952. BABYLON.GroundMesh = GroundMesh;
  10953. })(BABYLON || (BABYLON = {}));
  10954. //# sourceMappingURL=babylon.groundMesh.js.map
  10955. var BABYLON;
  10956. (function (BABYLON) {
  10957. /**
  10958. * Creates an instance based on a source mesh.
  10959. */
  10960. var InstancedMesh = (function (_super) {
  10961. __extends(InstancedMesh, _super);
  10962. function InstancedMesh(name, source) {
  10963. _super.call(this, name, source.getScene());
  10964. source.instances.push(this);
  10965. this._sourceMesh = source;
  10966. this.position.copyFrom(source.position);
  10967. this.rotation.copyFrom(source.rotation);
  10968. this.scaling.copyFrom(source.scaling);
  10969. if (source.rotationQuaternion) {
  10970. this.rotationQuaternion = source.rotationQuaternion.clone();
  10971. }
  10972. this.infiniteDistance = source.infiniteDistance;
  10973. this.setPivotMatrix(source.getPivotMatrix());
  10974. this.refreshBoundingInfo();
  10975. this._syncSubMeshes();
  10976. }
  10977. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  10978. // Methods
  10979. get: function () {
  10980. return this._sourceMesh.receiveShadows;
  10981. },
  10982. enumerable: true,
  10983. configurable: true
  10984. });
  10985. Object.defineProperty(InstancedMesh.prototype, "material", {
  10986. get: function () {
  10987. return this._sourceMesh.material;
  10988. },
  10989. enumerable: true,
  10990. configurable: true
  10991. });
  10992. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  10993. get: function () {
  10994. return this._sourceMesh.visibility;
  10995. },
  10996. enumerable: true,
  10997. configurable: true
  10998. });
  10999. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11000. get: function () {
  11001. return this._sourceMesh.skeleton;
  11002. },
  11003. enumerable: true,
  11004. configurable: true
  11005. });
  11006. InstancedMesh.prototype.getTotalVertices = function () {
  11007. return this._sourceMesh.getTotalVertices();
  11008. };
  11009. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11010. get: function () {
  11011. return this._sourceMesh;
  11012. },
  11013. enumerable: true,
  11014. configurable: true
  11015. });
  11016. InstancedMesh.prototype.getVerticesData = function (kind) {
  11017. return this._sourceMesh.getVerticesData(kind);
  11018. };
  11019. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11020. return this._sourceMesh.isVerticesDataPresent(kind);
  11021. };
  11022. InstancedMesh.prototype.getIndices = function () {
  11023. return this._sourceMesh.getIndices();
  11024. };
  11025. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11026. get: function () {
  11027. return this._sourceMesh._positions;
  11028. },
  11029. enumerable: true,
  11030. configurable: true
  11031. });
  11032. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11033. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11034. if (data) {
  11035. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11036. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11037. }
  11038. this._updateBoundingInfo();
  11039. };
  11040. InstancedMesh.prototype._preActivate = function () {
  11041. if (this._currentLOD) {
  11042. this._currentLOD._preActivate();
  11043. }
  11044. };
  11045. InstancedMesh.prototype._activate = function (renderId) {
  11046. if (this._currentLOD) {
  11047. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11048. }
  11049. };
  11050. InstancedMesh.prototype.getLOD = function (camera) {
  11051. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11052. if (this._currentLOD === this.sourceMesh) {
  11053. return this;
  11054. }
  11055. return this._currentLOD;
  11056. };
  11057. InstancedMesh.prototype._syncSubMeshes = function () {
  11058. this.releaseSubMeshes();
  11059. if (this._sourceMesh.subMeshes) {
  11060. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11061. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11062. }
  11063. }
  11064. };
  11065. InstancedMesh.prototype._generatePointsArray = function () {
  11066. return this._sourceMesh._generatePointsArray();
  11067. };
  11068. // Clone
  11069. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11070. var result = this._sourceMesh.createInstance(name);
  11071. // Deep copy
  11072. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11073. // Bounding info
  11074. this.refreshBoundingInfo();
  11075. // Parent
  11076. if (newParent) {
  11077. result.parent = newParent;
  11078. }
  11079. if (!doNotCloneChildren) {
  11080. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11081. var mesh = this.getScene().meshes[index];
  11082. if (mesh.parent === this) {
  11083. mesh.clone(mesh.name, result);
  11084. }
  11085. }
  11086. }
  11087. result.computeWorldMatrix(true);
  11088. return result;
  11089. };
  11090. // Dispoe
  11091. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11092. // Remove from mesh
  11093. var index = this._sourceMesh.instances.indexOf(this);
  11094. this._sourceMesh.instances.splice(index, 1);
  11095. _super.prototype.dispose.call(this, doNotRecurse);
  11096. };
  11097. return InstancedMesh;
  11098. })(BABYLON.AbstractMesh);
  11099. BABYLON.InstancedMesh = InstancedMesh;
  11100. })(BABYLON || (BABYLON = {}));
  11101. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  11102. (function (BABYLON) {
  11103. var SubMesh = (function () {
  11104. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  11105. if (createBoundingBox === void 0) { createBoundingBox = true; }
  11106. this.materialIndex = materialIndex;
  11107. this.verticesStart = verticesStart;
  11108. this.verticesCount = verticesCount;
  11109. this.indexStart = indexStart;
  11110. this.indexCount = indexCount;
  11111. this._renderId = 0;
  11112. this._mesh = mesh;
  11113. this._renderingMesh = renderingMesh || mesh;
  11114. mesh.subMeshes.push(this);
  11115. this._id = mesh.subMeshes.length - 1;
  11116. if (createBoundingBox) {
  11117. this.refreshBoundingInfo();
  11118. }
  11119. }
  11120. SubMesh.prototype.getBoundingInfo = function () {
  11121. return this._boundingInfo;
  11122. };
  11123. SubMesh.prototype.getMesh = function () {
  11124. return this._mesh;
  11125. };
  11126. SubMesh.prototype.getRenderingMesh = function () {
  11127. return this._renderingMesh;
  11128. };
  11129. SubMesh.prototype.getMaterial = function () {
  11130. var rootMaterial = this._renderingMesh.material;
  11131. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11132. var multiMaterial = rootMaterial;
  11133. return multiMaterial.getSubMaterial(this.materialIndex);
  11134. }
  11135. if (!rootMaterial) {
  11136. return this._mesh.getScene().defaultMaterial;
  11137. }
  11138. return rootMaterial;
  11139. };
  11140. // Methods
  11141. SubMesh.prototype.refreshBoundingInfo = function () {
  11142. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11143. if (!data) {
  11144. this._boundingInfo = this._mesh._boundingInfo;
  11145. return;
  11146. }
  11147. var indices = this._renderingMesh.getIndices();
  11148. var extend;
  11149. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11150. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11151. }
  11152. else {
  11153. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11154. }
  11155. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11156. };
  11157. SubMesh.prototype._checkCollision = function (collider) {
  11158. return this._boundingInfo._checkCollision(collider);
  11159. };
  11160. SubMesh.prototype.updateBoundingInfo = function (world) {
  11161. if (!this._boundingInfo) {
  11162. this.refreshBoundingInfo();
  11163. }
  11164. this._boundingInfo._update(world);
  11165. };
  11166. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11167. return this._boundingInfo.isInFrustum(frustumPlanes);
  11168. };
  11169. SubMesh.prototype.render = function () {
  11170. this._renderingMesh.render(this);
  11171. };
  11172. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11173. if (!this._linesIndexBuffer) {
  11174. var linesIndices = [];
  11175. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11176. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11177. }
  11178. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11179. this.linesIndexCount = linesIndices.length;
  11180. }
  11181. return this._linesIndexBuffer;
  11182. };
  11183. SubMesh.prototype.canIntersects = function (ray) {
  11184. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11185. };
  11186. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11187. var intersectInfo = null;
  11188. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11189. var p0 = positions[indices[index]];
  11190. var p1 = positions[indices[index + 1]];
  11191. var p2 = positions[indices[index + 2]];
  11192. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11193. if (currentIntersectInfo) {
  11194. if (currentIntersectInfo.distance < 0) {
  11195. continue;
  11196. }
  11197. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11198. intersectInfo = currentIntersectInfo;
  11199. intersectInfo.faceId = index / 3;
  11200. if (fastCheck) {
  11201. break;
  11202. }
  11203. }
  11204. }
  11205. }
  11206. return intersectInfo;
  11207. };
  11208. // Clone
  11209. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11210. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11211. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11212. return result;
  11213. };
  11214. // Dispose
  11215. SubMesh.prototype.dispose = function () {
  11216. if (this._linesIndexBuffer) {
  11217. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11218. this._linesIndexBuffer = null;
  11219. }
  11220. // Remove from mesh
  11221. var index = this._mesh.subMeshes.indexOf(this);
  11222. this._mesh.subMeshes.splice(index, 1);
  11223. };
  11224. // Statics
  11225. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11226. var minVertexIndex = Number.MAX_VALUE;
  11227. var maxVertexIndex = -Number.MAX_VALUE;
  11228. renderingMesh = renderingMesh || mesh;
  11229. var indices = renderingMesh.getIndices();
  11230. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11231. var vertexIndex = indices[index];
  11232. if (vertexIndex < minVertexIndex)
  11233. minVertexIndex = vertexIndex;
  11234. if (vertexIndex > maxVertexIndex)
  11235. maxVertexIndex = vertexIndex;
  11236. }
  11237. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11238. };
  11239. return SubMesh;
  11240. })();
  11241. BABYLON.SubMesh = SubMesh;
  11242. })(BABYLON || (BABYLON = {}));
  11243. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11244. (function (BABYLON) {
  11245. var BaseTexture = (function () {
  11246. function BaseTexture(scene) {
  11247. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11248. this.hasAlpha = false;
  11249. this.getAlphaFromRGB = false;
  11250. this.level = 1;
  11251. this.isCube = false;
  11252. this.isRenderTarget = false;
  11253. this.animations = new Array();
  11254. this.coordinatesIndex = 0;
  11255. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11256. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11257. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11258. this.anisotropicFilteringLevel = 4;
  11259. this._scene = scene;
  11260. this._scene.textures.push(this);
  11261. }
  11262. BaseTexture.prototype.getScene = function () {
  11263. return this._scene;
  11264. };
  11265. BaseTexture.prototype.getTextureMatrix = function () {
  11266. return null;
  11267. };
  11268. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11269. return null;
  11270. };
  11271. BaseTexture.prototype.getInternalTexture = function () {
  11272. return this._texture;
  11273. };
  11274. BaseTexture.prototype.isReady = function () {
  11275. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11276. return true;
  11277. }
  11278. if (this._texture) {
  11279. return this._texture.isReady;
  11280. }
  11281. return false;
  11282. };
  11283. BaseTexture.prototype.getSize = function () {
  11284. if (this._texture._width) {
  11285. return { width: this._texture._width, height: this._texture._height };
  11286. }
  11287. if (this._texture._size) {
  11288. return { width: this._texture._size, height: this._texture._size };
  11289. }
  11290. return { width: 0, height: 0 };
  11291. };
  11292. BaseTexture.prototype.getBaseSize = function () {
  11293. if (!this.isReady())
  11294. return { width: 0, height: 0 };
  11295. if (this._texture._size) {
  11296. return { width: this._texture._size, height: this._texture._size };
  11297. }
  11298. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11299. };
  11300. BaseTexture.prototype.scale = function (ratio) {
  11301. };
  11302. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11303. get: function () {
  11304. return false;
  11305. },
  11306. enumerable: true,
  11307. configurable: true
  11308. });
  11309. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11310. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11311. for (var index = 0; index < texturesCache.length; index++) {
  11312. var texturesCacheEntry = texturesCache[index];
  11313. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11314. texturesCache.splice(index, 1);
  11315. return;
  11316. }
  11317. }
  11318. };
  11319. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11320. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11321. for (var index = 0; index < texturesCache.length; index++) {
  11322. var texturesCacheEntry = texturesCache[index];
  11323. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11324. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11325. texturesCacheEntry.references++;
  11326. return texturesCacheEntry;
  11327. }
  11328. }
  11329. }
  11330. return null;
  11331. };
  11332. BaseTexture.prototype.delayLoad = function () {
  11333. };
  11334. BaseTexture.prototype.releaseInternalTexture = function () {
  11335. if (!this._texture) {
  11336. return;
  11337. }
  11338. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11339. this._texture.references--;
  11340. // Final reference ?
  11341. if (this._texture.references === 0) {
  11342. var index = texturesCache.indexOf(this._texture);
  11343. texturesCache.splice(index, 1);
  11344. this._scene.getEngine()._releaseTexture(this._texture);
  11345. delete this._texture;
  11346. }
  11347. };
  11348. BaseTexture.prototype.clone = function () {
  11349. return null;
  11350. };
  11351. BaseTexture.prototype.dispose = function () {
  11352. // Remove from scene
  11353. var index = this._scene.textures.indexOf(this);
  11354. if (index >= 0) {
  11355. this._scene.textures.splice(index, 1);
  11356. }
  11357. if (this._texture === undefined) {
  11358. return;
  11359. }
  11360. this.releaseInternalTexture();
  11361. // Callback
  11362. if (this.onDispose) {
  11363. this.onDispose();
  11364. }
  11365. };
  11366. return BaseTexture;
  11367. })();
  11368. BABYLON.BaseTexture = BaseTexture;
  11369. })(BABYLON || (BABYLON = {}));
  11370. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  11371. (function (BABYLON) {
  11372. var RenderingGroup = (function () {
  11373. function RenderingGroup(index, scene) {
  11374. this.index = index;
  11375. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11376. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11377. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11378. this._scene = scene;
  11379. }
  11380. RenderingGroup.prototype.render = function (customRenderFunction) {
  11381. if (customRenderFunction) {
  11382. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11383. return true;
  11384. }
  11385. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11386. return false;
  11387. }
  11388. var engine = this._scene.getEngine();
  11389. // Opaque
  11390. var subIndex;
  11391. var submesh;
  11392. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11393. submesh = this._opaqueSubMeshes.data[subIndex];
  11394. submesh.render();
  11395. }
  11396. // Alpha test
  11397. engine.setAlphaTesting(true);
  11398. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11399. submesh = this._alphaTestSubMeshes.data[subIndex];
  11400. submesh.render();
  11401. }
  11402. engine.setAlphaTesting(false);
  11403. // Transparent
  11404. if (this._transparentSubMeshes.length) {
  11405. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11406. submesh = this._transparentSubMeshes.data[subIndex];
  11407. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11408. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11409. }
  11410. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11411. sortedArray.sort(function (a, b) {
  11412. // Alpha index first
  11413. if (a._alphaIndex > b._alphaIndex) {
  11414. return 1;
  11415. }
  11416. if (a._alphaIndex < b._alphaIndex) {
  11417. return -1;
  11418. }
  11419. // Then distance to camera
  11420. if (a._distanceToCamera < b._distanceToCamera) {
  11421. return 1;
  11422. }
  11423. if (a._distanceToCamera > b._distanceToCamera) {
  11424. return -1;
  11425. }
  11426. return 0;
  11427. });
  11428. // Rendering
  11429. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11430. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11431. submesh = sortedArray[subIndex];
  11432. submesh.render();
  11433. }
  11434. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11435. }
  11436. return true;
  11437. };
  11438. RenderingGroup.prototype.prepare = function () {
  11439. this._opaqueSubMeshes.reset();
  11440. this._transparentSubMeshes.reset();
  11441. this._alphaTestSubMeshes.reset();
  11442. };
  11443. RenderingGroup.prototype.dispatch = function (subMesh) {
  11444. var material = subMesh.getMaterial();
  11445. var mesh = subMesh.getMesh();
  11446. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11447. this._transparentSubMeshes.push(subMesh);
  11448. }
  11449. else if (material.needAlphaTesting()) {
  11450. this._alphaTestSubMeshes.push(subMesh);
  11451. }
  11452. else {
  11453. this._opaqueSubMeshes.push(subMesh); // Opaque
  11454. }
  11455. };
  11456. return RenderingGroup;
  11457. })();
  11458. BABYLON.RenderingGroup = RenderingGroup;
  11459. })(BABYLON || (BABYLON = {}));
  11460. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  11461. (function (BABYLON) {
  11462. var RenderingManager = (function () {
  11463. function RenderingManager(scene) {
  11464. this._renderingGroups = new Array();
  11465. this._scene = scene;
  11466. }
  11467. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11468. if (this._scene._activeParticleSystems.length === 0) {
  11469. return;
  11470. }
  11471. // Particles
  11472. var beforeParticlesDate = BABYLON.Tools.Now;
  11473. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11474. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11475. if (particleSystem.renderingGroupId !== index) {
  11476. continue;
  11477. }
  11478. this._clearDepthBuffer();
  11479. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11480. this._scene._activeParticles += particleSystem.render();
  11481. }
  11482. }
  11483. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11484. };
  11485. RenderingManager.prototype._renderSprites = function (index) {
  11486. if (this._scene.spriteManagers.length === 0) {
  11487. return;
  11488. }
  11489. // Sprites
  11490. var beforeSpritessDate = BABYLON.Tools.Now;
  11491. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11492. var spriteManager = this._scene.spriteManagers[id];
  11493. if (spriteManager.renderingGroupId === index) {
  11494. this._clearDepthBuffer();
  11495. spriteManager.render();
  11496. }
  11497. }
  11498. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11499. };
  11500. RenderingManager.prototype._clearDepthBuffer = function () {
  11501. if (this._depthBufferAlreadyCleaned) {
  11502. return;
  11503. }
  11504. this._scene.getEngine().clear(0, false, true);
  11505. this._depthBufferAlreadyCleaned = true;
  11506. };
  11507. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11508. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11509. this._depthBufferAlreadyCleaned = false;
  11510. var renderingGroup = this._renderingGroups[index];
  11511. if (renderingGroup) {
  11512. this._clearDepthBuffer();
  11513. if (!renderingGroup.render(customRenderFunction)) {
  11514. this._renderingGroups.splice(index, 1);
  11515. }
  11516. }
  11517. if (renderSprites) {
  11518. this._renderSprites(index);
  11519. }
  11520. if (renderParticles) {
  11521. this._renderParticles(index, activeMeshes);
  11522. }
  11523. }
  11524. };
  11525. RenderingManager.prototype.reset = function () {
  11526. for (var index in this._renderingGroups) {
  11527. var renderingGroup = this._renderingGroups[index];
  11528. renderingGroup.prepare();
  11529. }
  11530. };
  11531. RenderingManager.prototype.dispatch = function (subMesh) {
  11532. var mesh = subMesh.getMesh();
  11533. var renderingGroupId = mesh.renderingGroupId || 0;
  11534. if (!this._renderingGroups[renderingGroupId]) {
  11535. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11536. }
  11537. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11538. };
  11539. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11540. return RenderingManager;
  11541. })();
  11542. BABYLON.RenderingManager = RenderingManager;
  11543. })(BABYLON || (BABYLON = {}));
  11544. //# sourceMappingURL=babylon.renderingManager.js.map
  11545. var BABYLON;
  11546. (function (BABYLON) {
  11547. var Texture = (function (_super) {
  11548. __extends(Texture, _super);
  11549. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  11550. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11551. if (onLoad === void 0) { onLoad = null; }
  11552. if (onError === void 0) { onError = null; }
  11553. if (buffer === void 0) { buffer = null; }
  11554. if (deleteBuffer === void 0) { deleteBuffer = false; }
  11555. _super.call(this, scene);
  11556. this.uOffset = 0;
  11557. this.vOffset = 0;
  11558. this.uScale = 1.0;
  11559. this.vScale = 1.0;
  11560. this.uAng = 0;
  11561. this.vAng = 0;
  11562. this.wAng = 0;
  11563. this.name = url;
  11564. this.url = url;
  11565. this._noMipmap = noMipmap;
  11566. this._invertY = invertY;
  11567. this._samplingMode = samplingMode;
  11568. this._buffer = buffer;
  11569. this._deleteBuffer = deleteBuffer;
  11570. if (!url) {
  11571. return;
  11572. }
  11573. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  11574. if (!this._texture) {
  11575. if (!scene.useDelayedTextureLoading) {
  11576. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  11577. if (deleteBuffer) {
  11578. delete this._buffer;
  11579. }
  11580. }
  11581. else {
  11582. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11583. }
  11584. }
  11585. }
  11586. Texture.prototype.delayLoad = function () {
  11587. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11588. return;
  11589. }
  11590. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11591. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  11592. if (!this._texture) {
  11593. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  11594. if (this._deleteBuffer) {
  11595. delete this._buffer;
  11596. }
  11597. }
  11598. };
  11599. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  11600. x -= this.uOffset + 0.5;
  11601. y -= this.vOffset + 0.5;
  11602. z -= 0.5;
  11603. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  11604. t.x *= this.uScale;
  11605. t.y *= this.vScale;
  11606. t.x += 0.5;
  11607. t.y += 0.5;
  11608. t.z += 0.5;
  11609. };
  11610. Texture.prototype.getTextureMatrix = function () {
  11611. 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) {
  11612. return this._cachedTextureMatrix;
  11613. }
  11614. this._cachedUOffset = this.uOffset;
  11615. this._cachedVOffset = this.vOffset;
  11616. this._cachedUScale = this.uScale;
  11617. this._cachedVScale = this.vScale;
  11618. this._cachedUAng = this.uAng;
  11619. this._cachedVAng = this.vAng;
  11620. this._cachedWAng = this.wAng;
  11621. if (!this._cachedTextureMatrix) {
  11622. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11623. this._rowGenerationMatrix = new BABYLON.Matrix();
  11624. this._t0 = BABYLON.Vector3.Zero();
  11625. this._t1 = BABYLON.Vector3.Zero();
  11626. this._t2 = BABYLON.Vector3.Zero();
  11627. }
  11628. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  11629. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  11630. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  11631. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  11632. this._t1.subtractInPlace(this._t0);
  11633. this._t2.subtractInPlace(this._t0);
  11634. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11635. this._cachedTextureMatrix.m[0] = this._t1.x;
  11636. this._cachedTextureMatrix.m[1] = this._t1.y;
  11637. this._cachedTextureMatrix.m[2] = this._t1.z;
  11638. this._cachedTextureMatrix.m[4] = this._t2.x;
  11639. this._cachedTextureMatrix.m[5] = this._t2.y;
  11640. this._cachedTextureMatrix.m[6] = this._t2.z;
  11641. this._cachedTextureMatrix.m[8] = this._t0.x;
  11642. this._cachedTextureMatrix.m[9] = this._t0.y;
  11643. this._cachedTextureMatrix.m[10] = this._t0.z;
  11644. return this._cachedTextureMatrix;
  11645. };
  11646. Texture.prototype.getReflectionTextureMatrix = function () {
  11647. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  11648. return this._cachedTextureMatrix;
  11649. }
  11650. if (!this._cachedTextureMatrix) {
  11651. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11652. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  11653. }
  11654. this._cachedCoordinatesMode = this.coordinatesMode;
  11655. switch (this.coordinatesMode) {
  11656. case BABYLON.Texture.SPHERICAL_MODE:
  11657. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11658. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  11659. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  11660. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  11661. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  11662. break;
  11663. case BABYLON.Texture.PLANAR_MODE:
  11664. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11665. this._cachedTextureMatrix[0] = this.uScale;
  11666. this._cachedTextureMatrix[5] = this.vScale;
  11667. this._cachedTextureMatrix[12] = this.uOffset;
  11668. this._cachedTextureMatrix[13] = this.vOffset;
  11669. break;
  11670. case BABYLON.Texture.PROJECTION_MODE:
  11671. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  11672. this._projectionModeMatrix.m[0] = 0.5;
  11673. this._projectionModeMatrix.m[5] = -0.5;
  11674. this._projectionModeMatrix.m[10] = 0.0;
  11675. this._projectionModeMatrix.m[12] = 0.5;
  11676. this._projectionModeMatrix.m[13] = 0.5;
  11677. this._projectionModeMatrix.m[14] = 1.0;
  11678. this._projectionModeMatrix.m[15] = 1.0;
  11679. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  11680. break;
  11681. default:
  11682. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11683. break;
  11684. }
  11685. return this._cachedTextureMatrix;
  11686. };
  11687. Texture.prototype.clone = function () {
  11688. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  11689. // Base texture
  11690. newTexture.hasAlpha = this.hasAlpha;
  11691. newTexture.level = this.level;
  11692. newTexture.wrapU = this.wrapU;
  11693. newTexture.wrapV = this.wrapV;
  11694. newTexture.coordinatesIndex = this.coordinatesIndex;
  11695. newTexture.coordinatesMode = this.coordinatesMode;
  11696. // Texture
  11697. newTexture.uOffset = this.uOffset;
  11698. newTexture.vOffset = this.vOffset;
  11699. newTexture.uScale = this.uScale;
  11700. newTexture.vScale = this.vScale;
  11701. newTexture.uAng = this.uAng;
  11702. newTexture.vAng = this.vAng;
  11703. newTexture.wAng = this.wAng;
  11704. return newTexture;
  11705. };
  11706. // Statics
  11707. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  11708. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11709. if (onLoad === void 0) { onLoad = null; }
  11710. if (onError === void 0) { onError = null; }
  11711. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  11712. };
  11713. // Constants
  11714. Texture.NEAREST_SAMPLINGMODE = 1;
  11715. Texture.BILINEAR_SAMPLINGMODE = 2;
  11716. Texture.TRILINEAR_SAMPLINGMODE = 3;
  11717. Texture.EXPLICIT_MODE = 0;
  11718. Texture.SPHERICAL_MODE = 1;
  11719. Texture.PLANAR_MODE = 2;
  11720. Texture.CUBIC_MODE = 3;
  11721. Texture.PROJECTION_MODE = 4;
  11722. Texture.SKYBOX_MODE = 5;
  11723. Texture.CLAMP_ADDRESSMODE = 0;
  11724. Texture.WRAP_ADDRESSMODE = 1;
  11725. Texture.MIRROR_ADDRESSMODE = 2;
  11726. return Texture;
  11727. })(BABYLON.BaseTexture);
  11728. BABYLON.Texture = Texture;
  11729. })(BABYLON || (BABYLON = {}));
  11730. //# sourceMappingURL=babylon.texture.js.map
  11731. var BABYLON;
  11732. (function (BABYLON) {
  11733. var CubeTexture = (function (_super) {
  11734. __extends(CubeTexture, _super);
  11735. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  11736. _super.call(this, scene);
  11737. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  11738. this.name = rootUrl;
  11739. this.url = rootUrl;
  11740. this._noMipmap = noMipmap;
  11741. this.hasAlpha = false;
  11742. this._texture = this._getFromCache(rootUrl, noMipmap);
  11743. if (!extensions) {
  11744. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  11745. }
  11746. this._extensions = extensions;
  11747. if (!this._texture) {
  11748. if (!scene.useDelayedTextureLoading) {
  11749. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  11750. }
  11751. else {
  11752. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11753. }
  11754. }
  11755. this.isCube = true;
  11756. this._textureMatrix = BABYLON.Matrix.Identity();
  11757. }
  11758. CubeTexture.prototype.clone = function () {
  11759. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  11760. // Base texture
  11761. newTexture.level = this.level;
  11762. newTexture.wrapU = this.wrapU;
  11763. newTexture.wrapV = this.wrapV;
  11764. newTexture.coordinatesIndex = this.coordinatesIndex;
  11765. newTexture.coordinatesMode = this.coordinatesMode;
  11766. return newTexture;
  11767. };
  11768. // Methods
  11769. CubeTexture.prototype.delayLoad = function () {
  11770. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11771. return;
  11772. }
  11773. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11774. this._texture = this._getFromCache(this.url, this._noMipmap);
  11775. if (!this._texture) {
  11776. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  11777. }
  11778. };
  11779. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  11780. return this._textureMatrix;
  11781. };
  11782. return CubeTexture;
  11783. })(BABYLON.BaseTexture);
  11784. BABYLON.CubeTexture = CubeTexture;
  11785. })(BABYLON || (BABYLON = {}));
  11786. //# sourceMappingURL=babylon.cubeTexture.js.map
  11787. var BABYLON;
  11788. (function (BABYLON) {
  11789. var RenderTargetTexture = (function (_super) {
  11790. __extends(RenderTargetTexture, _super);
  11791. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  11792. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  11793. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  11794. _super.call(this, null, scene, !generateMipMaps);
  11795. this.renderList = new Array();
  11796. this.renderParticles = true;
  11797. this.renderSprites = false;
  11798. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  11799. this._currentRefreshId = -1;
  11800. this._refreshRate = 1;
  11801. this.name = name;
  11802. this.isRenderTarget = true;
  11803. this._size = size;
  11804. this._generateMipMaps = generateMipMaps;
  11805. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  11806. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  11807. // Rendering groups
  11808. this._renderingManager = new BABYLON.RenderingManager(scene);
  11809. }
  11810. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  11811. this._currentRefreshId = -1;
  11812. };
  11813. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  11814. get: function () {
  11815. return this._refreshRate;
  11816. },
  11817. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11818. set: function (value) {
  11819. this._refreshRate = value;
  11820. this.resetRefreshCounter();
  11821. },
  11822. enumerable: true,
  11823. configurable: true
  11824. });
  11825. RenderTargetTexture.prototype._shouldRender = function () {
  11826. if (this._currentRefreshId === -1) {
  11827. this._currentRefreshId = 1;
  11828. return true;
  11829. }
  11830. if (this.refreshRate === this._currentRefreshId) {
  11831. this._currentRefreshId = 1;
  11832. return true;
  11833. }
  11834. this._currentRefreshId++;
  11835. return false;
  11836. };
  11837. RenderTargetTexture.prototype.isReady = function () {
  11838. if (!this.getScene().renderTargetsEnabled) {
  11839. return false;
  11840. }
  11841. return _super.prototype.isReady.call(this);
  11842. };
  11843. RenderTargetTexture.prototype.getRenderSize = function () {
  11844. return this._size;
  11845. };
  11846. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11847. get: function () {
  11848. return true;
  11849. },
  11850. enumerable: true,
  11851. configurable: true
  11852. });
  11853. RenderTargetTexture.prototype.scale = function (ratio) {
  11854. var newSize = this._size * ratio;
  11855. this.resize(newSize, this._generateMipMaps);
  11856. };
  11857. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11858. this.releaseInternalTexture();
  11859. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11860. };
  11861. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11862. var scene = this.getScene();
  11863. var engine = scene.getEngine();
  11864. if (!this.activeCamera) {
  11865. this.activeCamera = scene.activeCamera;
  11866. }
  11867. if (this._waitingRenderList) {
  11868. this.renderList = [];
  11869. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11870. var id = this._waitingRenderList[index];
  11871. this.renderList.push(scene.getMeshByID(id));
  11872. }
  11873. delete this._waitingRenderList;
  11874. }
  11875. if (this.renderList && this.renderList.length === 0) {
  11876. return;
  11877. }
  11878. // Bind
  11879. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11880. engine.bindFramebuffer(this._texture);
  11881. }
  11882. // Clear
  11883. engine.clear(scene.clearColor, true, true);
  11884. this._renderingManager.reset();
  11885. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  11886. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  11887. var mesh = currentRenderList[meshIndex];
  11888. if (mesh) {
  11889. if (!mesh.isReady()) {
  11890. // Reset _currentRefreshId
  11891. this.resetRefreshCounter();
  11892. continue;
  11893. }
  11894. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  11895. mesh._activate(scene.getRenderId());
  11896. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  11897. var subMesh = mesh.subMeshes[subIndex];
  11898. scene._activeVertices += subMesh.indexCount;
  11899. this._renderingManager.dispatch(subMesh);
  11900. }
  11901. }
  11902. }
  11903. }
  11904. if (!this._doNotChangeAspectRatio) {
  11905. scene.updateTransformMatrix(true);
  11906. }
  11907. if (this.onBeforeRender) {
  11908. this.onBeforeRender();
  11909. }
  11910. // Render
  11911. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  11912. if (useCameraPostProcess) {
  11913. scene.postProcessManager._finalizeFrame(false, this._texture);
  11914. }
  11915. if (this.onAfterRender) {
  11916. this.onAfterRender();
  11917. }
  11918. // Unbind
  11919. engine.unBindFramebuffer(this._texture);
  11920. if (!this._doNotChangeAspectRatio) {
  11921. scene.updateTransformMatrix(true);
  11922. }
  11923. };
  11924. RenderTargetTexture.prototype.clone = function () {
  11925. var textureSize = this.getSize();
  11926. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11927. // Base texture
  11928. newTexture.hasAlpha = this.hasAlpha;
  11929. newTexture.level = this.level;
  11930. // RenderTarget Texture
  11931. newTexture.coordinatesMode = this.coordinatesMode;
  11932. newTexture.renderList = this.renderList.slice(0);
  11933. return newTexture;
  11934. };
  11935. return RenderTargetTexture;
  11936. })(BABYLON.Texture);
  11937. BABYLON.RenderTargetTexture = RenderTargetTexture;
  11938. })(BABYLON || (BABYLON = {}));
  11939. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  11940. var BABYLON;
  11941. (function (BABYLON) {
  11942. var ProceduralTexture = (function (_super) {
  11943. __extends(ProceduralTexture, _super);
  11944. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  11945. if (generateMipMaps === void 0) { generateMipMaps = true; }
  11946. _super.call(this, null, scene, !generateMipMaps);
  11947. this._currentRefreshId = -1;
  11948. this._refreshRate = 1;
  11949. this._vertexDeclaration = [2];
  11950. this._vertexStrideSize = 2 * 4;
  11951. this._uniforms = new Array();
  11952. this._samplers = new Array();
  11953. this._textures = new Array();
  11954. this._floats = new Array();
  11955. this._floatsArrays = {};
  11956. this._colors3 = new Array();
  11957. this._colors4 = new Array();
  11958. this._vectors2 = new Array();
  11959. this._vectors3 = new Array();
  11960. this._matrices = new Array();
  11961. this._fallbackTextureUsed = false;
  11962. scene._proceduralTextures.push(this);
  11963. this.name = name;
  11964. this.isRenderTarget = true;
  11965. this._size = size;
  11966. this._generateMipMaps = generateMipMaps;
  11967. this.setFragment(fragment);
  11968. this._fallbackTexture = fallbackTexture;
  11969. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11970. // VBO
  11971. var vertices = [];
  11972. vertices.push(1, 1);
  11973. vertices.push(-1, 1);
  11974. vertices.push(-1, -1);
  11975. vertices.push(1, -1);
  11976. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11977. // Indices
  11978. var indices = [];
  11979. indices.push(0);
  11980. indices.push(1);
  11981. indices.push(2);
  11982. indices.push(0);
  11983. indices.push(2);
  11984. indices.push(3);
  11985. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11986. }
  11987. ProceduralTexture.prototype.reset = function () {
  11988. if (this._effect === undefined) {
  11989. return;
  11990. }
  11991. var engine = this.getScene().getEngine();
  11992. engine._releaseEffect(this._effect);
  11993. };
  11994. ProceduralTexture.prototype.isReady = function () {
  11995. var _this = this;
  11996. var engine = this.getScene().getEngine();
  11997. var shaders;
  11998. if (!this._fragment) {
  11999. return false;
  12000. }
  12001. if (this._fallbackTextureUsed) {
  12002. return true;
  12003. }
  12004. if (this._fragment.fragmentElement !== undefined) {
  12005. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12006. }
  12007. else {
  12008. shaders = { vertex: "procedural", fragment: this._fragment };
  12009. }
  12010. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12011. _this.releaseInternalTexture();
  12012. if (_this._fallbackTexture) {
  12013. _this._texture = _this._fallbackTexture._texture;
  12014. _this._texture.references++;
  12015. }
  12016. _this._fallbackTextureUsed = true;
  12017. });
  12018. return this._effect.isReady();
  12019. };
  12020. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12021. this._currentRefreshId = -1;
  12022. };
  12023. ProceduralTexture.prototype.setFragment = function (fragment) {
  12024. this._fragment = fragment;
  12025. };
  12026. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12027. get: function () {
  12028. return this._refreshRate;
  12029. },
  12030. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12031. set: function (value) {
  12032. this._refreshRate = value;
  12033. this.resetRefreshCounter();
  12034. },
  12035. enumerable: true,
  12036. configurable: true
  12037. });
  12038. ProceduralTexture.prototype._shouldRender = function () {
  12039. if (!this.isReady() || !this._texture) {
  12040. return false;
  12041. }
  12042. if (this._fallbackTextureUsed) {
  12043. return false;
  12044. }
  12045. if (this._currentRefreshId === -1) {
  12046. this._currentRefreshId = 1;
  12047. return true;
  12048. }
  12049. if (this.refreshRate === this._currentRefreshId) {
  12050. this._currentRefreshId = 1;
  12051. return true;
  12052. }
  12053. this._currentRefreshId++;
  12054. return false;
  12055. };
  12056. ProceduralTexture.prototype.getRenderSize = function () {
  12057. return this._size;
  12058. };
  12059. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  12060. if (this._fallbackTextureUsed) {
  12061. return;
  12062. }
  12063. this.releaseInternalTexture();
  12064. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12065. };
  12066. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  12067. if (this._uniforms.indexOf(uniformName) === -1) {
  12068. this._uniforms.push(uniformName);
  12069. }
  12070. };
  12071. ProceduralTexture.prototype.setTexture = function (name, texture) {
  12072. if (this._samplers.indexOf(name) === -1) {
  12073. this._samplers.push(name);
  12074. }
  12075. this._textures[name] = texture;
  12076. return this;
  12077. };
  12078. ProceduralTexture.prototype.setFloat = function (name, value) {
  12079. this._checkUniform(name);
  12080. this._floats[name] = value;
  12081. return this;
  12082. };
  12083. ProceduralTexture.prototype.setFloats = function (name, value) {
  12084. this._checkUniform(name);
  12085. this._floatsArrays[name] = value;
  12086. return this;
  12087. };
  12088. ProceduralTexture.prototype.setColor3 = function (name, value) {
  12089. this._checkUniform(name);
  12090. this._colors3[name] = value;
  12091. return this;
  12092. };
  12093. ProceduralTexture.prototype.setColor4 = function (name, value) {
  12094. this._checkUniform(name);
  12095. this._colors4[name] = value;
  12096. return this;
  12097. };
  12098. ProceduralTexture.prototype.setVector2 = function (name, value) {
  12099. this._checkUniform(name);
  12100. this._vectors2[name] = value;
  12101. return this;
  12102. };
  12103. ProceduralTexture.prototype.setVector3 = function (name, value) {
  12104. this._checkUniform(name);
  12105. this._vectors3[name] = value;
  12106. return this;
  12107. };
  12108. ProceduralTexture.prototype.setMatrix = function (name, value) {
  12109. this._checkUniform(name);
  12110. this._matrices[name] = value;
  12111. return this;
  12112. };
  12113. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12114. var scene = this.getScene();
  12115. var engine = scene.getEngine();
  12116. engine.bindFramebuffer(this._texture);
  12117. // Clear
  12118. engine.clear(scene.clearColor, true, true);
  12119. // Render
  12120. engine.enableEffect(this._effect);
  12121. engine.setState(false);
  12122. for (var name in this._textures) {
  12123. this._effect.setTexture(name, this._textures[name]);
  12124. }
  12125. for (name in this._floats) {
  12126. this._effect.setFloat(name, this._floats[name]);
  12127. }
  12128. for (name in this._floatsArrays) {
  12129. this._effect.setArray(name, this._floatsArrays[name]);
  12130. }
  12131. for (name in this._colors3) {
  12132. this._effect.setColor3(name, this._colors3[name]);
  12133. }
  12134. for (name in this._colors4) {
  12135. var color = this._colors4[name];
  12136. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12137. }
  12138. for (name in this._vectors2) {
  12139. this._effect.setVector2(name, this._vectors2[name]);
  12140. }
  12141. for (name in this._vectors3) {
  12142. this._effect.setVector3(name, this._vectors3[name]);
  12143. }
  12144. for (name in this._matrices) {
  12145. this._effect.setMatrix(name, this._matrices[name]);
  12146. }
  12147. // VBOs
  12148. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12149. // Draw order
  12150. engine.draw(true, 0, 6);
  12151. // Unbind
  12152. engine.unBindFramebuffer(this._texture);
  12153. };
  12154. ProceduralTexture.prototype.clone = function () {
  12155. var textureSize = this.getSize();
  12156. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12157. // Base texture
  12158. newTexture.hasAlpha = this.hasAlpha;
  12159. newTexture.level = this.level;
  12160. // RenderTarget Texture
  12161. newTexture.coordinatesMode = this.coordinatesMode;
  12162. return newTexture;
  12163. };
  12164. ProceduralTexture.prototype.dispose = function () {
  12165. var index = this.getScene()._proceduralTextures.indexOf(this);
  12166. if (index >= 0) {
  12167. this.getScene()._proceduralTextures.splice(index, 1);
  12168. }
  12169. _super.prototype.dispose.call(this);
  12170. };
  12171. return ProceduralTexture;
  12172. })(BABYLON.Texture);
  12173. BABYLON.ProceduralTexture = ProceduralTexture;
  12174. })(BABYLON || (BABYLON = {}));
  12175. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12176. var BABYLON;
  12177. (function (BABYLON) {
  12178. var WoodProceduralTexture = (function (_super) {
  12179. __extends(WoodProceduralTexture, _super);
  12180. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12181. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12182. this._ampScale = 100.0;
  12183. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12184. this.updateShaderUniforms();
  12185. this.refreshRate = 0;
  12186. }
  12187. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12188. this.setFloat("ampScale", this._ampScale);
  12189. this.setColor3("woodColor", this._woodColor);
  12190. };
  12191. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12192. get: function () {
  12193. return this._ampScale;
  12194. },
  12195. set: function (value) {
  12196. this._ampScale = value;
  12197. this.updateShaderUniforms();
  12198. },
  12199. enumerable: true,
  12200. configurable: true
  12201. });
  12202. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12203. get: function () {
  12204. return this._woodColor;
  12205. },
  12206. set: function (value) {
  12207. this._woodColor = value;
  12208. this.updateShaderUniforms();
  12209. },
  12210. enumerable: true,
  12211. configurable: true
  12212. });
  12213. return WoodProceduralTexture;
  12214. })(BABYLON.ProceduralTexture);
  12215. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12216. var FireProceduralTexture = (function (_super) {
  12217. __extends(FireProceduralTexture, _super);
  12218. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12219. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12220. this._time = 0.0;
  12221. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12222. this._shift = 1.6;
  12223. this._autoGenerateTime = true;
  12224. this._alphaThreshold = 0.5;
  12225. this._fireColors = FireProceduralTexture.RedFireColors;
  12226. this.updateShaderUniforms();
  12227. this.refreshRate = 1;
  12228. }
  12229. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12230. this.setFloat("time", this._time);
  12231. this.setVector2("speed", this._speed);
  12232. this.setFloat("shift", this._shift);
  12233. this.setColor3("c1", this._fireColors[0]);
  12234. this.setColor3("c2", this._fireColors[1]);
  12235. this.setColor3("c3", this._fireColors[2]);
  12236. this.setColor3("c4", this._fireColors[3]);
  12237. this.setColor3("c5", this._fireColors[4]);
  12238. this.setColor3("c6", this._fireColors[5]);
  12239. this.setFloat("alphaThreshold", this._alphaThreshold);
  12240. };
  12241. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12242. if (this._autoGenerateTime) {
  12243. this._time += this.getScene().getAnimationRatio() * 0.03;
  12244. this.updateShaderUniforms();
  12245. }
  12246. _super.prototype.render.call(this, useCameraPostProcess);
  12247. };
  12248. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12249. get: function () {
  12250. return [
  12251. new BABYLON.Color3(0.5, 0.0, 1.0),
  12252. new BABYLON.Color3(0.9, 0.0, 1.0),
  12253. new BABYLON.Color3(0.2, 0.0, 1.0),
  12254. new BABYLON.Color3(1.0, 0.9, 1.0),
  12255. new BABYLON.Color3(0.1, 0.1, 1.0),
  12256. new BABYLON.Color3(0.9, 0.9, 1.0)
  12257. ];
  12258. },
  12259. enumerable: true,
  12260. configurable: true
  12261. });
  12262. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12263. get: function () {
  12264. return [
  12265. new BABYLON.Color3(0.5, 1.0, 0.0),
  12266. new BABYLON.Color3(0.5, 1.0, 0.0),
  12267. new BABYLON.Color3(0.3, 0.4, 0.0),
  12268. new BABYLON.Color3(0.5, 1.0, 0.0),
  12269. new BABYLON.Color3(0.2, 0.0, 0.0),
  12270. new BABYLON.Color3(0.5, 1.0, 0.0)
  12271. ];
  12272. },
  12273. enumerable: true,
  12274. configurable: true
  12275. });
  12276. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12277. get: function () {
  12278. return [
  12279. new BABYLON.Color3(0.5, 0.0, 0.1),
  12280. new BABYLON.Color3(0.9, 0.0, 0.0),
  12281. new BABYLON.Color3(0.2, 0.0, 0.0),
  12282. new BABYLON.Color3(1.0, 0.9, 0.0),
  12283. new BABYLON.Color3(0.1, 0.1, 0.1),
  12284. new BABYLON.Color3(0.9, 0.9, 0.9)
  12285. ];
  12286. },
  12287. enumerable: true,
  12288. configurable: true
  12289. });
  12290. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12291. get: function () {
  12292. return [
  12293. new BABYLON.Color3(0.1, 0.0, 0.5),
  12294. new BABYLON.Color3(0.0, 0.0, 0.5),
  12295. new BABYLON.Color3(0.1, 0.0, 0.2),
  12296. new BABYLON.Color3(0.0, 0.0, 1.0),
  12297. new BABYLON.Color3(0.1, 0.2, 0.3),
  12298. new BABYLON.Color3(0.0, 0.2, 0.9)
  12299. ];
  12300. },
  12301. enumerable: true,
  12302. configurable: true
  12303. });
  12304. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12305. get: function () {
  12306. return this._fireColors;
  12307. },
  12308. set: function (value) {
  12309. this._fireColors = value;
  12310. this.updateShaderUniforms();
  12311. },
  12312. enumerable: true,
  12313. configurable: true
  12314. });
  12315. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12316. get: function () {
  12317. return this._time;
  12318. },
  12319. set: function (value) {
  12320. this._time = value;
  12321. this.updateShaderUniforms();
  12322. },
  12323. enumerable: true,
  12324. configurable: true
  12325. });
  12326. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12327. get: function () {
  12328. return this._speed;
  12329. },
  12330. set: function (value) {
  12331. this._speed = value;
  12332. this.updateShaderUniforms();
  12333. },
  12334. enumerable: true,
  12335. configurable: true
  12336. });
  12337. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12338. get: function () {
  12339. return this._shift;
  12340. },
  12341. set: function (value) {
  12342. this._shift = value;
  12343. this.updateShaderUniforms();
  12344. },
  12345. enumerable: true,
  12346. configurable: true
  12347. });
  12348. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12349. get: function () {
  12350. return this._alphaThreshold;
  12351. },
  12352. set: function (value) {
  12353. this._alphaThreshold = value;
  12354. this.updateShaderUniforms();
  12355. },
  12356. enumerable: true,
  12357. configurable: true
  12358. });
  12359. return FireProceduralTexture;
  12360. })(BABYLON.ProceduralTexture);
  12361. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12362. var CloudProceduralTexture = (function (_super) {
  12363. __extends(CloudProceduralTexture, _super);
  12364. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12365. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12366. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12367. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12368. this.updateShaderUniforms();
  12369. this.refreshRate = 0;
  12370. }
  12371. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12372. this.setColor3("skyColor", this._skyColor);
  12373. this.setColor3("cloudColor", this._cloudColor);
  12374. };
  12375. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12376. get: function () {
  12377. return this._skyColor;
  12378. },
  12379. set: function (value) {
  12380. this._skyColor = value;
  12381. this.updateShaderUniforms();
  12382. },
  12383. enumerable: true,
  12384. configurable: true
  12385. });
  12386. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  12387. get: function () {
  12388. return this._cloudColor;
  12389. },
  12390. set: function (value) {
  12391. this._cloudColor = value;
  12392. this.updateShaderUniforms();
  12393. },
  12394. enumerable: true,
  12395. configurable: true
  12396. });
  12397. return CloudProceduralTexture;
  12398. })(BABYLON.ProceduralTexture);
  12399. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12400. var GrassProceduralTexture = (function (_super) {
  12401. __extends(GrassProceduralTexture, _super);
  12402. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12403. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12404. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12405. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12406. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12407. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12408. this._grassColors = [
  12409. new BABYLON.Color3(0.29, 0.38, 0.02),
  12410. new BABYLON.Color3(0.36, 0.49, 0.09),
  12411. new BABYLON.Color3(0.51, 0.6, 0.28)
  12412. ];
  12413. this.updateShaderUniforms();
  12414. this.refreshRate = 0;
  12415. }
  12416. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  12417. this.setColor3("herb1Color", this._grassColors[0]);
  12418. this.setColor3("herb2Color", this._grassColors[1]);
  12419. this.setColor3("herb3Color", this._grassColors[2]);
  12420. this.setColor3("groundColor", this._groundColor);
  12421. };
  12422. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  12423. get: function () {
  12424. return this._grassColors;
  12425. },
  12426. set: function (value) {
  12427. this._grassColors = value;
  12428. this.updateShaderUniforms();
  12429. },
  12430. enumerable: true,
  12431. configurable: true
  12432. });
  12433. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  12434. get: function () {
  12435. return this._groundColor;
  12436. },
  12437. set: function (value) {
  12438. this.groundColor = value;
  12439. this.updateShaderUniforms();
  12440. },
  12441. enumerable: true,
  12442. configurable: true
  12443. });
  12444. return GrassProceduralTexture;
  12445. })(BABYLON.ProceduralTexture);
  12446. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  12447. var RoadProceduralTexture = (function (_super) {
  12448. __extends(RoadProceduralTexture, _super);
  12449. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12450. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  12451. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  12452. this.updateShaderUniforms();
  12453. this.refreshRate = 0;
  12454. }
  12455. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  12456. this.setColor3("roadColor", this._roadColor);
  12457. };
  12458. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  12459. get: function () {
  12460. return this._roadColor;
  12461. },
  12462. set: function (value) {
  12463. this._roadColor = value;
  12464. this.updateShaderUniforms();
  12465. },
  12466. enumerable: true,
  12467. configurable: true
  12468. });
  12469. return RoadProceduralTexture;
  12470. })(BABYLON.ProceduralTexture);
  12471. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  12472. var BrickProceduralTexture = (function (_super) {
  12473. __extends(BrickProceduralTexture, _super);
  12474. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12475. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  12476. this._numberOfBricksHeight = 15;
  12477. this._numberOfBricksWidth = 5;
  12478. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12479. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12480. this.updateShaderUniforms();
  12481. this.refreshRate = 0;
  12482. }
  12483. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  12484. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  12485. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  12486. this.setColor3("brickColor", this._brickColor);
  12487. this.setColor3("jointColor", this._jointColor);
  12488. };
  12489. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  12490. get: function () {
  12491. return this._numberOfBricksHeight;
  12492. },
  12493. enumerable: true,
  12494. configurable: true
  12495. });
  12496. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  12497. set: function (value) {
  12498. this._numberOfBricksHeight = value;
  12499. this.updateShaderUniforms();
  12500. },
  12501. enumerable: true,
  12502. configurable: true
  12503. });
  12504. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  12505. get: function () {
  12506. return this._numberOfBricksWidth;
  12507. },
  12508. set: function (value) {
  12509. this._numberOfBricksHeight = value;
  12510. this.updateShaderUniforms();
  12511. },
  12512. enumerable: true,
  12513. configurable: true
  12514. });
  12515. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  12516. get: function () {
  12517. return this._jointColor;
  12518. },
  12519. set: function (value) {
  12520. this._jointColor = value;
  12521. this.updateShaderUniforms();
  12522. },
  12523. enumerable: true,
  12524. configurable: true
  12525. });
  12526. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  12527. get: function () {
  12528. return this._brickColor;
  12529. },
  12530. set: function (value) {
  12531. this._brickColor = value;
  12532. this.updateShaderUniforms();
  12533. },
  12534. enumerable: true,
  12535. configurable: true
  12536. });
  12537. return BrickProceduralTexture;
  12538. })(BABYLON.ProceduralTexture);
  12539. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  12540. var MarbleProceduralTexture = (function (_super) {
  12541. __extends(MarbleProceduralTexture, _super);
  12542. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12543. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  12544. this._numberOfTilesHeight = 3;
  12545. this._numberOfTilesWidth = 3;
  12546. this._amplitude = 9.0;
  12547. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12548. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12549. this.updateShaderUniforms();
  12550. this.refreshRate = 0;
  12551. }
  12552. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  12553. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  12554. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  12555. this.setFloat("amplitude", this._amplitude);
  12556. this.setColor3("marbleColor", this._marbleColor);
  12557. this.setColor3("jointColor", this._jointColor);
  12558. };
  12559. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  12560. get: function () {
  12561. return this._numberOfTilesHeight;
  12562. },
  12563. set: function (value) {
  12564. this._numberOfTilesHeight = value;
  12565. this.updateShaderUniforms();
  12566. },
  12567. enumerable: true,
  12568. configurable: true
  12569. });
  12570. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  12571. get: function () {
  12572. return this._numberOfTilesWidth;
  12573. },
  12574. set: function (value) {
  12575. this._numberOfTilesWidth = value;
  12576. this.updateShaderUniforms();
  12577. },
  12578. enumerable: true,
  12579. configurable: true
  12580. });
  12581. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  12582. get: function () {
  12583. return this._jointColor;
  12584. },
  12585. set: function (value) {
  12586. this._jointColor = value;
  12587. this.updateShaderUniforms();
  12588. },
  12589. enumerable: true,
  12590. configurable: true
  12591. });
  12592. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  12593. get: function () {
  12594. return this._marbleColor;
  12595. },
  12596. set: function (value) {
  12597. this._marbleColor = value;
  12598. this.updateShaderUniforms();
  12599. },
  12600. enumerable: true,
  12601. configurable: true
  12602. });
  12603. return MarbleProceduralTexture;
  12604. })(BABYLON.ProceduralTexture);
  12605. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  12606. })(BABYLON || (BABYLON = {}));
  12607. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  12608. var BABYLON;
  12609. (function (BABYLON) {
  12610. var CustomProceduralTexture = (function (_super) {
  12611. __extends(CustomProceduralTexture, _super);
  12612. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  12613. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  12614. this._animate = true;
  12615. this._time = 0;
  12616. this._texturePath = texturePath;
  12617. //Try to load json
  12618. this.loadJson(texturePath);
  12619. this.refreshRate = 1;
  12620. }
  12621. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  12622. var _this = this;
  12623. var that = this;
  12624. function noConfigFile() {
  12625. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  12626. try {
  12627. that.setFragment(that._texturePath);
  12628. }
  12629. catch (ex) {
  12630. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  12631. }
  12632. }
  12633. var configFileUrl = jsonUrl + "/config.json";
  12634. var xhr = new XMLHttpRequest();
  12635. xhr.open("GET", configFileUrl, true);
  12636. xhr.addEventListener("load", function () {
  12637. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12638. try {
  12639. _this._config = JSON.parse(xhr.response);
  12640. _this.updateShaderUniforms();
  12641. _this.updateTextures();
  12642. _this.setFragment(_this._texturePath + "/custom");
  12643. _this._animate = _this._config.animate;
  12644. _this.refreshRate = _this._config.refreshrate;
  12645. }
  12646. catch (ex) {
  12647. noConfigFile();
  12648. }
  12649. }
  12650. else {
  12651. noConfigFile();
  12652. }
  12653. }, false);
  12654. xhr.addEventListener("error", function (event) {
  12655. noConfigFile();
  12656. }, false);
  12657. try {
  12658. xhr.send();
  12659. }
  12660. catch (ex) {
  12661. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  12662. }
  12663. };
  12664. CustomProceduralTexture.prototype.isReady = function () {
  12665. if (!_super.prototype.isReady.call(this)) {
  12666. return false;
  12667. }
  12668. for (var name in this._textures) {
  12669. var texture = this._textures[name];
  12670. if (!texture.isReady()) {
  12671. return false;
  12672. }
  12673. }
  12674. return true;
  12675. };
  12676. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12677. if (this._animate) {
  12678. this._time += this.getScene().getAnimationRatio() * 0.03;
  12679. this.updateShaderUniforms();
  12680. }
  12681. _super.prototype.render.call(this, useCameraPostProcess);
  12682. };
  12683. CustomProceduralTexture.prototype.updateTextures = function () {
  12684. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  12685. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  12686. }
  12687. };
  12688. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  12689. if (this._config) {
  12690. for (var j = 0; j < this._config.uniforms.length; j++) {
  12691. var uniform = this._config.uniforms[j];
  12692. switch (uniform.type) {
  12693. case "float":
  12694. this.setFloat(uniform.name, uniform.value);
  12695. break;
  12696. case "color3":
  12697. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  12698. break;
  12699. case "color4":
  12700. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  12701. break;
  12702. case "vector2":
  12703. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  12704. break;
  12705. case "vector3":
  12706. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  12707. break;
  12708. }
  12709. }
  12710. }
  12711. this.setFloat("time", this._time);
  12712. };
  12713. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  12714. get: function () {
  12715. return this._animate;
  12716. },
  12717. set: function (value) {
  12718. this._animate = value;
  12719. },
  12720. enumerable: true,
  12721. configurable: true
  12722. });
  12723. return CustomProceduralTexture;
  12724. })(BABYLON.ProceduralTexture);
  12725. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  12726. })(BABYLON || (BABYLON = {}));
  12727. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  12728. var BABYLON;
  12729. (function (BABYLON) {
  12730. var MirrorTexture = (function (_super) {
  12731. __extends(MirrorTexture, _super);
  12732. function MirrorTexture(name, size, scene, generateMipMaps) {
  12733. var _this = this;
  12734. _super.call(this, name, size, scene, generateMipMaps, true);
  12735. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  12736. this._transformMatrix = BABYLON.Matrix.Zero();
  12737. this._mirrorMatrix = BABYLON.Matrix.Zero();
  12738. this.onBeforeRender = function () {
  12739. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  12740. _this._savedViewMatrix = scene.getViewMatrix();
  12741. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  12742. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  12743. scene.clipPlane = _this.mirrorPlane;
  12744. scene.getEngine().cullBackFaces = false;
  12745. };
  12746. this.onAfterRender = function () {
  12747. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  12748. scene.getEngine().cullBackFaces = true;
  12749. delete scene.clipPlane;
  12750. };
  12751. }
  12752. MirrorTexture.prototype.clone = function () {
  12753. var textureSize = this.getSize();
  12754. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12755. // Base texture
  12756. newTexture.hasAlpha = this.hasAlpha;
  12757. newTexture.level = this.level;
  12758. // Mirror Texture
  12759. newTexture.mirrorPlane = this.mirrorPlane.clone();
  12760. newTexture.renderList = this.renderList.slice(0);
  12761. return newTexture;
  12762. };
  12763. return MirrorTexture;
  12764. })(BABYLON.RenderTargetTexture);
  12765. BABYLON.MirrorTexture = MirrorTexture;
  12766. })(BABYLON || (BABYLON = {}));
  12767. //# sourceMappingURL=babylon.mirrorTexture.js.map
  12768. var BABYLON;
  12769. (function (BABYLON) {
  12770. var DynamicTexture = (function (_super) {
  12771. __extends(DynamicTexture, _super);
  12772. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  12773. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12774. _super.call(this, null, scene, !generateMipMaps);
  12775. this.name = name;
  12776. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12777. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12778. this._generateMipMaps = generateMipMaps;
  12779. if (options.getContext) {
  12780. this._canvas = options;
  12781. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12782. }
  12783. else {
  12784. this._canvas = document.createElement("canvas");
  12785. if (options.width) {
  12786. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12787. }
  12788. else {
  12789. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  12790. }
  12791. }
  12792. var textureSize = this.getSize();
  12793. this._canvas.width = textureSize.width;
  12794. this._canvas.height = textureSize.height;
  12795. this._context = this._canvas.getContext("2d");
  12796. }
  12797. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  12798. get: function () {
  12799. return true;
  12800. },
  12801. enumerable: true,
  12802. configurable: true
  12803. });
  12804. DynamicTexture.prototype.scale = function (ratio) {
  12805. var textureSize = this.getSize();
  12806. textureSize.width *= ratio;
  12807. textureSize.height *= ratio;
  12808. this._canvas.width = textureSize.width;
  12809. this._canvas.height = textureSize.height;
  12810. this.releaseInternalTexture();
  12811. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  12812. };
  12813. DynamicTexture.prototype.getContext = function () {
  12814. return this._context;
  12815. };
  12816. DynamicTexture.prototype.clear = function () {
  12817. var size = this.getSize();
  12818. this._context.fillRect(0, 0, size.width, size.height);
  12819. };
  12820. DynamicTexture.prototype.update = function (invertY) {
  12821. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  12822. };
  12823. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  12824. if (update === void 0) { update = true; }
  12825. var size = this.getSize();
  12826. if (clearColor) {
  12827. this._context.fillStyle = clearColor;
  12828. this._context.fillRect(0, 0, size.width, size.height);
  12829. }
  12830. this._context.font = font;
  12831. if (x === null) {
  12832. var textSize = this._context.measureText(text);
  12833. x = (size.width - textSize.width) / 2;
  12834. }
  12835. this._context.fillStyle = color;
  12836. this._context.fillText(text, x, y);
  12837. if (update) {
  12838. this.update(invertY);
  12839. }
  12840. };
  12841. DynamicTexture.prototype.clone = function () {
  12842. var textureSize = this.getSize();
  12843. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12844. // Base texture
  12845. newTexture.hasAlpha = this.hasAlpha;
  12846. newTexture.level = this.level;
  12847. // Dynamic Texture
  12848. newTexture.wrapU = this.wrapU;
  12849. newTexture.wrapV = this.wrapV;
  12850. return newTexture;
  12851. };
  12852. return DynamicTexture;
  12853. })(BABYLON.Texture);
  12854. BABYLON.DynamicTexture = DynamicTexture;
  12855. })(BABYLON || (BABYLON = {}));
  12856. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12857. var BABYLON;
  12858. (function (BABYLON) {
  12859. var VideoTexture = (function (_super) {
  12860. __extends(VideoTexture, _super);
  12861. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12862. var _this = this;
  12863. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12864. _super.call(this, null, scene, !generateMipMaps, invertY);
  12865. this._autoLaunch = true;
  12866. this.name = name;
  12867. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12868. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12869. var requiredWidth = size.width || size;
  12870. var requiredHeight = size.height || size;
  12871. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12872. var textureSize = this.getSize();
  12873. this.video = document.createElement("video");
  12874. this.video.width = textureSize.width;
  12875. this.video.height = textureSize.height;
  12876. this.video.autoplay = false;
  12877. this.video.loop = true;
  12878. this.video.addEventListener("canplaythrough", function () {
  12879. if (_this._texture) {
  12880. _this._texture.isReady = true;
  12881. }
  12882. });
  12883. urls.forEach(function (url) {
  12884. var source = document.createElement("source");
  12885. source.src = url;
  12886. _this.video.appendChild(source);
  12887. });
  12888. this._lastUpdate = BABYLON.Tools.Now;
  12889. }
  12890. VideoTexture.prototype.update = function () {
  12891. if (this._autoLaunch) {
  12892. this._autoLaunch = false;
  12893. this.video.play();
  12894. }
  12895. var now = BABYLON.Tools.Now;
  12896. if (now - this._lastUpdate < 15) {
  12897. return false;
  12898. }
  12899. this._lastUpdate = now;
  12900. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  12901. return true;
  12902. };
  12903. return VideoTexture;
  12904. })(BABYLON.Texture);
  12905. BABYLON.VideoTexture = VideoTexture;
  12906. })(BABYLON || (BABYLON = {}));
  12907. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  12908. (function (BABYLON) {
  12909. var EffectFallbacks = (function () {
  12910. function EffectFallbacks() {
  12911. this._defines = {};
  12912. this._currentRank = 32;
  12913. this._maxRank = -1;
  12914. }
  12915. EffectFallbacks.prototype.addFallback = function (rank, define) {
  12916. if (!this._defines[rank]) {
  12917. if (rank < this._currentRank) {
  12918. this._currentRank = rank;
  12919. }
  12920. if (rank > this._maxRank) {
  12921. this._maxRank = rank;
  12922. }
  12923. this._defines[rank] = new Array();
  12924. }
  12925. this._defines[rank].push(define);
  12926. };
  12927. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  12928. get: function () {
  12929. return this._currentRank <= this._maxRank;
  12930. },
  12931. enumerable: true,
  12932. configurable: true
  12933. });
  12934. EffectFallbacks.prototype.reduce = function (currentDefines) {
  12935. var currentFallbacks = this._defines[this._currentRank];
  12936. for (var index = 0; index < currentFallbacks.length; index++) {
  12937. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  12938. }
  12939. this._currentRank++;
  12940. return currentDefines;
  12941. };
  12942. return EffectFallbacks;
  12943. })();
  12944. BABYLON.EffectFallbacks = EffectFallbacks;
  12945. var Effect = (function () {
  12946. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  12947. var _this = this;
  12948. this._isReady = false;
  12949. this._compilationError = "";
  12950. this._valueCache = [];
  12951. this._engine = engine;
  12952. this.name = baseName;
  12953. this.defines = defines;
  12954. this._uniformsNames = uniformsNames.concat(samplers);
  12955. this._samplers = samplers;
  12956. this._attributesNames = attributesNames;
  12957. this.onError = onError;
  12958. this.onCompiled = onCompiled;
  12959. var vertexSource;
  12960. var fragmentSource;
  12961. if (baseName.vertexElement) {
  12962. vertexSource = document.getElementById(baseName.vertexElement);
  12963. if (!vertexSource) {
  12964. vertexSource = baseName.vertexElement;
  12965. }
  12966. }
  12967. else {
  12968. vertexSource = baseName.vertex || baseName;
  12969. }
  12970. if (baseName.fragmentElement) {
  12971. fragmentSource = document.getElementById(baseName.fragmentElement);
  12972. if (!fragmentSource) {
  12973. fragmentSource = baseName.fragmentElement;
  12974. }
  12975. }
  12976. else {
  12977. fragmentSource = baseName.fragment || baseName;
  12978. }
  12979. this._loadVertexShader(vertexSource, function (vertexCode) {
  12980. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  12981. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  12982. });
  12983. });
  12984. }
  12985. // Properties
  12986. Effect.prototype.isReady = function () {
  12987. return this._isReady;
  12988. };
  12989. Effect.prototype.getProgram = function () {
  12990. return this._program;
  12991. };
  12992. Effect.prototype.getAttributesNames = function () {
  12993. return this._attributesNames;
  12994. };
  12995. Effect.prototype.getAttributeLocation = function (index) {
  12996. return this._attributes[index];
  12997. };
  12998. Effect.prototype.getAttributeLocationByName = function (name) {
  12999. var index = this._attributesNames.indexOf(name);
  13000. return this._attributes[index];
  13001. };
  13002. Effect.prototype.getAttributesCount = function () {
  13003. return this._attributes.length;
  13004. };
  13005. Effect.prototype.getUniformIndex = function (uniformName) {
  13006. return this._uniformsNames.indexOf(uniformName);
  13007. };
  13008. Effect.prototype.getUniform = function (uniformName) {
  13009. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13010. };
  13011. Effect.prototype.getSamplers = function () {
  13012. return this._samplers;
  13013. };
  13014. Effect.prototype.getCompilationError = function () {
  13015. return this._compilationError;
  13016. };
  13017. // Methods
  13018. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13019. // DOM element ?
  13020. if (vertex instanceof HTMLElement) {
  13021. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13022. callback(vertexCode);
  13023. return;
  13024. }
  13025. // Is in local store ?
  13026. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13027. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13028. return;
  13029. }
  13030. var vertexShaderUrl;
  13031. if (vertex[0] === ".") {
  13032. vertexShaderUrl = vertex;
  13033. }
  13034. else {
  13035. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13036. }
  13037. // Vertex shader
  13038. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13039. };
  13040. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13041. // DOM element ?
  13042. if (fragment instanceof HTMLElement) {
  13043. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13044. callback(fragmentCode);
  13045. return;
  13046. }
  13047. // Is in local store ?
  13048. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13049. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13050. return;
  13051. }
  13052. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  13053. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  13054. return;
  13055. }
  13056. var fragmentShaderUrl;
  13057. if (fragment[0] === ".") {
  13058. fragmentShaderUrl = fragment;
  13059. }
  13060. else {
  13061. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  13062. }
  13063. // Fragment shader
  13064. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  13065. };
  13066. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  13067. try {
  13068. var engine = this._engine;
  13069. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  13070. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  13071. this._attributes = engine.getAttributes(this._program, attributesNames);
  13072. for (var index = 0; index < this._samplers.length; index++) {
  13073. var sampler = this.getUniform(this._samplers[index]);
  13074. if (sampler == null) {
  13075. this._samplers.splice(index, 1);
  13076. index--;
  13077. }
  13078. }
  13079. engine.bindSamplers(this);
  13080. this._isReady = true;
  13081. if (this.onCompiled) {
  13082. this.onCompiled(this);
  13083. }
  13084. }
  13085. catch (e) {
  13086. // Is it a problem with precision?
  13087. if (e.message.indexOf("highp") !== -1) {
  13088. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  13089. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  13090. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13091. return;
  13092. }
  13093. // Let's go through fallbacks then
  13094. if (fallbacks && fallbacks.isMoreFallbacks) {
  13095. defines = fallbacks.reduce(defines);
  13096. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13097. }
  13098. else {
  13099. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  13100. BABYLON.Tools.Error("Defines: " + defines);
  13101. BABYLON.Tools.Error("Error: " + e.message);
  13102. this._compilationError = e.message;
  13103. if (this.onError) {
  13104. this.onError(this, this._compilationError);
  13105. }
  13106. }
  13107. }
  13108. };
  13109. Effect.prototype._bindTexture = function (channel, texture) {
  13110. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  13111. };
  13112. Effect.prototype.setTexture = function (channel, texture) {
  13113. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  13114. };
  13115. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13116. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  13117. };
  13118. //public _cacheMatrix(uniformName, matrix) {
  13119. // if (!this._valueCache[uniformName]) {
  13120. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13121. // }
  13122. // for (var index = 0; index < 16; index++) {
  13123. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13124. // }
  13125. //};
  13126. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13127. if (!this._valueCache[uniformName]) {
  13128. this._valueCache[uniformName] = [x, y];
  13129. return;
  13130. }
  13131. this._valueCache[uniformName][0] = x;
  13132. this._valueCache[uniformName][1] = y;
  13133. };
  13134. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13135. if (!this._valueCache[uniformName]) {
  13136. this._valueCache[uniformName] = [x, y, z];
  13137. return;
  13138. }
  13139. this._valueCache[uniformName][0] = x;
  13140. this._valueCache[uniformName][1] = y;
  13141. this._valueCache[uniformName][2] = z;
  13142. };
  13143. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13144. if (!this._valueCache[uniformName]) {
  13145. this._valueCache[uniformName] = [x, y, z, w];
  13146. return;
  13147. }
  13148. this._valueCache[uniformName][0] = x;
  13149. this._valueCache[uniformName][1] = y;
  13150. this._valueCache[uniformName][2] = z;
  13151. this._valueCache[uniformName][3] = w;
  13152. };
  13153. Effect.prototype.setArray = function (uniformName, array) {
  13154. this._engine.setArray(this.getUniform(uniformName), array);
  13155. return this;
  13156. };
  13157. Effect.prototype.setArray2 = function (uniformName, array) {
  13158. this._engine.setArray2(this.getUniform(uniformName), array);
  13159. return this;
  13160. };
  13161. Effect.prototype.setArray3 = function (uniformName, array) {
  13162. this._engine.setArray3(this.getUniform(uniformName), array);
  13163. return this;
  13164. };
  13165. Effect.prototype.setArray4 = function (uniformName, array) {
  13166. this._engine.setArray4(this.getUniform(uniformName), array);
  13167. return this;
  13168. };
  13169. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13170. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13171. return this;
  13172. };
  13173. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13174. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13175. // return;
  13176. //this._cacheMatrix(uniformName, matrix);
  13177. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13178. return this;
  13179. };
  13180. Effect.prototype.setFloat = function (uniformName, value) {
  13181. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13182. return this;
  13183. this._valueCache[uniformName] = value;
  13184. this._engine.setFloat(this.getUniform(uniformName), value);
  13185. return this;
  13186. };
  13187. Effect.prototype.setBool = function (uniformName, bool) {
  13188. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13189. return this;
  13190. this._valueCache[uniformName] = bool;
  13191. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13192. return this;
  13193. };
  13194. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13195. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13196. return this;
  13197. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13198. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13199. return this;
  13200. };
  13201. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13202. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13203. return this;
  13204. this._cacheFloat2(uniformName, x, y);
  13205. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13206. return this;
  13207. };
  13208. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13209. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13210. return this;
  13211. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13212. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13213. return this;
  13214. };
  13215. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13216. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13217. return this;
  13218. this._cacheFloat3(uniformName, x, y, z);
  13219. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13220. return this;
  13221. };
  13222. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13223. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13224. return this;
  13225. this._cacheFloat4(uniformName, x, y, z, w);
  13226. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13227. return this;
  13228. };
  13229. Effect.prototype.setColor3 = function (uniformName, color3) {
  13230. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13231. return this;
  13232. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13233. this._engine.setColor3(this.getUniform(uniformName), color3);
  13234. return this;
  13235. };
  13236. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13237. 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)
  13238. return this;
  13239. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13240. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13241. return this;
  13242. };
  13243. // Statics
  13244. 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}",
  13245. 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}",
  13246. 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}",
  13247. brickPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfBricksHeight;\nuniform float numberOfBricksWidth;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvoid main(void)\n{\n float brickW = 1.0 / numberOfBricksWidth;\n float brickH = 1.0 / numberOfBricksHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.05;\n vec3 color = brickColor;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\n\n if (brickColorSwitch == 0.0)\n color = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\n else if (brickColorSwitch == 2.0)\n color = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\n }\n\n gl_FragColor = vec4(color, 1.0);\n}",
  13248. cloudPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\n\nuniform vec3 skyColor;\nuniform vec3 cloudColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n\n vec2 p = vUV * 12.0;\n vec3 c = mix(skyColor, cloudColor, fbm(p));\n gl_FragColor = vec4(c, 1);\n\n}",
  13249. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13250. 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}",
  13251. 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}",
  13252. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / 1500.0)) < depth.z) visibility -= 0.2;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  13253. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#else\n finalWorld = finalWorld * (m0 + m1 + m2);\n#endif \n\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n\n // Point size\n#ifdef POINTSIZE\n gl_PointSize = pointSize;\n#endif\n}",
  13254. depthPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nuniform float far;\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n float depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\n gl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\n}",
  13255. depthVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  13256. 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}",
  13257. 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}",
  13258. firePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform float time;\nuniform vec3 c1;\nuniform vec3 c2;\nuniform vec3 c3;\nuniform vec3 c4;\nuniform vec3 c5;\nuniform vec3 c6;\nuniform vec2 speed;\nuniform float shift;\nuniform float alphaThreshold;\n\nvarying vec2 vUV;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n vec2 p = vUV * 8.0;\n float q = fbm(p - time * 0.1);\n vec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\n vec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\n vec3 color = c * cos(shift * vUV.y);\n float luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\n\n gl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\n}",
  13259. 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}",
  13260. grassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform vec3 herb1Color;\nuniform vec3 herb2Color;\nuniform vec3 herb3Color;\nuniform vec3 groundColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n vec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\n color = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\n color = mix(color, herb3Color, rand(gl_FragCoord.xy));\n color = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\n gl_FragColor = vec4(color, 1.0);\n}",
  13261. 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}",
  13262. 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}",
  13263. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return 0.;\n }\n return 1.;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW;\n if (lightData.w == 0.)\n {\n lightVectorW = normalize(lightData.xyz - vPositionW);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\n result[0] = ndl * diffuseColor.rgb;\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = ndl * spotAtten * diffuseColor.rgb;\n result[1] = specComp * specularColor * spotAtten;\n result[2] = vec3(0.);\n\n return result;\n }\n\n result[0] = vec3(0.);\n result[1] = vec3(0.);\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\n mat3 result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = mix(groundColor, diffuseColor.rgb, ndl);\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n mat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\n mat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n mat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  13264. legacydefaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return position;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n finalWorld = world;\n#endif\n\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef REFLECTION\n vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  13265. 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}",
  13266. 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}",
  13267. marblePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfTilesHeight;\nuniform float numberOfTilesWidth;\nuniform float amplitude;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat turbulence(vec2 P)\n{\n float val = 0.0;\n float freq = 1.0;\n for (int i = 0; i < 4; i++)\n {\n val += abs(noise(P*freq) / freq);\n freq *= 2.07;\n }\n return val;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvec3 marble_color(float x)\n{\n vec3 col;\n x = 0.5*(x + 1.);\n x = sqrt(x); \n x = sqrt(x);\n x = sqrt(x);\n col = vec3(.2 + .75*x); \n col.b *= 0.95; \n return col;\n}\n\nvoid main()\n{\n float brickW = 1.0 / numberOfTilesWidth;\n float brickH = 1.0 / numberOfTilesHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.01;\n vec3 color = brickColor;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\n t += amplitude * turbulence(brickvUV.xy);\n t = sin(t);\n color = marble_color(t);\n }\n\n gl_FragColor = vec4(color, 0.0);\n}",
  13268. 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}",
  13269. outlinePixelShader:"precision highp float;\n\nuniform vec4 color;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void) {\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n gl_FragColor = color;\n}",
  13270. 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}",
  13271. 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}",
  13272. 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}",
  13273. 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}",
  13274. 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}",
  13275. 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}",
  13276. 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}",
  13277. roadPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV; \nuniform vec3 roadColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\n vec3 color = roadColor * ratioy;\n gl_FragColor = vec4(color, 1.0);\n}",
  13278. 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}",
  13279. 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}",
  13280. 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}",
  13281. 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}",
  13282. ssaoPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define SAMPLES 16\n\nuniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\n\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[16];\n\nvarying vec2 vUV;\n\nconst vec2 offset1 = vec2(0.0, 0.001);\nconst vec2 offset2 = vec2(0.001, 0.0);\n\nvec3 normalFromDepth(const float depth, const vec2 coords) {\n float depth1 = texture2D(textureSampler, coords + offset1).r;\n float depth2 = texture2D(textureSampler, coords + offset2).r;\n\n vec3 p1 = vec3(offset1, depth1 - depth);\n vec3 p2 = vec3(offset2, depth2 - depth);\n\n vec3 normal = cross(p1, p2);\n normal.z = -normal.z;\n\n return normalize(normal);\n}\n\nvoid main(void)\n{\n const float totalStrength = 1.0;\n const float base = 0.2;\n const float area = 0.0075;\n const float fallOff = 0.000001;\n const float radius = 0.0002;\n\n vec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\n float depth = texture2D(textureSampler, vUV).r;\n vec3 position = vec3(vUV, depth);\n vec3 normal = normalFromDepth(depth, vUV);\n float radiusDepth = radius / depth;\n float occlusion = 0.0;\n\n vec3 ray;\n vec3 hemiRay;\n float occlusionDepth;\n float difference;\n\n for (int i = 0; i < SAMPLES; i++)\n {\n ray = radiusDepth * reflect(sampleSphere[i], random);\n hemiRay = position + sign(dot(ray, normal)) * ray;\n\n occlusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\n difference = depth - occlusionDepth;\n\n occlusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\n }\n\n float ao = 1.0 - totalStrength * occlusion * samplesFactor;\n\n float result = clamp(ao + base, 0.0, 1.0);\n gl_FragColor.r = result;\n gl_FragColor.g = result;\n gl_FragColor.b = result;\n gl_FragColor.a = result;\n}",
  13283. ssaoCombinePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D originalColor;\n\nvarying vec2 vUV;\n\nvoid main(void) {\n gl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\n}",
  13284. volumetricLightScatteringPixelShader:"// Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html\n\n#ifdef GL_ES\nprecision mediump float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\n\nuniform vec2 lightPositionOnScreen;\n\nvarying vec2 vUV;\n\nvoid main(void) {\n \n float decay = 0.96815;\n float exposure = 0.3;\n float density = 0.926;\n float weight = 0.58767;\n\n const int NUM_SAMPLES = 100;\n\n vec2 tc = vUV;\n vec2 deltaTexCoord = (tc - lightPositionOnScreen.xy);\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\n\n float illuminationDecay = 1.0;\n\n vec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\n\n for(int i=0; i < NUM_SAMPLES; i++)\n {\n tc -= deltaTexCoord;\n vec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\n sample *= illuminationDecay * weight;\n color += sample;\n illuminationDecay *= decay;\n }\n\n vec4 realColor = texture2D(textureSampler, vUV);\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\n}",
  13285. volumetricLightScatteringPassPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\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 BASIC_RENDER\n gl_FragColor = texture2D(diffuseSampler, vUV);\n#else\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n#endif\n}",
  13286. woodPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float ampScale;\nuniform vec3 woodColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\n vec3 wood = woodColor * ratioy;\n gl_FragColor = vec4(wood, 1.0);\n}",
  13287. };
  13288. return Effect;
  13289. })();
  13290. BABYLON.Effect = Effect;
  13291. })(BABYLON || (BABYLON = {}));
  13292. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13293. (function (BABYLON) {
  13294. var Material = (function () {
  13295. function Material(name, scene, doNotAdd) {
  13296. this.name = name;
  13297. this.checkReadyOnEveryCall = true;
  13298. this.checkReadyOnlyOnce = false;
  13299. this.state = "";
  13300. this.alpha = 1.0;
  13301. this.backFaceCulling = true;
  13302. this._wasPreviouslyReady = false;
  13303. this._fillMode = Material.TriangleFillMode;
  13304. this.pointSize = 1.0;
  13305. this.id = name;
  13306. this._scene = scene;
  13307. if (!doNotAdd) {
  13308. scene.materials.push(this);
  13309. }
  13310. }
  13311. Object.defineProperty(Material, "TriangleFillMode", {
  13312. get: function () {
  13313. return Material._TriangleFillMode;
  13314. },
  13315. enumerable: true,
  13316. configurable: true
  13317. });
  13318. Object.defineProperty(Material, "WireFrameFillMode", {
  13319. get: function () {
  13320. return Material._WireFrameFillMode;
  13321. },
  13322. enumerable: true,
  13323. configurable: true
  13324. });
  13325. Object.defineProperty(Material, "PointFillMode", {
  13326. get: function () {
  13327. return Material._PointFillMode;
  13328. },
  13329. enumerable: true,
  13330. configurable: true
  13331. });
  13332. Object.defineProperty(Material.prototype, "wireframe", {
  13333. get: function () {
  13334. return this._fillMode === Material.WireFrameFillMode;
  13335. },
  13336. set: function (value) {
  13337. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13338. },
  13339. enumerable: true,
  13340. configurable: true
  13341. });
  13342. Object.defineProperty(Material.prototype, "pointsCloud", {
  13343. get: function () {
  13344. return this._fillMode === Material.PointFillMode;
  13345. },
  13346. set: function (value) {
  13347. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13348. },
  13349. enumerable: true,
  13350. configurable: true
  13351. });
  13352. Object.defineProperty(Material.prototype, "fillMode", {
  13353. get: function () {
  13354. return this._fillMode;
  13355. },
  13356. set: function (value) {
  13357. this._fillMode = value;
  13358. },
  13359. enumerable: true,
  13360. configurable: true
  13361. });
  13362. Material.prototype.isReady = function (mesh, useInstances) {
  13363. return true;
  13364. };
  13365. Material.prototype.getEffect = function () {
  13366. return this._effect;
  13367. };
  13368. Material.prototype.getScene = function () {
  13369. return this._scene;
  13370. };
  13371. Material.prototype.needAlphaBlending = function () {
  13372. return (this.alpha < 1.0);
  13373. };
  13374. Material.prototype.needAlphaTesting = function () {
  13375. return false;
  13376. };
  13377. Material.prototype.getAlphaTestTexture = function () {
  13378. return null;
  13379. };
  13380. Material.prototype.trackCreation = function (onCompiled, onError) {
  13381. };
  13382. Material.prototype._preBind = function () {
  13383. var engine = this._scene.getEngine();
  13384. engine.enableEffect(this._effect);
  13385. engine.setState(this.backFaceCulling);
  13386. };
  13387. Material.prototype.bind = function (world, mesh) {
  13388. this._scene._cachedMaterial = this;
  13389. if (this.onBind) {
  13390. this.onBind(this);
  13391. }
  13392. };
  13393. Material.prototype.bindOnlyWorldMatrix = function (world) {
  13394. };
  13395. Material.prototype.unbind = function () {
  13396. };
  13397. Material.prototype.dispose = function (forceDisposeEffect) {
  13398. // Remove from scene
  13399. var index = this._scene.materials.indexOf(this);
  13400. this._scene.materials.splice(index, 1);
  13401. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  13402. if (forceDisposeEffect && this._effect) {
  13403. this._scene.getEngine()._releaseEffect(this._effect);
  13404. this._effect = null;
  13405. }
  13406. // Callback
  13407. if (this.onDispose) {
  13408. this.onDispose();
  13409. }
  13410. };
  13411. Material._TriangleFillMode = 0;
  13412. Material._WireFrameFillMode = 1;
  13413. Material._PointFillMode = 2;
  13414. return Material;
  13415. })();
  13416. BABYLON.Material = Material;
  13417. })(BABYLON || (BABYLON = {}));
  13418. //# sourceMappingURL=babylon.material.js.map
  13419. var BABYLON;
  13420. (function (BABYLON) {
  13421. var maxSimultaneousLights = 4;
  13422. var FresnelParameters = (function () {
  13423. function FresnelParameters() {
  13424. this.isEnabled = true;
  13425. this.leftColor = BABYLON.Color3.White();
  13426. this.rightColor = BABYLON.Color3.Black();
  13427. this.bias = 0;
  13428. this.power = 1;
  13429. }
  13430. return FresnelParameters;
  13431. })();
  13432. BABYLON.FresnelParameters = FresnelParameters;
  13433. var StandardMaterial = (function (_super) {
  13434. __extends(StandardMaterial, _super);
  13435. function StandardMaterial(name, scene) {
  13436. var _this = this;
  13437. _super.call(this, name, scene);
  13438. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13439. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  13440. this.specularColor = new BABYLON.Color3(1, 1, 1);
  13441. this.specularPower = 64;
  13442. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  13443. this.useAlphaFromDiffuseTexture = false;
  13444. this.useSpecularOverAlpha = true;
  13445. this.fogEnabled = true;
  13446. this._cachedDefines = null;
  13447. this._renderTargets = new BABYLON.SmartArray(16);
  13448. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  13449. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  13450. this._scaledDiffuse = new BABYLON.Color3();
  13451. this._scaledSpecular = new BABYLON.Color3();
  13452. this.getRenderTargetTextures = function () {
  13453. _this._renderTargets.reset();
  13454. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  13455. _this._renderTargets.push(_this.reflectionTexture);
  13456. }
  13457. return _this._renderTargets;
  13458. };
  13459. }
  13460. StandardMaterial.prototype.needAlphaBlending = function () {
  13461. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  13462. };
  13463. StandardMaterial.prototype.needAlphaTesting = function () {
  13464. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  13465. };
  13466. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  13467. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  13468. };
  13469. StandardMaterial.prototype.getAlphaTestTexture = function () {
  13470. return this.diffuseTexture;
  13471. };
  13472. // Methods
  13473. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  13474. if (this.checkReadyOnlyOnce) {
  13475. if (this._wasPreviouslyReady) {
  13476. return true;
  13477. }
  13478. }
  13479. var scene = this.getScene();
  13480. if (!this.checkReadyOnEveryCall) {
  13481. if (this._renderId === scene.getRenderId()) {
  13482. return true;
  13483. }
  13484. }
  13485. var engine = scene.getEngine();
  13486. var defines = [];
  13487. var fallbacks = new BABYLON.EffectFallbacks();
  13488. // Textures
  13489. if (scene.texturesEnabled) {
  13490. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13491. if (!this.diffuseTexture.isReady()) {
  13492. return false;
  13493. }
  13494. else {
  13495. defines.push("#define DIFFUSE");
  13496. }
  13497. }
  13498. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13499. if (!this.ambientTexture.isReady()) {
  13500. return false;
  13501. }
  13502. else {
  13503. defines.push("#define AMBIENT");
  13504. }
  13505. }
  13506. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13507. if (!this.opacityTexture.isReady()) {
  13508. return false;
  13509. }
  13510. else {
  13511. defines.push("#define OPACITY");
  13512. if (this.opacityTexture.getAlphaFromRGB) {
  13513. defines.push("#define OPACITYRGB");
  13514. }
  13515. }
  13516. }
  13517. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13518. if (!this.reflectionTexture.isReady()) {
  13519. return false;
  13520. }
  13521. else {
  13522. defines.push("#define REFLECTION");
  13523. fallbacks.addFallback(0, "REFLECTION");
  13524. }
  13525. }
  13526. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13527. if (!this.emissiveTexture.isReady()) {
  13528. return false;
  13529. }
  13530. else {
  13531. defines.push("#define EMISSIVE");
  13532. }
  13533. }
  13534. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13535. if (!this.specularTexture.isReady()) {
  13536. return false;
  13537. }
  13538. else {
  13539. defines.push("#define SPECULAR");
  13540. fallbacks.addFallback(0, "SPECULAR");
  13541. }
  13542. }
  13543. }
  13544. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  13545. if (!this.bumpTexture.isReady()) {
  13546. return false;
  13547. }
  13548. else {
  13549. defines.push("#define BUMP");
  13550. fallbacks.addFallback(0, "BUMP");
  13551. }
  13552. }
  13553. // Effect
  13554. if (this.useSpecularOverAlpha) {
  13555. defines.push("#define SPECULAROVERALPHA");
  13556. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  13557. }
  13558. if (scene.clipPlane) {
  13559. defines.push("#define CLIPPLANE");
  13560. }
  13561. if (engine.getAlphaTesting()) {
  13562. defines.push("#define ALPHATEST");
  13563. }
  13564. if (this._shouldUseAlphaFromDiffuseTexture()) {
  13565. defines.push("#define ALPHAFROMDIFFUSE");
  13566. }
  13567. // Point size
  13568. if (this.pointsCloud || scene.forcePointsCloud) {
  13569. defines.push("#define POINTSIZE");
  13570. }
  13571. // Fog
  13572. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13573. defines.push("#define FOG");
  13574. fallbacks.addFallback(1, "FOG");
  13575. }
  13576. var shadowsActivated = false;
  13577. var lightIndex = 0;
  13578. if (scene.lightsEnabled) {
  13579. for (var index = 0; index < scene.lights.length; index++) {
  13580. var light = scene.lights[index];
  13581. if (!light.isEnabled()) {
  13582. continue;
  13583. }
  13584. // Excluded check
  13585. if (light._excludedMeshesIds.length > 0) {
  13586. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  13587. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  13588. if (excludedMesh) {
  13589. light.excludedMeshes.push(excludedMesh);
  13590. }
  13591. }
  13592. light._excludedMeshesIds = [];
  13593. }
  13594. // Included check
  13595. if (light._includedOnlyMeshesIds.length > 0) {
  13596. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  13597. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  13598. if (includedOnlyMesh) {
  13599. light.includedOnlyMeshes.push(includedOnlyMesh);
  13600. }
  13601. }
  13602. light._includedOnlyMeshesIds = [];
  13603. }
  13604. if (!light.canAffectMesh(mesh)) {
  13605. continue;
  13606. }
  13607. defines.push("#define LIGHT" + lightIndex);
  13608. if (lightIndex > 0) {
  13609. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  13610. }
  13611. var type;
  13612. if (light instanceof BABYLON.SpotLight) {
  13613. type = "#define SPOTLIGHT" + lightIndex;
  13614. }
  13615. else if (light instanceof BABYLON.HemisphericLight) {
  13616. type = "#define HEMILIGHT" + lightIndex;
  13617. }
  13618. else {
  13619. type = "#define POINTDIRLIGHT" + lightIndex;
  13620. }
  13621. defines.push(type);
  13622. if (lightIndex > 0) {
  13623. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  13624. }
  13625. // Shadows
  13626. if (scene.shadowsEnabled) {
  13627. var shadowGenerator = light.getShadowGenerator();
  13628. if (mesh && mesh.receiveShadows && shadowGenerator) {
  13629. defines.push("#define SHADOW" + lightIndex);
  13630. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  13631. if (!shadowsActivated) {
  13632. defines.push("#define SHADOWS");
  13633. shadowsActivated = true;
  13634. }
  13635. if (shadowGenerator.useVarianceShadowMap) {
  13636. defines.push("#define SHADOWVSM" + lightIndex);
  13637. if (lightIndex > 0) {
  13638. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  13639. }
  13640. }
  13641. if (shadowGenerator.usePoissonSampling) {
  13642. defines.push("#define SHADOWPCF" + lightIndex);
  13643. if (lightIndex > 0) {
  13644. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  13645. }
  13646. }
  13647. }
  13648. }
  13649. lightIndex++;
  13650. if (lightIndex === maxSimultaneousLights)
  13651. break;
  13652. }
  13653. }
  13654. if (StandardMaterial.FresnelEnabled) {
  13655. // Fresnel
  13656. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13657. var fresnelRank = 1;
  13658. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13659. defines.push("#define DIFFUSEFRESNEL");
  13660. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  13661. fresnelRank++;
  13662. }
  13663. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13664. defines.push("#define OPACITYFRESNEL");
  13665. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  13666. fresnelRank++;
  13667. }
  13668. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13669. defines.push("#define REFLECTIONFRESNEL");
  13670. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  13671. fresnelRank++;
  13672. }
  13673. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13674. defines.push("#define EMISSIVEFRESNEL");
  13675. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  13676. fresnelRank++;
  13677. }
  13678. defines.push("#define FRESNEL");
  13679. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  13680. }
  13681. }
  13682. // Attribs
  13683. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  13684. if (mesh) {
  13685. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13686. attribs.push(BABYLON.VertexBuffer.UVKind);
  13687. defines.push("#define UV1");
  13688. }
  13689. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13690. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  13691. defines.push("#define UV2");
  13692. }
  13693. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13694. attribs.push(BABYLON.VertexBuffer.ColorKind);
  13695. defines.push("#define VERTEXCOLOR");
  13696. if (mesh.hasVertexAlpha) {
  13697. defines.push("#define VERTEXALPHA");
  13698. }
  13699. }
  13700. if (mesh.useBones) {
  13701. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13702. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13703. defines.push("#define BONES");
  13704. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13705. defines.push("#define BONES4");
  13706. fallbacks.addFallback(0, "BONES4");
  13707. }
  13708. // Instances
  13709. if (useInstances) {
  13710. defines.push("#define INSTANCES");
  13711. attribs.push("world0");
  13712. attribs.push("world1");
  13713. attribs.push("world2");
  13714. attribs.push("world3");
  13715. }
  13716. }
  13717. // Get correct effect
  13718. var join = defines.join("\n");
  13719. if (this._cachedDefines !== join) {
  13720. this._cachedDefines = join;
  13721. scene.resetCachedMaterial();
  13722. // Legacy browser patch
  13723. var shaderName = "default";
  13724. if (!scene.getEngine().getCaps().standardDerivatives) {
  13725. shaderName = "legacydefault";
  13726. }
  13727. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0", "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1", "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2", "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "mBones", "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "darkness0", "darkness1", "darkness2", "darkness3", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"], join, fallbacks, this.onCompiled, this.onError);
  13728. }
  13729. if (!this._effect.isReady()) {
  13730. return false;
  13731. }
  13732. this._renderId = scene.getRenderId();
  13733. this._wasPreviouslyReady = true;
  13734. return true;
  13735. };
  13736. StandardMaterial.prototype.unbind = function () {
  13737. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  13738. this._effect.setTexture("reflection2DSampler", null);
  13739. }
  13740. };
  13741. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  13742. this._effect.setMatrix("world", world);
  13743. };
  13744. StandardMaterial.prototype.bind = function (world, mesh) {
  13745. var scene = this.getScene();
  13746. // Matrices
  13747. this.bindOnlyWorldMatrix(world);
  13748. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  13749. // Bones
  13750. if (mesh.useBones) {
  13751. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  13752. }
  13753. if (scene.getCachedMaterial() !== this) {
  13754. if (StandardMaterial.FresnelEnabled) {
  13755. // Fresnel
  13756. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13757. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  13758. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  13759. }
  13760. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13761. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  13762. }
  13763. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13764. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  13765. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  13766. }
  13767. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13768. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  13769. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  13770. }
  13771. }
  13772. // Textures
  13773. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13774. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  13775. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  13776. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  13777. }
  13778. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13779. this._effect.setTexture("ambientSampler", this.ambientTexture);
  13780. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  13781. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  13782. }
  13783. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13784. this._effect.setTexture("opacitySampler", this.opacityTexture);
  13785. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  13786. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  13787. }
  13788. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13789. if (this.reflectionTexture.isCube) {
  13790. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  13791. }
  13792. else {
  13793. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  13794. }
  13795. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  13796. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  13797. }
  13798. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13799. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  13800. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  13801. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  13802. }
  13803. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13804. this._effect.setTexture("specularSampler", this.specularTexture);
  13805. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  13806. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  13807. }
  13808. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  13809. this._effect.setTexture("bumpSampler", this.bumpTexture);
  13810. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  13811. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  13812. }
  13813. // Clip plane
  13814. if (scene.clipPlane) {
  13815. var clipPlane = scene.clipPlane;
  13816. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13817. }
  13818. // Point size
  13819. if (this.pointsCloud) {
  13820. this._effect.setFloat("pointSize", this.pointSize);
  13821. }
  13822. // Colors
  13823. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  13824. // Scaling down color according to emissive
  13825. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13826. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13827. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13828. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  13829. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  13830. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  13831. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  13832. }
  13833. // Scaling down color according to emissive
  13834. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13835. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13836. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13837. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  13838. if (scene.lightsEnabled) {
  13839. var lightIndex = 0;
  13840. for (var index = 0; index < scene.lights.length; index++) {
  13841. var light = scene.lights[index];
  13842. if (!light.isEnabled()) {
  13843. continue;
  13844. }
  13845. if (!light.canAffectMesh(mesh)) {
  13846. continue;
  13847. }
  13848. if (light instanceof BABYLON.PointLight) {
  13849. // Point Light
  13850. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13851. }
  13852. else if (light instanceof BABYLON.DirectionalLight) {
  13853. // Directional Light
  13854. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13855. }
  13856. else if (light instanceof BABYLON.SpotLight) {
  13857. // Spot Light
  13858. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  13859. }
  13860. else if (light instanceof BABYLON.HemisphericLight) {
  13861. // Hemispheric Light
  13862. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  13863. }
  13864. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  13865. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  13866. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  13867. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  13868. // Shadows
  13869. if (scene.shadowsEnabled) {
  13870. var shadowGenerator = light.getShadowGenerator();
  13871. if (mesh.receiveShadows && shadowGenerator) {
  13872. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13873. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13874. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13875. }
  13876. }
  13877. lightIndex++;
  13878. if (lightIndex === maxSimultaneousLights)
  13879. break;
  13880. }
  13881. }
  13882. // View
  13883. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13884. this._effect.setMatrix("view", scene.getViewMatrix());
  13885. }
  13886. // Fog
  13887. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13888. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13889. this._effect.setColor3("vFogColor", scene.fogColor);
  13890. }
  13891. _super.prototype.bind.call(this, world, mesh);
  13892. };
  13893. StandardMaterial.prototype.getAnimatables = function () {
  13894. var results = [];
  13895. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  13896. results.push(this.diffuseTexture);
  13897. }
  13898. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  13899. results.push(this.ambientTexture);
  13900. }
  13901. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  13902. results.push(this.opacityTexture);
  13903. }
  13904. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  13905. results.push(this.reflectionTexture);
  13906. }
  13907. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  13908. results.push(this.emissiveTexture);
  13909. }
  13910. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  13911. results.push(this.specularTexture);
  13912. }
  13913. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  13914. results.push(this.bumpTexture);
  13915. }
  13916. return results;
  13917. };
  13918. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  13919. if (this.diffuseTexture) {
  13920. this.diffuseTexture.dispose();
  13921. }
  13922. if (this.ambientTexture) {
  13923. this.ambientTexture.dispose();
  13924. }
  13925. if (this.opacityTexture) {
  13926. this.opacityTexture.dispose();
  13927. }
  13928. if (this.reflectionTexture) {
  13929. this.reflectionTexture.dispose();
  13930. }
  13931. if (this.emissiveTexture) {
  13932. this.emissiveTexture.dispose();
  13933. }
  13934. if (this.specularTexture) {
  13935. this.specularTexture.dispose();
  13936. }
  13937. if (this.bumpTexture) {
  13938. this.bumpTexture.dispose();
  13939. }
  13940. _super.prototype.dispose.call(this, forceDisposeEffect);
  13941. };
  13942. StandardMaterial.prototype.clone = function (name) {
  13943. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  13944. // Base material
  13945. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  13946. newStandardMaterial.alpha = this.alpha;
  13947. newStandardMaterial.fillMode = this.fillMode;
  13948. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  13949. // Standard material
  13950. if (this.diffuseTexture && this.diffuseTexture.clone) {
  13951. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  13952. }
  13953. if (this.ambientTexture && this.ambientTexture.clone) {
  13954. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  13955. }
  13956. if (this.opacityTexture && this.opacityTexture.clone) {
  13957. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  13958. }
  13959. if (this.reflectionTexture && this.reflectionTexture.clone) {
  13960. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  13961. }
  13962. if (this.emissiveTexture && this.emissiveTexture.clone) {
  13963. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  13964. }
  13965. if (this.specularTexture && this.specularTexture.clone) {
  13966. newStandardMaterial.specularTexture = this.specularTexture.clone();
  13967. }
  13968. if (this.bumpTexture && this.bumpTexture.clone) {
  13969. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  13970. }
  13971. newStandardMaterial.ambientColor = this.ambientColor.clone();
  13972. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  13973. newStandardMaterial.specularColor = this.specularColor.clone();
  13974. newStandardMaterial.specularPower = this.specularPower;
  13975. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  13976. return newStandardMaterial;
  13977. };
  13978. // Statics
  13979. // Flags used to enable or disable a type of texture for all Standard Materials
  13980. StandardMaterial.DiffuseTextureEnabled = true;
  13981. StandardMaterial.AmbientTextureEnabled = true;
  13982. StandardMaterial.OpacityTextureEnabled = true;
  13983. StandardMaterial.ReflectionTextureEnabled = true;
  13984. StandardMaterial.EmissiveTextureEnabled = true;
  13985. StandardMaterial.SpecularTextureEnabled = true;
  13986. StandardMaterial.BumpTextureEnabled = true;
  13987. StandardMaterial.FresnelEnabled = true;
  13988. return StandardMaterial;
  13989. })(BABYLON.Material);
  13990. BABYLON.StandardMaterial = StandardMaterial;
  13991. })(BABYLON || (BABYLON = {}));
  13992. //# sourceMappingURL=babylon.standardMaterial.js.map
  13993. var BABYLON;
  13994. (function (BABYLON) {
  13995. var MultiMaterial = (function (_super) {
  13996. __extends(MultiMaterial, _super);
  13997. function MultiMaterial(name, scene) {
  13998. _super.call(this, name, scene, true);
  13999. this.subMaterials = new Array();
  14000. scene.multiMaterials.push(this);
  14001. }
  14002. // Properties
  14003. MultiMaterial.prototype.getSubMaterial = function (index) {
  14004. if (index < 0 || index >= this.subMaterials.length) {
  14005. return this.getScene().defaultMaterial;
  14006. }
  14007. return this.subMaterials[index];
  14008. };
  14009. // Methods
  14010. MultiMaterial.prototype.isReady = function (mesh) {
  14011. for (var index = 0; index < this.subMaterials.length; index++) {
  14012. var subMaterial = this.subMaterials[index];
  14013. if (subMaterial) {
  14014. if (!this.subMaterials[index].isReady(mesh)) {
  14015. return false;
  14016. }
  14017. }
  14018. }
  14019. return true;
  14020. };
  14021. return MultiMaterial;
  14022. })(BABYLON.Material);
  14023. BABYLON.MultiMaterial = MultiMaterial;
  14024. })(BABYLON || (BABYLON = {}));
  14025. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14026. (function (BABYLON) {
  14027. var Database = (function () {
  14028. function Database(urlToScene, callbackManifestChecked) {
  14029. // Handling various flavors of prefixed version of IndexedDB
  14030. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14031. this.callbackManifestChecked = callbackManifestChecked;
  14032. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  14033. this.db = null;
  14034. this.enableSceneOffline = false;
  14035. this.enableTexturesOffline = false;
  14036. this.manifestVersionFound = 0;
  14037. this.mustUpdateRessources = false;
  14038. this.hasReachedQuota = false;
  14039. this.checkManifestFile();
  14040. }
  14041. Database.prototype.checkManifestFile = function () {
  14042. var _this = this;
  14043. function noManifestFile() {
  14044. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  14045. that.enableSceneOffline = false;
  14046. that.enableTexturesOffline = false;
  14047. that.callbackManifestChecked(false);
  14048. }
  14049. var that = this;
  14050. var manifestURL = this.currentSceneUrl + ".manifest";
  14051. var xhr = new XMLHttpRequest();
  14052. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  14053. xhr.open("GET", manifestURLTimeStamped, true);
  14054. xhr.addEventListener("load", function () {
  14055. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14056. try {
  14057. var manifestFile = JSON.parse(xhr.response);
  14058. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  14059. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  14060. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  14061. _this.manifestVersionFound = manifestFile.version;
  14062. }
  14063. if (_this.callbackManifestChecked) {
  14064. _this.callbackManifestChecked(true);
  14065. }
  14066. }
  14067. catch (ex) {
  14068. noManifestFile();
  14069. }
  14070. }
  14071. else {
  14072. noManifestFile();
  14073. }
  14074. }, false);
  14075. xhr.addEventListener("error", function (event) {
  14076. noManifestFile();
  14077. }, false);
  14078. try {
  14079. xhr.send();
  14080. }
  14081. catch (ex) {
  14082. BABYLON.Tools.Error("Error on XHR send request.");
  14083. that.callbackManifestChecked(false);
  14084. }
  14085. };
  14086. Database.prototype.openAsync = function (successCallback, errorCallback) {
  14087. var _this = this;
  14088. function handleError() {
  14089. that.isSupported = false;
  14090. if (errorCallback)
  14091. errorCallback();
  14092. }
  14093. var that = this;
  14094. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  14095. // Your browser doesn't support IndexedDB
  14096. this.isSupported = false;
  14097. if (errorCallback)
  14098. errorCallback();
  14099. }
  14100. else {
  14101. // If the DB hasn't been opened or created yet
  14102. if (!this.db) {
  14103. this.hasReachedQuota = false;
  14104. this.isSupported = true;
  14105. var request = this.idbFactory.open("babylonjs", 1);
  14106. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  14107. request.onerror = function (event) {
  14108. handleError();
  14109. };
  14110. // executes when a version change transaction cannot complete due to other active transactions
  14111. request.onblocked = function (event) {
  14112. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  14113. handleError();
  14114. };
  14115. // DB has been opened successfully
  14116. request.onsuccess = function (event) {
  14117. _this.db = request.result;
  14118. successCallback();
  14119. };
  14120. // Initialization of the DB. Creating Scenes & Textures stores
  14121. request.onupgradeneeded = function (event) {
  14122. _this.db = (event.target).result;
  14123. try {
  14124. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  14125. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  14126. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  14127. }
  14128. catch (ex) {
  14129. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  14130. handleError();
  14131. }
  14132. };
  14133. }
  14134. else {
  14135. if (successCallback)
  14136. successCallback();
  14137. }
  14138. }
  14139. };
  14140. Database.prototype.loadImageFromDB = function (url, image) {
  14141. var _this = this;
  14142. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  14143. var saveAndLoadImage = function () {
  14144. if (!_this.hasReachedQuota && _this.db !== null) {
  14145. // the texture is not yet in the DB, let's try to save it
  14146. _this._saveImageIntoDBAsync(completeURL, image);
  14147. }
  14148. else {
  14149. image.src = url;
  14150. }
  14151. };
  14152. if (!this.mustUpdateRessources) {
  14153. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14154. }
  14155. else {
  14156. saveAndLoadImage();
  14157. }
  14158. };
  14159. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14160. if (this.isSupported && this.db !== null) {
  14161. var texture;
  14162. var transaction = this.db.transaction(["textures"]);
  14163. transaction.onabort = function (event) {
  14164. image.src = url;
  14165. };
  14166. transaction.oncomplete = function (event) {
  14167. var blobTextureURL;
  14168. if (texture) {
  14169. var URL = window.URL || window.webkitURL;
  14170. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14171. image.onerror = function () {
  14172. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14173. image.src = url;
  14174. };
  14175. image.src = blobTextureURL;
  14176. }
  14177. else {
  14178. notInDBCallback();
  14179. }
  14180. };
  14181. var getRequest = transaction.objectStore("textures").get(url);
  14182. getRequest.onsuccess = function (event) {
  14183. texture = (event.target).result;
  14184. };
  14185. getRequest.onerror = function (event) {
  14186. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14187. image.src = url;
  14188. };
  14189. }
  14190. else {
  14191. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14192. image.src = url;
  14193. }
  14194. };
  14195. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14196. var _this = this;
  14197. if (this.isSupported) {
  14198. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14199. var generateBlobUrl = function () {
  14200. var blobTextureURL;
  14201. if (blob) {
  14202. var URL = window.URL || window.webkitURL;
  14203. try {
  14204. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14205. }
  14206. catch (ex) {
  14207. blobTextureURL = URL.createObjectURL(blob);
  14208. }
  14209. }
  14210. image.src = blobTextureURL;
  14211. };
  14212. if (BABYLON.Database.isUASupportingBlobStorage) {
  14213. var xhr = new XMLHttpRequest(), blob;
  14214. xhr.open("GET", url, true);
  14215. xhr.responseType = "blob";
  14216. xhr.addEventListener("load", function () {
  14217. if (xhr.status === 200) {
  14218. // Blob as response (XHR2)
  14219. blob = xhr.response;
  14220. var transaction = _this.db.transaction(["textures"], "readwrite");
  14221. // the transaction could abort because of a QuotaExceededError error
  14222. transaction.onabort = function (event) {
  14223. try {
  14224. if (event.srcElement.error.name === "QuotaExceededError") {
  14225. this.hasReachedQuota = true;
  14226. }
  14227. }
  14228. catch (ex) {
  14229. }
  14230. generateBlobUrl();
  14231. };
  14232. transaction.oncomplete = function (event) {
  14233. generateBlobUrl();
  14234. };
  14235. var newTexture = { textureUrl: url, data: blob };
  14236. try {
  14237. // Put the blob into the dabase
  14238. var addRequest = transaction.objectStore("textures").put(newTexture);
  14239. addRequest.onsuccess = function (event) {
  14240. };
  14241. addRequest.onerror = function (event) {
  14242. generateBlobUrl();
  14243. };
  14244. }
  14245. catch (ex) {
  14246. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14247. if (ex.code === 25) {
  14248. BABYLON.Database.isUASupportingBlobStorage = false;
  14249. }
  14250. image.src = url;
  14251. }
  14252. }
  14253. else {
  14254. image.src = url;
  14255. }
  14256. }, false);
  14257. xhr.addEventListener("error", function (event) {
  14258. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14259. image.src = url;
  14260. }, false);
  14261. xhr.send();
  14262. }
  14263. else {
  14264. image.src = url;
  14265. }
  14266. }
  14267. else {
  14268. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14269. image.src = url;
  14270. }
  14271. };
  14272. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14273. var _this = this;
  14274. var updateVersion = function (event) {
  14275. // the version is not yet in the DB or we need to update it
  14276. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14277. };
  14278. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14279. };
  14280. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14281. var _this = this;
  14282. if (this.isSupported) {
  14283. var version;
  14284. try {
  14285. var transaction = this.db.transaction(["versions"]);
  14286. transaction.oncomplete = function (event) {
  14287. if (version) {
  14288. // If the version in the JSON file is > than the version in DB
  14289. if (_this.manifestVersionFound > version.data) {
  14290. _this.mustUpdateRessources = true;
  14291. updateInDBCallback();
  14292. }
  14293. else {
  14294. callback(version.data);
  14295. }
  14296. }
  14297. else {
  14298. _this.mustUpdateRessources = true;
  14299. updateInDBCallback();
  14300. }
  14301. };
  14302. transaction.onabort = function (event) {
  14303. callback(-1);
  14304. };
  14305. var getRequest = transaction.objectStore("versions").get(url);
  14306. getRequest.onsuccess = function (event) {
  14307. version = (event.target).result;
  14308. };
  14309. getRequest.onerror = function (event) {
  14310. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14311. callback(-1);
  14312. };
  14313. }
  14314. catch (ex) {
  14315. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14316. callback(-1);
  14317. }
  14318. }
  14319. else {
  14320. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14321. callback(-1);
  14322. }
  14323. };
  14324. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14325. var _this = this;
  14326. if (this.isSupported && !this.hasReachedQuota) {
  14327. try {
  14328. // Open a transaction to the database
  14329. var transaction = this.db.transaction(["versions"], "readwrite");
  14330. // the transaction could abort because of a QuotaExceededError error
  14331. transaction.onabort = function (event) {
  14332. try {
  14333. if (event.srcElement.error.name === "QuotaExceededError") {
  14334. _this.hasReachedQuota = true;
  14335. }
  14336. }
  14337. catch (ex) {
  14338. }
  14339. callback(-1);
  14340. };
  14341. transaction.oncomplete = function (event) {
  14342. callback(_this.manifestVersionFound);
  14343. };
  14344. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14345. // Put the scene into the database
  14346. var addRequest = transaction.objectStore("versions").put(newVersion);
  14347. addRequest.onsuccess = function (event) {
  14348. };
  14349. addRequest.onerror = function (event) {
  14350. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14351. };
  14352. }
  14353. catch (ex) {
  14354. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14355. callback(-1);
  14356. }
  14357. }
  14358. else {
  14359. callback(-1);
  14360. }
  14361. };
  14362. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  14363. var _this = this;
  14364. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  14365. var saveAndLoadFile = function (event) {
  14366. // the scene is not yet in the DB, let's try to save it
  14367. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  14368. };
  14369. this._checkVersionFromDB(completeUrl, function (version) {
  14370. if (version !== -1) {
  14371. if (!_this.mustUpdateRessources) {
  14372. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  14373. }
  14374. else {
  14375. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  14376. }
  14377. }
  14378. else {
  14379. errorCallback();
  14380. }
  14381. });
  14382. };
  14383. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  14384. if (this.isSupported) {
  14385. var targetStore;
  14386. if (url.indexOf(".babylon") !== -1) {
  14387. targetStore = "scenes";
  14388. }
  14389. else {
  14390. targetStore = "textures";
  14391. }
  14392. var file;
  14393. var transaction = this.db.transaction([targetStore]);
  14394. transaction.oncomplete = function (event) {
  14395. if (file) {
  14396. callback(file.data);
  14397. }
  14398. else {
  14399. notInDBCallback();
  14400. }
  14401. };
  14402. transaction.onabort = function (event) {
  14403. notInDBCallback();
  14404. };
  14405. var getRequest = transaction.objectStore(targetStore).get(url);
  14406. getRequest.onsuccess = function (event) {
  14407. file = (event.target).result;
  14408. };
  14409. getRequest.onerror = function (event) {
  14410. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  14411. notInDBCallback();
  14412. };
  14413. }
  14414. else {
  14415. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14416. callback();
  14417. }
  14418. };
  14419. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  14420. var _this = this;
  14421. if (this.isSupported) {
  14422. var targetStore;
  14423. if (url.indexOf(".babylon") !== -1) {
  14424. targetStore = "scenes";
  14425. }
  14426. else {
  14427. targetStore = "textures";
  14428. }
  14429. // Create XHR
  14430. var xhr = new XMLHttpRequest(), fileData;
  14431. xhr.open("GET", url, true);
  14432. if (useArrayBuffer) {
  14433. xhr.responseType = "arraybuffer";
  14434. }
  14435. xhr.onprogress = progressCallback;
  14436. xhr.addEventListener("load", function () {
  14437. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  14438. // Blob as response (XHR2)
  14439. //fileData = xhr.responseText;
  14440. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  14441. if (!_this.hasReachedQuota) {
  14442. // Open a transaction to the database
  14443. var transaction = _this.db.transaction([targetStore], "readwrite");
  14444. // the transaction could abort because of a QuotaExceededError error
  14445. transaction.onabort = function (event) {
  14446. try {
  14447. if (event.srcElement.error.name === "QuotaExceededError") {
  14448. this.hasReachedQuota = true;
  14449. }
  14450. }
  14451. catch (ex) {
  14452. }
  14453. callback(fileData);
  14454. };
  14455. transaction.oncomplete = function (event) {
  14456. callback(fileData);
  14457. };
  14458. var newFile;
  14459. if (targetStore === "scenes") {
  14460. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  14461. }
  14462. else {
  14463. newFile = { textureUrl: url, data: fileData };
  14464. }
  14465. try {
  14466. // Put the scene into the database
  14467. var addRequest = transaction.objectStore(targetStore).put(newFile);
  14468. addRequest.onsuccess = function (event) {
  14469. };
  14470. addRequest.onerror = function (event) {
  14471. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  14472. };
  14473. }
  14474. catch (ex) {
  14475. callback(fileData);
  14476. }
  14477. }
  14478. else {
  14479. callback(fileData);
  14480. }
  14481. }
  14482. else {
  14483. callback();
  14484. }
  14485. }, false);
  14486. xhr.addEventListener("error", function (event) {
  14487. BABYLON.Tools.Error("error on XHR request.");
  14488. callback();
  14489. }, false);
  14490. xhr.send();
  14491. }
  14492. else {
  14493. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14494. callback();
  14495. }
  14496. };
  14497. Database.isUASupportingBlobStorage = true;
  14498. Database.parseURL = function (url) {
  14499. var a = document.createElement('a');
  14500. a.href = url;
  14501. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  14502. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  14503. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  14504. return absLocation;
  14505. };
  14506. Database.ReturnFullUrlLocation = function (url) {
  14507. if (url.indexOf("http:/") === -1) {
  14508. return (BABYLON.Database.parseURL(window.location.href) + url);
  14509. }
  14510. else {
  14511. return url;
  14512. }
  14513. };
  14514. return Database;
  14515. })();
  14516. BABYLON.Database = Database;
  14517. })(BABYLON || (BABYLON = {}));
  14518. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  14519. (function (BABYLON) {
  14520. var SpriteManager = (function () {
  14521. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  14522. this.name = name;
  14523. this.cellSize = cellSize;
  14524. this.sprites = new Array();
  14525. this.renderingGroupId = 0;
  14526. this.fogEnabled = true;
  14527. this._vertexDeclaration = [3, 4, 4, 4];
  14528. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  14529. this._capacity = capacity;
  14530. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  14531. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14532. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14533. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  14534. this._scene = scene;
  14535. this._scene.spriteManagers.push(this);
  14536. // VBO
  14537. this._vertexDeclaration = [3, 4, 4, 4];
  14538. this._vertexStrideSize = 15 * 4;
  14539. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14540. var indices = [];
  14541. var index = 0;
  14542. for (var count = 0; count < capacity; count++) {
  14543. indices.push(index);
  14544. indices.push(index + 1);
  14545. indices.push(index + 2);
  14546. indices.push(index);
  14547. indices.push(index + 2);
  14548. indices.push(index + 3);
  14549. index += 4;
  14550. }
  14551. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14552. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14553. // Effects
  14554. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  14555. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  14556. }
  14557. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  14558. var arrayOffset = index * 15;
  14559. if (offsetX == 0)
  14560. offsetX = this._epsilon;
  14561. else if (offsetX == 1)
  14562. offsetX = 1 - this._epsilon;
  14563. if (offsetY == 0)
  14564. offsetY = this._epsilon;
  14565. else if (offsetY == 1)
  14566. offsetY = 1 - this._epsilon;
  14567. this._vertices[arrayOffset] = sprite.position.x;
  14568. this._vertices[arrayOffset + 1] = sprite.position.y;
  14569. this._vertices[arrayOffset + 2] = sprite.position.z;
  14570. this._vertices[arrayOffset + 3] = sprite.angle;
  14571. this._vertices[arrayOffset + 4] = sprite.size;
  14572. this._vertices[arrayOffset + 5] = offsetX;
  14573. this._vertices[arrayOffset + 6] = offsetY;
  14574. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  14575. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  14576. var offset = (sprite.cellIndex / rowSize) >> 0;
  14577. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  14578. this._vertices[arrayOffset + 10] = offset;
  14579. // Color
  14580. this._vertices[arrayOffset + 11] = sprite.color.r;
  14581. this._vertices[arrayOffset + 12] = sprite.color.g;
  14582. this._vertices[arrayOffset + 13] = sprite.color.b;
  14583. this._vertices[arrayOffset + 14] = sprite.color.a;
  14584. };
  14585. SpriteManager.prototype.render = function () {
  14586. // Check
  14587. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  14588. return;
  14589. var engine = this._scene.getEngine();
  14590. var baseSize = this._spriteTexture.getBaseSize();
  14591. // Sprites
  14592. var deltaTime = engine.getDeltaTime();
  14593. var max = Math.min(this._capacity, this.sprites.length);
  14594. var rowSize = baseSize.width / this.cellSize;
  14595. var offset = 0;
  14596. for (var index = 0; index < max; index++) {
  14597. var sprite = this.sprites[index];
  14598. if (!sprite) {
  14599. continue;
  14600. }
  14601. sprite._animate(deltaTime);
  14602. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  14603. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  14604. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  14605. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  14606. }
  14607. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14608. // Render
  14609. var effect = this._effectBase;
  14610. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14611. effect = this._effectFog;
  14612. }
  14613. engine.enableEffect(effect);
  14614. var viewMatrix = this._scene.getViewMatrix();
  14615. effect.setTexture("diffuseSampler", this._spriteTexture);
  14616. effect.setMatrix("view", viewMatrix);
  14617. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14618. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  14619. // Fog
  14620. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14621. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  14622. effect.setColor3("vFogColor", this._scene.fogColor);
  14623. }
  14624. // VBOs
  14625. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14626. // Draw order
  14627. effect.setBool("alphaTest", true);
  14628. engine.setColorWrite(false);
  14629. engine.draw(true, 0, max * 6);
  14630. engine.setColorWrite(true);
  14631. effect.setBool("alphaTest", false);
  14632. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14633. engine.draw(true, 0, max * 6);
  14634. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14635. };
  14636. SpriteManager.prototype.dispose = function () {
  14637. if (this._vertexBuffer) {
  14638. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14639. this._vertexBuffer = null;
  14640. }
  14641. if (this._indexBuffer) {
  14642. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14643. this._indexBuffer = null;
  14644. }
  14645. if (this._spriteTexture) {
  14646. this._spriteTexture.dispose();
  14647. this._spriteTexture = null;
  14648. }
  14649. // Remove from scene
  14650. var index = this._scene.spriteManagers.indexOf(this);
  14651. this._scene.spriteManagers.splice(index, 1);
  14652. // Callback
  14653. if (this.onDispose) {
  14654. this.onDispose();
  14655. }
  14656. };
  14657. return SpriteManager;
  14658. })();
  14659. BABYLON.SpriteManager = SpriteManager;
  14660. })(BABYLON || (BABYLON = {}));
  14661. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  14662. (function (BABYLON) {
  14663. var Sprite = (function () {
  14664. function Sprite(name, manager) {
  14665. this.name = name;
  14666. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14667. this.size = 1.0;
  14668. this.angle = 0;
  14669. this.cellIndex = 0;
  14670. this.invertU = 0;
  14671. this.invertV = 0;
  14672. this.animations = new Array();
  14673. this._animationStarted = false;
  14674. this._loopAnimation = false;
  14675. this._fromIndex = 0;
  14676. this._toIndex = 0;
  14677. this._delay = 0;
  14678. this._direction = 1;
  14679. this._frameCount = 0;
  14680. this._time = 0;
  14681. this._manager = manager;
  14682. this._manager.sprites.push(this);
  14683. this.position = BABYLON.Vector3.Zero();
  14684. }
  14685. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  14686. this._fromIndex = from;
  14687. this._toIndex = to;
  14688. this._loopAnimation = loop;
  14689. this._delay = delay;
  14690. this._animationStarted = true;
  14691. this._direction = from < to ? 1 : -1;
  14692. this.cellIndex = from;
  14693. this._time = 0;
  14694. };
  14695. Sprite.prototype.stopAnimation = function () {
  14696. this._animationStarted = false;
  14697. };
  14698. Sprite.prototype._animate = function (deltaTime) {
  14699. if (!this._animationStarted)
  14700. return;
  14701. this._time += deltaTime;
  14702. if (this._time > this._delay) {
  14703. this._time = this._time % this._delay;
  14704. this.cellIndex += this._direction;
  14705. if (this.cellIndex == this._toIndex) {
  14706. if (this._loopAnimation) {
  14707. this.cellIndex = this._fromIndex;
  14708. }
  14709. else {
  14710. this._animationStarted = false;
  14711. if (this.disposeWhenFinishedAnimating) {
  14712. this.dispose();
  14713. }
  14714. }
  14715. }
  14716. }
  14717. };
  14718. Sprite.prototype.dispose = function () {
  14719. for (var i = 0; i < this._manager.sprites.length; i++) {
  14720. if (this._manager.sprites[i] == this) {
  14721. this._manager.sprites.splice(i, 1);
  14722. }
  14723. }
  14724. };
  14725. return Sprite;
  14726. })();
  14727. BABYLON.Sprite = Sprite;
  14728. })(BABYLON || (BABYLON = {}));
  14729. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  14730. (function (BABYLON) {
  14731. var Layer = (function () {
  14732. function Layer(name, imgUrl, scene, isBackground, color) {
  14733. this.name = name;
  14734. this._vertexDeclaration = [2];
  14735. this._vertexStrideSize = 2 * 4;
  14736. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  14737. this.isBackground = isBackground === undefined ? true : isBackground;
  14738. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  14739. this._scene = scene;
  14740. this._scene.layers.push(this);
  14741. // VBO
  14742. var vertices = [];
  14743. vertices.push(1, 1);
  14744. vertices.push(-1, 1);
  14745. vertices.push(-1, -1);
  14746. vertices.push(1, -1);
  14747. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14748. // Indices
  14749. var indices = [];
  14750. indices.push(0);
  14751. indices.push(1);
  14752. indices.push(2);
  14753. indices.push(0);
  14754. indices.push(2);
  14755. indices.push(3);
  14756. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14757. // Effects
  14758. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  14759. }
  14760. Layer.prototype.render = function () {
  14761. // Check
  14762. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  14763. return;
  14764. var engine = this._scene.getEngine();
  14765. // Render
  14766. engine.enableEffect(this._effect);
  14767. engine.setState(false);
  14768. // Texture
  14769. this._effect.setTexture("textureSampler", this.texture);
  14770. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  14771. // Color
  14772. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  14773. // VBOs
  14774. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14775. // Draw order
  14776. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14777. engine.draw(true, 0, 6);
  14778. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14779. };
  14780. Layer.prototype.dispose = function () {
  14781. if (this._vertexBuffer) {
  14782. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14783. this._vertexBuffer = null;
  14784. }
  14785. if (this._indexBuffer) {
  14786. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14787. this._indexBuffer = null;
  14788. }
  14789. if (this.texture) {
  14790. this.texture.dispose();
  14791. this.texture = null;
  14792. }
  14793. // Remove from scene
  14794. var index = this._scene.layers.indexOf(this);
  14795. this._scene.layers.splice(index, 1);
  14796. // Callback
  14797. if (this.onDispose) {
  14798. this.onDispose();
  14799. }
  14800. };
  14801. return Layer;
  14802. })();
  14803. BABYLON.Layer = Layer;
  14804. })(BABYLON || (BABYLON = {}));
  14805. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  14806. (function (BABYLON) {
  14807. var Particle = (function () {
  14808. function Particle() {
  14809. this.position = BABYLON.Vector3.Zero();
  14810. this.direction = BABYLON.Vector3.Zero();
  14811. this.color = new BABYLON.Color4(0, 0, 0, 0);
  14812. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  14813. this.lifeTime = 1.0;
  14814. this.age = 0;
  14815. this.size = 0;
  14816. this.angle = 0;
  14817. this.angularSpeed = 0;
  14818. }
  14819. Particle.prototype.copyTo = function (other) {
  14820. other.position.copyFrom(this.position);
  14821. other.direction.copyFrom(this.direction);
  14822. other.color.copyFrom(this.color);
  14823. other.colorStep.copyFrom(this.colorStep);
  14824. other.lifeTime = this.lifeTime;
  14825. other.age = this.age;
  14826. other.size = this.size;
  14827. other.angle = this.angle;
  14828. other.angularSpeed = this.angularSpeed;
  14829. };
  14830. return Particle;
  14831. })();
  14832. BABYLON.Particle = Particle;
  14833. })(BABYLON || (BABYLON = {}));
  14834. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  14835. (function (BABYLON) {
  14836. var randomNumber = function (min, max) {
  14837. if (min === max) {
  14838. return (min);
  14839. }
  14840. var random = Math.random();
  14841. return ((random * (max - min)) + min);
  14842. };
  14843. var ParticleSystem = (function () {
  14844. function ParticleSystem(name, capacity, scene, customEffect) {
  14845. var _this = this;
  14846. this.name = name;
  14847. this.renderingGroupId = 0;
  14848. this.emitter = null;
  14849. this.emitRate = 10;
  14850. this.manualEmitCount = -1;
  14851. this.updateSpeed = 0.01;
  14852. this.targetStopDuration = 0;
  14853. this.disposeOnStop = false;
  14854. this.minEmitPower = 1;
  14855. this.maxEmitPower = 1;
  14856. this.minLifeTime = 1;
  14857. this.maxLifeTime = 1;
  14858. this.minSize = 1;
  14859. this.maxSize = 1;
  14860. this.minAngularSpeed = 0;
  14861. this.maxAngularSpeed = 0;
  14862. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  14863. this.forceDepthWrite = false;
  14864. this.gravity = BABYLON.Vector3.Zero();
  14865. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  14866. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  14867. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  14868. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14869. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14870. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14871. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  14872. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14873. this.particles = new Array();
  14874. this._vertexDeclaration = [3, 4, 4];
  14875. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  14876. this._stockParticles = new Array();
  14877. this._newPartsExcess = 0;
  14878. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  14879. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  14880. this._scaledDirection = BABYLON.Vector3.Zero();
  14881. this._scaledGravity = BABYLON.Vector3.Zero();
  14882. this._currentRenderId = -1;
  14883. this._started = false;
  14884. this._stopped = false;
  14885. this._actualFrame = 0;
  14886. this.id = name;
  14887. this._capacity = capacity;
  14888. this._scene = scene;
  14889. this._customEffect = customEffect;
  14890. scene.particleSystems.push(this);
  14891. // VBO
  14892. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14893. var indices = [];
  14894. var index = 0;
  14895. for (var count = 0; count < capacity; count++) {
  14896. indices.push(index);
  14897. indices.push(index + 1);
  14898. indices.push(index + 2);
  14899. indices.push(index);
  14900. indices.push(index + 2);
  14901. indices.push(index + 3);
  14902. index += 4;
  14903. }
  14904. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14905. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14906. // Default behaviors
  14907. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  14908. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  14909. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  14910. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  14911. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  14912. };
  14913. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  14914. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  14915. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  14916. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  14917. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  14918. };
  14919. this.updateFunction = function (particles) {
  14920. for (var index = 0; index < particles.length; index++) {
  14921. var particle = particles[index];
  14922. particle.age += _this._scaledUpdateSpeed;
  14923. if (particle.age >= particle.lifeTime) {
  14924. _this.recycleParticle(particle);
  14925. index--;
  14926. continue;
  14927. }
  14928. else {
  14929. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  14930. particle.color.addInPlace(_this._scaledColorStep);
  14931. if (particle.color.a < 0)
  14932. particle.color.a = 0;
  14933. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  14934. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  14935. particle.position.addInPlace(_this._scaledDirection);
  14936. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  14937. particle.direction.addInPlace(_this._scaledGravity);
  14938. }
  14939. }
  14940. };
  14941. }
  14942. ParticleSystem.prototype.recycleParticle = function (particle) {
  14943. var lastParticle = this.particles.pop();
  14944. if (lastParticle !== particle) {
  14945. lastParticle.copyTo(particle);
  14946. this._stockParticles.push(lastParticle);
  14947. }
  14948. };
  14949. ParticleSystem.prototype.getCapacity = function () {
  14950. return this._capacity;
  14951. };
  14952. ParticleSystem.prototype.isAlive = function () {
  14953. return this._alive;
  14954. };
  14955. ParticleSystem.prototype.isStarted = function () {
  14956. return this._started;
  14957. };
  14958. ParticleSystem.prototype.start = function () {
  14959. this._started = true;
  14960. this._stopped = false;
  14961. this._actualFrame = 0;
  14962. };
  14963. ParticleSystem.prototype.stop = function () {
  14964. this._stopped = true;
  14965. };
  14966. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  14967. var offset = index * 11;
  14968. this._vertices[offset] = particle.position.x;
  14969. this._vertices[offset + 1] = particle.position.y;
  14970. this._vertices[offset + 2] = particle.position.z;
  14971. this._vertices[offset + 3] = particle.color.r;
  14972. this._vertices[offset + 4] = particle.color.g;
  14973. this._vertices[offset + 5] = particle.color.b;
  14974. this._vertices[offset + 6] = particle.color.a;
  14975. this._vertices[offset + 7] = particle.angle;
  14976. this._vertices[offset + 8] = particle.size;
  14977. this._vertices[offset + 9] = offsetX;
  14978. this._vertices[offset + 10] = offsetY;
  14979. };
  14980. ParticleSystem.prototype._update = function (newParticles) {
  14981. // Update current
  14982. this._alive = this.particles.length > 0;
  14983. this.updateFunction(this.particles);
  14984. // Add new ones
  14985. var worldMatrix;
  14986. if (this.emitter.position) {
  14987. worldMatrix = this.emitter.getWorldMatrix();
  14988. }
  14989. else {
  14990. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  14991. }
  14992. for (var index = 0; index < newParticles; index++) {
  14993. if (this.particles.length === this._capacity) {
  14994. break;
  14995. }
  14996. if (this._stockParticles.length !== 0) {
  14997. var particle = this._stockParticles.pop();
  14998. particle.age = 0;
  14999. }
  15000. else {
  15001. particle = new BABYLON.Particle();
  15002. }
  15003. this.particles.push(particle);
  15004. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15005. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15006. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15007. particle.size = randomNumber(this.minSize, this.maxSize);
  15008. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15009. this.startPositionFunction(worldMatrix, particle.position);
  15010. var step = randomNumber(0, 1.0);
  15011. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15012. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15013. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15014. }
  15015. };
  15016. ParticleSystem.prototype._getEffect = function () {
  15017. if (this._customEffect) {
  15018. return this._customEffect;
  15019. }
  15020. ;
  15021. var defines = [];
  15022. if (this._scene.clipPlane) {
  15023. defines.push("#define CLIPPLANE");
  15024. }
  15025. // Effect
  15026. var join = defines.join("\n");
  15027. if (this._cachedDefines !== join) {
  15028. this._cachedDefines = join;
  15029. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  15030. }
  15031. return this._effect;
  15032. };
  15033. ParticleSystem.prototype.animate = function () {
  15034. if (!this._started)
  15035. return;
  15036. var effect = this._getEffect();
  15037. // Check
  15038. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  15039. return;
  15040. if (this._currentRenderId === this._scene.getRenderId()) {
  15041. return;
  15042. }
  15043. this._currentRenderId = this._scene.getRenderId();
  15044. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  15045. // determine the number of particles we need to create
  15046. var emitCout;
  15047. if (this.manualEmitCount > -1) {
  15048. emitCout = this.manualEmitCount;
  15049. this.manualEmitCount = 0;
  15050. }
  15051. else {
  15052. emitCout = this.emitRate;
  15053. }
  15054. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  15055. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  15056. if (this._newPartsExcess > 1.0) {
  15057. newParticles += this._newPartsExcess >> 0;
  15058. this._newPartsExcess -= this._newPartsExcess >> 0;
  15059. }
  15060. this._alive = false;
  15061. if (!this._stopped) {
  15062. this._actualFrame += this._scaledUpdateSpeed;
  15063. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  15064. this.stop();
  15065. }
  15066. else {
  15067. newParticles = 0;
  15068. }
  15069. this._update(newParticles);
  15070. // Stopped?
  15071. if (this._stopped) {
  15072. if (!this._alive) {
  15073. this._started = false;
  15074. if (this.disposeOnStop) {
  15075. this._scene._toBeDisposed.push(this);
  15076. }
  15077. }
  15078. }
  15079. // Update VBO
  15080. var offset = 0;
  15081. for (var index = 0; index < this.particles.length; index++) {
  15082. var particle = this.particles[index];
  15083. this._appendParticleVertex(offset++, particle, 0, 0);
  15084. this._appendParticleVertex(offset++, particle, 1, 0);
  15085. this._appendParticleVertex(offset++, particle, 1, 1);
  15086. this._appendParticleVertex(offset++, particle, 0, 1);
  15087. }
  15088. var engine = this._scene.getEngine();
  15089. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15090. };
  15091. ParticleSystem.prototype.render = function () {
  15092. var effect = this._getEffect();
  15093. // Check
  15094. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  15095. return 0;
  15096. var engine = this._scene.getEngine();
  15097. // Render
  15098. engine.enableEffect(effect);
  15099. engine.setState(false);
  15100. var viewMatrix = this._scene.getViewMatrix();
  15101. effect.setTexture("diffuseSampler", this.particleTexture);
  15102. effect.setMatrix("view", viewMatrix);
  15103. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15104. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  15105. if (this._scene.clipPlane) {
  15106. var clipPlane = this._scene.clipPlane;
  15107. var invView = viewMatrix.clone();
  15108. invView.invert();
  15109. effect.setMatrix("invView", invView);
  15110. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15111. }
  15112. // VBOs
  15113. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15114. // Draw order
  15115. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  15116. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15117. }
  15118. else {
  15119. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15120. }
  15121. if (this.forceDepthWrite) {
  15122. engine.setDepthWrite(true);
  15123. }
  15124. engine.draw(true, 0, this.particles.length * 6);
  15125. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15126. return this.particles.length;
  15127. };
  15128. ParticleSystem.prototype.dispose = function () {
  15129. if (this._vertexBuffer) {
  15130. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15131. this._vertexBuffer = null;
  15132. }
  15133. if (this._indexBuffer) {
  15134. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15135. this._indexBuffer = null;
  15136. }
  15137. if (this.particleTexture) {
  15138. this.particleTexture.dispose();
  15139. this.particleTexture = null;
  15140. }
  15141. // Remove from scene
  15142. var index = this._scene.particleSystems.indexOf(this);
  15143. this._scene.particleSystems.splice(index, 1);
  15144. // Callback
  15145. if (this.onDispose) {
  15146. this.onDispose();
  15147. }
  15148. };
  15149. // Clone
  15150. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15151. var result = new ParticleSystem(name, this._capacity, this._scene);
  15152. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15153. if (newEmitter === undefined) {
  15154. newEmitter = this.emitter;
  15155. }
  15156. result.emitter = newEmitter;
  15157. if (this.particleTexture) {
  15158. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15159. }
  15160. result.start();
  15161. return result;
  15162. };
  15163. // Statics
  15164. ParticleSystem.BLENDMODE_ONEONE = 0;
  15165. ParticleSystem.BLENDMODE_STANDARD = 1;
  15166. return ParticleSystem;
  15167. })();
  15168. BABYLON.ParticleSystem = ParticleSystem;
  15169. })(BABYLON || (BABYLON = {}));
  15170. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15171. (function (BABYLON) {
  15172. var Animation = (function () {
  15173. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15174. this.name = name;
  15175. this.targetProperty = targetProperty;
  15176. this.framePerSecond = framePerSecond;
  15177. this.dataType = dataType;
  15178. this.loopMode = loopMode;
  15179. this._offsetsCache = {};
  15180. this._highLimitsCache = {};
  15181. this._stopped = false;
  15182. this.targetPropertyPath = targetProperty.split(".");
  15183. this.dataType = dataType;
  15184. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15185. }
  15186. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15187. var dataType = undefined;
  15188. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15189. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15190. }
  15191. else if (from instanceof BABYLON.Quaternion) {
  15192. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15193. }
  15194. else if (from instanceof BABYLON.Vector3) {
  15195. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15196. }
  15197. else if (from instanceof BABYLON.Vector2) {
  15198. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15199. }
  15200. else if (from instanceof BABYLON.Color3) {
  15201. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15202. }
  15203. if (dataType == undefined) {
  15204. return;
  15205. }
  15206. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15207. var keys = [];
  15208. keys.push({ frame: 0, value: from });
  15209. keys.push({ frame: totalFrame, value: to });
  15210. animation.setKeys(keys);
  15211. mesh.animations.push(animation);
  15212. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15213. };
  15214. // Methods
  15215. Animation.prototype.isStopped = function () {
  15216. return this._stopped;
  15217. };
  15218. Animation.prototype.getKeys = function () {
  15219. return this._keys;
  15220. };
  15221. Animation.prototype.getEasingFunction = function () {
  15222. return this._easingFunction;
  15223. };
  15224. Animation.prototype.setEasingFunction = function (easingFunction) {
  15225. this._easingFunction = easingFunction;
  15226. };
  15227. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15228. return startValue + (endValue - startValue) * gradient;
  15229. };
  15230. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15231. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15232. };
  15233. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15234. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15235. };
  15236. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15237. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15238. };
  15239. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15240. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15241. };
  15242. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15243. var startScale = new BABYLON.Vector3(0, 0, 0);
  15244. var startRotation = new BABYLON.Quaternion();
  15245. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15246. startValue.decompose(startScale, startRotation, startTranslation);
  15247. var endScale = new BABYLON.Vector3(0, 0, 0);
  15248. var endRotation = new BABYLON.Quaternion();
  15249. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15250. endValue.decompose(endScale, endRotation, endTranslation);
  15251. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15252. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15253. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15254. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15255. return result;
  15256. };
  15257. Animation.prototype.clone = function () {
  15258. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15259. clone.setKeys(this._keys);
  15260. return clone;
  15261. };
  15262. Animation.prototype.setKeys = function (values) {
  15263. this._keys = values.slice(0);
  15264. this._offsetsCache = {};
  15265. this._highLimitsCache = {};
  15266. };
  15267. Animation.prototype._getKeyValue = function (value) {
  15268. if (typeof value === "function") {
  15269. return value();
  15270. }
  15271. return value;
  15272. };
  15273. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15274. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15275. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15276. }
  15277. this.currentFrame = currentFrame;
  15278. for (var key = 0; key < this._keys.length; key++) {
  15279. // for each frame, we need the key just before the frame superior
  15280. if (this._keys[key + 1].frame >= currentFrame) {
  15281. var startValue = this._getKeyValue(this._keys[key].value);
  15282. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15283. // gradient : percent of currentFrame between the frame inf and the frame sup
  15284. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15285. // check for easingFunction and correction of gradient
  15286. if (this._easingFunction != null) {
  15287. gradient = this._easingFunction.ease(gradient);
  15288. }
  15289. switch (this.dataType) {
  15290. case Animation.ANIMATIONTYPE_FLOAT:
  15291. switch (loopMode) {
  15292. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15293. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15294. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15295. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15296. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15297. }
  15298. break;
  15299. case Animation.ANIMATIONTYPE_QUATERNION:
  15300. var quaternion = null;
  15301. switch (loopMode) {
  15302. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15303. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15304. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15305. break;
  15306. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15307. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15308. break;
  15309. }
  15310. return quaternion;
  15311. case Animation.ANIMATIONTYPE_VECTOR3:
  15312. switch (loopMode) {
  15313. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15314. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15315. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15316. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15317. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15318. }
  15319. case Animation.ANIMATIONTYPE_VECTOR2:
  15320. switch (loopMode) {
  15321. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15322. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15323. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15324. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15325. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15326. }
  15327. case Animation.ANIMATIONTYPE_COLOR3:
  15328. switch (loopMode) {
  15329. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15330. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15331. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15332. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15333. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15334. }
  15335. case Animation.ANIMATIONTYPE_MATRIX:
  15336. switch (loopMode) {
  15337. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15338. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15339. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15340. return startValue;
  15341. }
  15342. default:
  15343. break;
  15344. }
  15345. break;
  15346. }
  15347. }
  15348. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15349. };
  15350. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15351. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15352. this._stopped = true;
  15353. return false;
  15354. }
  15355. var returnValue = true;
  15356. // Adding a start key at frame 0 if missing
  15357. if (this._keys[0].frame !== 0) {
  15358. var newKey = { frame: 0, value: this._keys[0].value };
  15359. this._keys.splice(0, 0, newKey);
  15360. }
  15361. // Check limits
  15362. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  15363. from = this._keys[0].frame;
  15364. }
  15365. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  15366. to = this._keys[this._keys.length - 1].frame;
  15367. }
  15368. // Compute ratio
  15369. var range = to - from;
  15370. var offsetValue;
  15371. // ratio represents the frame delta between from and to
  15372. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  15373. var highLimitValue = 0;
  15374. if (ratio > range && !loop) {
  15375. returnValue = false;
  15376. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  15377. }
  15378. else {
  15379. // Get max value if required
  15380. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  15381. var keyOffset = to.toString() + from.toString();
  15382. if (!this._offsetsCache[keyOffset]) {
  15383. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15384. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15385. switch (this.dataType) {
  15386. case Animation.ANIMATIONTYPE_FLOAT:
  15387. this._offsetsCache[keyOffset] = toValue - fromValue;
  15388. break;
  15389. case Animation.ANIMATIONTYPE_QUATERNION:
  15390. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15391. break;
  15392. case Animation.ANIMATIONTYPE_VECTOR3:
  15393. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15394. case Animation.ANIMATIONTYPE_VECTOR2:
  15395. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15396. case Animation.ANIMATIONTYPE_COLOR3:
  15397. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15398. default:
  15399. break;
  15400. }
  15401. this._highLimitsCache[keyOffset] = toValue;
  15402. }
  15403. highLimitValue = this._highLimitsCache[keyOffset];
  15404. offsetValue = this._offsetsCache[keyOffset];
  15405. }
  15406. }
  15407. if (offsetValue === undefined) {
  15408. switch (this.dataType) {
  15409. case Animation.ANIMATIONTYPE_FLOAT:
  15410. offsetValue = 0;
  15411. break;
  15412. case Animation.ANIMATIONTYPE_QUATERNION:
  15413. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  15414. break;
  15415. case Animation.ANIMATIONTYPE_VECTOR3:
  15416. offsetValue = BABYLON.Vector3.Zero();
  15417. break;
  15418. case Animation.ANIMATIONTYPE_VECTOR2:
  15419. offsetValue = BABYLON.Vector2.Zero();
  15420. break;
  15421. case Animation.ANIMATIONTYPE_COLOR3:
  15422. offsetValue = BABYLON.Color3.Black();
  15423. }
  15424. }
  15425. // Compute value
  15426. var repeatCount = (ratio / range) >> 0;
  15427. var currentFrame = returnValue ? from + ratio % range : to;
  15428. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  15429. // Set value
  15430. if (this.targetPropertyPath.length > 1) {
  15431. var property = this._target[this.targetPropertyPath[0]];
  15432. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  15433. property = property[this.targetPropertyPath[index]];
  15434. }
  15435. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  15436. }
  15437. else {
  15438. this._target[this.targetPropertyPath[0]] = currentValue;
  15439. }
  15440. if (this._target.markAsDirty) {
  15441. this._target.markAsDirty(this.targetProperty);
  15442. }
  15443. if (!returnValue) {
  15444. this._stopped = true;
  15445. }
  15446. return returnValue;
  15447. };
  15448. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  15449. get: function () {
  15450. return Animation._ANIMATIONTYPE_FLOAT;
  15451. },
  15452. enumerable: true,
  15453. configurable: true
  15454. });
  15455. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  15456. get: function () {
  15457. return Animation._ANIMATIONTYPE_VECTOR3;
  15458. },
  15459. enumerable: true,
  15460. configurable: true
  15461. });
  15462. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  15463. get: function () {
  15464. return Animation._ANIMATIONTYPE_VECTOR2;
  15465. },
  15466. enumerable: true,
  15467. configurable: true
  15468. });
  15469. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  15470. get: function () {
  15471. return Animation._ANIMATIONTYPE_QUATERNION;
  15472. },
  15473. enumerable: true,
  15474. configurable: true
  15475. });
  15476. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  15477. get: function () {
  15478. return Animation._ANIMATIONTYPE_MATRIX;
  15479. },
  15480. enumerable: true,
  15481. configurable: true
  15482. });
  15483. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  15484. get: function () {
  15485. return Animation._ANIMATIONTYPE_COLOR3;
  15486. },
  15487. enumerable: true,
  15488. configurable: true
  15489. });
  15490. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  15491. get: function () {
  15492. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  15493. },
  15494. enumerable: true,
  15495. configurable: true
  15496. });
  15497. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  15498. get: function () {
  15499. return Animation._ANIMATIONLOOPMODE_CYCLE;
  15500. },
  15501. enumerable: true,
  15502. configurable: true
  15503. });
  15504. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  15505. get: function () {
  15506. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  15507. },
  15508. enumerable: true,
  15509. configurable: true
  15510. });
  15511. // Statics
  15512. Animation._ANIMATIONTYPE_FLOAT = 0;
  15513. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  15514. Animation._ANIMATIONTYPE_QUATERNION = 2;
  15515. Animation._ANIMATIONTYPE_MATRIX = 3;
  15516. Animation._ANIMATIONTYPE_COLOR3 = 4;
  15517. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  15518. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  15519. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  15520. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  15521. return Animation;
  15522. })();
  15523. BABYLON.Animation = Animation;
  15524. })(BABYLON || (BABYLON = {}));
  15525. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  15526. (function (BABYLON) {
  15527. var Animatable = (function () {
  15528. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  15529. if (fromFrame === void 0) { fromFrame = 0; }
  15530. if (toFrame === void 0) { toFrame = 100; }
  15531. if (loopAnimation === void 0) { loopAnimation = false; }
  15532. if (speedRatio === void 0) { speedRatio = 1.0; }
  15533. this.target = target;
  15534. this.fromFrame = fromFrame;
  15535. this.toFrame = toFrame;
  15536. this.loopAnimation = loopAnimation;
  15537. this.speedRatio = speedRatio;
  15538. this.onAnimationEnd = onAnimationEnd;
  15539. this._animations = new Array();
  15540. this._paused = false;
  15541. this.animationStarted = false;
  15542. if (animations) {
  15543. this.appendAnimations(target, animations);
  15544. }
  15545. this._scene = scene;
  15546. scene._activeAnimatables.push(this);
  15547. }
  15548. // Methods
  15549. Animatable.prototype.appendAnimations = function (target, animations) {
  15550. for (var index = 0; index < animations.length; index++) {
  15551. var animation = animations[index];
  15552. animation._target = target;
  15553. this._animations.push(animation);
  15554. }
  15555. };
  15556. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  15557. var animations = this._animations;
  15558. for (var index = 0; index < animations.length; index++) {
  15559. if (animations[index].targetProperty === property) {
  15560. return animations[index];
  15561. }
  15562. }
  15563. return null;
  15564. };
  15565. Animatable.prototype.pause = function () {
  15566. if (this._paused) {
  15567. return;
  15568. }
  15569. this._paused = true;
  15570. };
  15571. Animatable.prototype.restart = function () {
  15572. this._paused = false;
  15573. };
  15574. Animatable.prototype.stop = function () {
  15575. var index = this._scene._activeAnimatables.indexOf(this);
  15576. if (index > -1) {
  15577. this._scene._activeAnimatables.splice(index, 1);
  15578. }
  15579. if (this.onAnimationEnd) {
  15580. this.onAnimationEnd();
  15581. }
  15582. };
  15583. Animatable.prototype._animate = function (delay) {
  15584. if (this._paused) {
  15585. if (!this._pausedDelay) {
  15586. this._pausedDelay = delay;
  15587. }
  15588. return true;
  15589. }
  15590. if (!this._localDelayOffset) {
  15591. this._localDelayOffset = delay;
  15592. }
  15593. else if (this._pausedDelay) {
  15594. this._localDelayOffset += delay - this._pausedDelay;
  15595. this._pausedDelay = null;
  15596. }
  15597. // Animating
  15598. var running = false;
  15599. var animations = this._animations;
  15600. for (var index = 0; index < animations.length; index++) {
  15601. var animation = animations[index];
  15602. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  15603. running = running || isRunning;
  15604. }
  15605. if (!running && this.onAnimationEnd) {
  15606. this.onAnimationEnd();
  15607. }
  15608. return running;
  15609. };
  15610. return Animatable;
  15611. })();
  15612. BABYLON.Animatable = Animatable;
  15613. })(BABYLON || (BABYLON = {}));
  15614. //# sourceMappingURL=babylon.animatable.js.map
  15615. var BABYLON;
  15616. (function (BABYLON) {
  15617. var EasingFunction = (function () {
  15618. function EasingFunction() {
  15619. // Properties
  15620. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  15621. }
  15622. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  15623. get: function () {
  15624. return EasingFunction._EASINGMODE_EASEIN;
  15625. },
  15626. enumerable: true,
  15627. configurable: true
  15628. });
  15629. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  15630. get: function () {
  15631. return EasingFunction._EASINGMODE_EASEOUT;
  15632. },
  15633. enumerable: true,
  15634. configurable: true
  15635. });
  15636. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  15637. get: function () {
  15638. return EasingFunction._EASINGMODE_EASEINOUT;
  15639. },
  15640. enumerable: true,
  15641. configurable: true
  15642. });
  15643. EasingFunction.prototype.setEasingMode = function (easingMode) {
  15644. var n = Math.min(Math.max(easingMode, 0), 2);
  15645. this._easingMode = n;
  15646. };
  15647. EasingFunction.prototype.getEasingMode = function () {
  15648. return this._easingMode;
  15649. };
  15650. EasingFunction.prototype.easeInCore = function (gradient) {
  15651. throw new Error('You must implement this method');
  15652. };
  15653. EasingFunction.prototype.ease = function (gradient) {
  15654. switch (this._easingMode) {
  15655. case EasingFunction.EASINGMODE_EASEIN:
  15656. return this.easeInCore(gradient);
  15657. case EasingFunction.EASINGMODE_EASEOUT:
  15658. return (1 - this.easeInCore(1 - gradient));
  15659. }
  15660. if (gradient >= 0.5) {
  15661. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  15662. }
  15663. return (this.easeInCore(gradient * 2) * 0.5);
  15664. };
  15665. //Statics
  15666. EasingFunction._EASINGMODE_EASEIN = 0;
  15667. EasingFunction._EASINGMODE_EASEOUT = 1;
  15668. EasingFunction._EASINGMODE_EASEINOUT = 2;
  15669. return EasingFunction;
  15670. })();
  15671. BABYLON.EasingFunction = EasingFunction;
  15672. var CircleEase = (function (_super) {
  15673. __extends(CircleEase, _super);
  15674. function CircleEase() {
  15675. _super.apply(this, arguments);
  15676. }
  15677. CircleEase.prototype.easeInCore = function (gradient) {
  15678. gradient = Math.max(0, Math.min(1, gradient));
  15679. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  15680. };
  15681. return CircleEase;
  15682. })(EasingFunction);
  15683. BABYLON.CircleEase = CircleEase;
  15684. var BackEase = (function (_super) {
  15685. __extends(BackEase, _super);
  15686. function BackEase(amplitude) {
  15687. if (amplitude === void 0) { amplitude = 1; }
  15688. _super.call(this);
  15689. this.amplitude = amplitude;
  15690. }
  15691. BackEase.prototype.easeInCore = function (gradient) {
  15692. var num = Math.max(0, this.amplitude);
  15693. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  15694. };
  15695. return BackEase;
  15696. })(EasingFunction);
  15697. BABYLON.BackEase = BackEase;
  15698. var BounceEase = (function (_super) {
  15699. __extends(BounceEase, _super);
  15700. function BounceEase(bounces, bounciness) {
  15701. if (bounces === void 0) { bounces = 3; }
  15702. if (bounciness === void 0) { bounciness = 2; }
  15703. _super.call(this);
  15704. this.bounces = bounces;
  15705. this.bounciness = bounciness;
  15706. }
  15707. BounceEase.prototype.easeInCore = function (gradient) {
  15708. var y = Math.max(0.0, this.bounces);
  15709. var bounciness = this.bounciness;
  15710. if (bounciness <= 1.0) {
  15711. bounciness = 1.001;
  15712. }
  15713. var num9 = Math.pow(bounciness, y);
  15714. var num5 = 1.0 - bounciness;
  15715. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  15716. var num15 = gradient * num4;
  15717. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  15718. var num3 = Math.floor(num65);
  15719. var num13 = num3 + 1.0;
  15720. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  15721. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  15722. var num7 = (num8 + num12) * 0.5;
  15723. var num6 = gradient - num7;
  15724. var num2 = num7 - num8;
  15725. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  15726. };
  15727. return BounceEase;
  15728. })(EasingFunction);
  15729. BABYLON.BounceEase = BounceEase;
  15730. var CubicEase = (function (_super) {
  15731. __extends(CubicEase, _super);
  15732. function CubicEase() {
  15733. _super.apply(this, arguments);
  15734. }
  15735. CubicEase.prototype.easeInCore = function (gradient) {
  15736. return (gradient * gradient * gradient);
  15737. };
  15738. return CubicEase;
  15739. })(EasingFunction);
  15740. BABYLON.CubicEase = CubicEase;
  15741. var ElasticEase = (function (_super) {
  15742. __extends(ElasticEase, _super);
  15743. function ElasticEase(oscillations, springiness) {
  15744. if (oscillations === void 0) { oscillations = 3; }
  15745. if (springiness === void 0) { springiness = 3; }
  15746. _super.call(this);
  15747. this.oscillations = oscillations;
  15748. this.springiness = springiness;
  15749. }
  15750. ElasticEase.prototype.easeInCore = function (gradient) {
  15751. var num2;
  15752. var num3 = Math.max(0.0, this.oscillations);
  15753. var num = Math.max(0.0, this.springiness);
  15754. if (num == 0) {
  15755. num2 = gradient;
  15756. }
  15757. else {
  15758. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  15759. }
  15760. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  15761. };
  15762. return ElasticEase;
  15763. })(EasingFunction);
  15764. BABYLON.ElasticEase = ElasticEase;
  15765. var ExponentialEase = (function (_super) {
  15766. __extends(ExponentialEase, _super);
  15767. function ExponentialEase(exponent) {
  15768. if (exponent === void 0) { exponent = 2; }
  15769. _super.call(this);
  15770. this.exponent = exponent;
  15771. }
  15772. ExponentialEase.prototype.easeInCore = function (gradient) {
  15773. if (this.exponent <= 0) {
  15774. return gradient;
  15775. }
  15776. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  15777. };
  15778. return ExponentialEase;
  15779. })(EasingFunction);
  15780. BABYLON.ExponentialEase = ExponentialEase;
  15781. var PowerEase = (function (_super) {
  15782. __extends(PowerEase, _super);
  15783. function PowerEase(power) {
  15784. if (power === void 0) { power = 2; }
  15785. _super.call(this);
  15786. this.power = power;
  15787. }
  15788. PowerEase.prototype.easeInCore = function (gradient) {
  15789. var y = Math.max(0.0, this.power);
  15790. return Math.pow(gradient, y);
  15791. };
  15792. return PowerEase;
  15793. })(EasingFunction);
  15794. BABYLON.PowerEase = PowerEase;
  15795. var QuadraticEase = (function (_super) {
  15796. __extends(QuadraticEase, _super);
  15797. function QuadraticEase() {
  15798. _super.apply(this, arguments);
  15799. }
  15800. QuadraticEase.prototype.easeInCore = function (gradient) {
  15801. return (gradient * gradient);
  15802. };
  15803. return QuadraticEase;
  15804. })(EasingFunction);
  15805. BABYLON.QuadraticEase = QuadraticEase;
  15806. var QuarticEase = (function (_super) {
  15807. __extends(QuarticEase, _super);
  15808. function QuarticEase() {
  15809. _super.apply(this, arguments);
  15810. }
  15811. QuarticEase.prototype.easeInCore = function (gradient) {
  15812. return (gradient * gradient * gradient * gradient);
  15813. };
  15814. return QuarticEase;
  15815. })(EasingFunction);
  15816. BABYLON.QuarticEase = QuarticEase;
  15817. var QuinticEase = (function (_super) {
  15818. __extends(QuinticEase, _super);
  15819. function QuinticEase() {
  15820. _super.apply(this, arguments);
  15821. }
  15822. QuinticEase.prototype.easeInCore = function (gradient) {
  15823. return (gradient * gradient * gradient * gradient * gradient);
  15824. };
  15825. return QuinticEase;
  15826. })(EasingFunction);
  15827. BABYLON.QuinticEase = QuinticEase;
  15828. var SineEase = (function (_super) {
  15829. __extends(SineEase, _super);
  15830. function SineEase() {
  15831. _super.apply(this, arguments);
  15832. }
  15833. SineEase.prototype.easeInCore = function (gradient) {
  15834. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  15835. };
  15836. return SineEase;
  15837. })(EasingFunction);
  15838. BABYLON.SineEase = SineEase;
  15839. var BezierCurveEase = (function (_super) {
  15840. __extends(BezierCurveEase, _super);
  15841. function BezierCurveEase(x1, y1, x2, y2) {
  15842. if (x1 === void 0) { x1 = 0; }
  15843. if (y1 === void 0) { y1 = 0; }
  15844. if (x2 === void 0) { x2 = 1; }
  15845. if (y2 === void 0) { y2 = 1; }
  15846. _super.call(this);
  15847. this.x1 = x1;
  15848. this.y1 = y1;
  15849. this.x2 = x2;
  15850. this.y2 = y2;
  15851. }
  15852. BezierCurveEase.prototype.easeInCore = function (gradient) {
  15853. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  15854. };
  15855. return BezierCurveEase;
  15856. })(EasingFunction);
  15857. BABYLON.BezierCurveEase = BezierCurveEase;
  15858. })(BABYLON || (BABYLON = {}));
  15859. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  15860. (function (BABYLON) {
  15861. var Octree = (function () {
  15862. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  15863. if (maxDepth === void 0) { maxDepth = 2; }
  15864. this.maxDepth = maxDepth;
  15865. this.dynamicContent = new Array();
  15866. this._maxBlockCapacity = maxBlockCapacity || 64;
  15867. this._selectionContent = new BABYLON.SmartArray(1024);
  15868. this._creationFunc = creationFunc;
  15869. }
  15870. // Methods
  15871. Octree.prototype.update = function (worldMin, worldMax, entries) {
  15872. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  15873. };
  15874. Octree.prototype.addMesh = function (entry) {
  15875. for (var index = 0; index < this.blocks.length; index++) {
  15876. var block = this.blocks[index];
  15877. block.addEntry(entry);
  15878. }
  15879. };
  15880. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  15881. this._selectionContent.reset();
  15882. for (var index = 0; index < this.blocks.length; index++) {
  15883. var block = this.blocks[index];
  15884. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  15885. }
  15886. if (allowDuplicate) {
  15887. this._selectionContent.concat(this.dynamicContent);
  15888. }
  15889. else {
  15890. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15891. }
  15892. return this._selectionContent;
  15893. };
  15894. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  15895. this._selectionContent.reset();
  15896. for (var index = 0; index < this.blocks.length; index++) {
  15897. var block = this.blocks[index];
  15898. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  15899. }
  15900. if (allowDuplicate) {
  15901. this._selectionContent.concat(this.dynamicContent);
  15902. }
  15903. else {
  15904. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15905. }
  15906. return this._selectionContent;
  15907. };
  15908. Octree.prototype.intersectsRay = function (ray) {
  15909. this._selectionContent.reset();
  15910. for (var index = 0; index < this.blocks.length; index++) {
  15911. var block = this.blocks[index];
  15912. block.intersectsRay(ray, this._selectionContent);
  15913. }
  15914. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15915. return this._selectionContent;
  15916. };
  15917. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  15918. target.blocks = new Array();
  15919. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  15920. for (var x = 0; x < 2; x++) {
  15921. for (var y = 0; y < 2; y++) {
  15922. for (var z = 0; z < 2; z++) {
  15923. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  15924. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  15925. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  15926. block.addEntries(entries);
  15927. target.blocks.push(block);
  15928. }
  15929. }
  15930. }
  15931. };
  15932. Octree.CreationFuncForMeshes = function (entry, block) {
  15933. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15934. block.entries.push(entry);
  15935. }
  15936. };
  15937. Octree.CreationFuncForSubMeshes = function (entry, block) {
  15938. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15939. block.entries.push(entry);
  15940. }
  15941. };
  15942. return Octree;
  15943. })();
  15944. BABYLON.Octree = Octree;
  15945. })(BABYLON || (BABYLON = {}));
  15946. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  15947. (function (BABYLON) {
  15948. var OctreeBlock = (function () {
  15949. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  15950. this.entries = new Array();
  15951. this._boundingVectors = new Array();
  15952. this._capacity = capacity;
  15953. this._depth = depth;
  15954. this._maxDepth = maxDepth;
  15955. this._creationFunc = creationFunc;
  15956. this._minPoint = minPoint;
  15957. this._maxPoint = maxPoint;
  15958. this._boundingVectors.push(minPoint.clone());
  15959. this._boundingVectors.push(maxPoint.clone());
  15960. this._boundingVectors.push(minPoint.clone());
  15961. this._boundingVectors[2].x = maxPoint.x;
  15962. this._boundingVectors.push(minPoint.clone());
  15963. this._boundingVectors[3].y = maxPoint.y;
  15964. this._boundingVectors.push(minPoint.clone());
  15965. this._boundingVectors[4].z = maxPoint.z;
  15966. this._boundingVectors.push(maxPoint.clone());
  15967. this._boundingVectors[5].z = minPoint.z;
  15968. this._boundingVectors.push(maxPoint.clone());
  15969. this._boundingVectors[6].x = minPoint.x;
  15970. this._boundingVectors.push(maxPoint.clone());
  15971. this._boundingVectors[7].y = minPoint.y;
  15972. }
  15973. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  15974. // Property
  15975. get: function () {
  15976. return this._capacity;
  15977. },
  15978. enumerable: true,
  15979. configurable: true
  15980. });
  15981. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  15982. get: function () {
  15983. return this._minPoint;
  15984. },
  15985. enumerable: true,
  15986. configurable: true
  15987. });
  15988. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  15989. get: function () {
  15990. return this._maxPoint;
  15991. },
  15992. enumerable: true,
  15993. configurable: true
  15994. });
  15995. // Methods
  15996. OctreeBlock.prototype.addEntry = function (entry) {
  15997. if (this.blocks) {
  15998. for (var index = 0; index < this.blocks.length; index++) {
  15999. var block = this.blocks[index];
  16000. block.addEntry(entry);
  16001. }
  16002. return;
  16003. }
  16004. this._creationFunc(entry, this);
  16005. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16006. this.createInnerBlocks();
  16007. }
  16008. };
  16009. OctreeBlock.prototype.addEntries = function (entries) {
  16010. for (var index = 0; index < entries.length; index++) {
  16011. var mesh = entries[index];
  16012. this.addEntry(mesh);
  16013. }
  16014. };
  16015. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  16016. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  16017. if (this.blocks) {
  16018. for (var index = 0; index < this.blocks.length; index++) {
  16019. var block = this.blocks[index];
  16020. block.select(frustumPlanes, selection, allowDuplicate);
  16021. }
  16022. return;
  16023. }
  16024. if (allowDuplicate) {
  16025. selection.concat(this.entries);
  16026. }
  16027. else {
  16028. selection.concatWithNoDuplicate(this.entries);
  16029. }
  16030. }
  16031. };
  16032. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  16033. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  16034. if (this.blocks) {
  16035. for (var index = 0; index < this.blocks.length; index++) {
  16036. var block = this.blocks[index];
  16037. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  16038. }
  16039. return;
  16040. }
  16041. if (allowDuplicate) {
  16042. selection.concat(this.entries);
  16043. }
  16044. else {
  16045. selection.concatWithNoDuplicate(this.entries);
  16046. }
  16047. }
  16048. };
  16049. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  16050. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  16051. if (this.blocks) {
  16052. for (var index = 0; index < this.blocks.length; index++) {
  16053. var block = this.blocks[index];
  16054. block.intersectsRay(ray, selection);
  16055. }
  16056. return;
  16057. }
  16058. selection.concatWithNoDuplicate(this.entries);
  16059. }
  16060. };
  16061. OctreeBlock.prototype.createInnerBlocks = function () {
  16062. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  16063. };
  16064. return OctreeBlock;
  16065. })();
  16066. BABYLON.OctreeBlock = OctreeBlock;
  16067. })(BABYLON || (BABYLON = {}));
  16068. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  16069. (function (BABYLON) {
  16070. var Bone = (function () {
  16071. function Bone(name, skeleton, parentBone, matrix) {
  16072. this.name = name;
  16073. this.children = new Array();
  16074. this.animations = new Array();
  16075. this._worldTransform = new BABYLON.Matrix();
  16076. this._absoluteTransform = new BABYLON.Matrix();
  16077. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  16078. this._skeleton = skeleton;
  16079. this._matrix = matrix;
  16080. this._baseMatrix = matrix;
  16081. skeleton.bones.push(this);
  16082. if (parentBone) {
  16083. this._parent = parentBone;
  16084. parentBone.children.push(this);
  16085. }
  16086. else {
  16087. this._parent = null;
  16088. }
  16089. this._updateDifferenceMatrix();
  16090. }
  16091. // Members
  16092. Bone.prototype.getParent = function () {
  16093. return this._parent;
  16094. };
  16095. Bone.prototype.getLocalMatrix = function () {
  16096. return this._matrix;
  16097. };
  16098. Bone.prototype.getBaseMatrix = function () {
  16099. return this._baseMatrix;
  16100. };
  16101. Bone.prototype.getWorldMatrix = function () {
  16102. return this._worldTransform;
  16103. };
  16104. Bone.prototype.getInvertedAbsoluteTransform = function () {
  16105. return this._invertedAbsoluteTransform;
  16106. };
  16107. Bone.prototype.getAbsoluteMatrix = function () {
  16108. var matrix = this._matrix.clone();
  16109. var parent = this._parent;
  16110. while (parent) {
  16111. matrix = matrix.multiply(parent.getLocalMatrix());
  16112. parent = parent.getParent();
  16113. }
  16114. return matrix;
  16115. };
  16116. // Methods
  16117. Bone.prototype.updateMatrix = function (matrix) {
  16118. this._matrix = matrix;
  16119. this._skeleton._markAsDirty();
  16120. this._updateDifferenceMatrix();
  16121. };
  16122. Bone.prototype._updateDifferenceMatrix = function () {
  16123. if (this._parent) {
  16124. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  16125. }
  16126. else {
  16127. this._absoluteTransform.copyFrom(this._matrix);
  16128. }
  16129. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  16130. for (var index = 0; index < this.children.length; index++) {
  16131. this.children[index]._updateDifferenceMatrix();
  16132. }
  16133. };
  16134. Bone.prototype.markAsDirty = function () {
  16135. this._skeleton._markAsDirty();
  16136. };
  16137. return Bone;
  16138. })();
  16139. BABYLON.Bone = Bone;
  16140. })(BABYLON || (BABYLON = {}));
  16141. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16142. (function (BABYLON) {
  16143. var Skeleton = (function () {
  16144. function Skeleton(name, id, scene) {
  16145. this.name = name;
  16146. this.id = id;
  16147. this.bones = new Array();
  16148. this._isDirty = true;
  16149. this._identity = BABYLON.Matrix.Identity();
  16150. this.bones = [];
  16151. this._scene = scene;
  16152. scene.skeletons.push(this);
  16153. }
  16154. // Members
  16155. Skeleton.prototype.getTransformMatrices = function () {
  16156. return this._transformMatrices;
  16157. };
  16158. // Methods
  16159. Skeleton.prototype._markAsDirty = function () {
  16160. this._isDirty = true;
  16161. };
  16162. Skeleton.prototype.prepare = function () {
  16163. if (!this._isDirty) {
  16164. return;
  16165. }
  16166. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16167. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16168. }
  16169. for (var index = 0; index < this.bones.length; index++) {
  16170. var bone = this.bones[index];
  16171. var parentBone = bone.getParent();
  16172. if (parentBone) {
  16173. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16174. }
  16175. else {
  16176. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16177. }
  16178. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16179. }
  16180. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16181. this._isDirty = false;
  16182. };
  16183. Skeleton.prototype.getAnimatables = function () {
  16184. if (!this._animatables || this._animatables.length != this.bones.length) {
  16185. this._animatables = [];
  16186. for (var index = 0; index < this.bones.length; index++) {
  16187. this._animatables.push(this.bones[index]);
  16188. }
  16189. }
  16190. return this._animatables;
  16191. };
  16192. Skeleton.prototype.clone = function (name, id) {
  16193. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  16194. for (var index = 0; index < this.bones.length; index++) {
  16195. var source = this.bones[index];
  16196. var parentBone = null;
  16197. if (source.getParent()) {
  16198. var parentIndex = this.bones.indexOf(source.getParent());
  16199. parentBone = result.bones[parentIndex];
  16200. }
  16201. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16202. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16203. }
  16204. return result;
  16205. };
  16206. return Skeleton;
  16207. })();
  16208. BABYLON.Skeleton = Skeleton;
  16209. })(BABYLON || (BABYLON = {}));
  16210. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16211. (function (BABYLON) {
  16212. var PostProcess = (function () {
  16213. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  16214. this.name = name;
  16215. this.width = -1;
  16216. this.height = -1;
  16217. this._reusable = false;
  16218. this._textures = new BABYLON.SmartArray(2);
  16219. this._currentRenderTextureInd = 0;
  16220. if (camera != null) {
  16221. this._camera = camera;
  16222. this._scene = camera.getScene();
  16223. camera.attachPostProcess(this);
  16224. this._engine = this._scene.getEngine();
  16225. }
  16226. else {
  16227. this._engine = engine;
  16228. }
  16229. this._renderRatio = ratio;
  16230. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16231. this._reusable = reusable || false;
  16232. samplers = samplers || [];
  16233. samplers.push("textureSampler");
  16234. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  16235. }
  16236. PostProcess.prototype.isReusable = function () {
  16237. return this._reusable;
  16238. };
  16239. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16240. camera = camera || this._camera;
  16241. var scene = camera.getScene();
  16242. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16243. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16244. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16245. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16246. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16247. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16248. if (this._textures.length > 0) {
  16249. for (var i = 0; i < this._textures.length; i++) {
  16250. this._engine._releaseTexture(this._textures.data[i]);
  16251. }
  16252. this._textures.reset();
  16253. }
  16254. this.width = desiredWidth;
  16255. this.height = desiredHeight;
  16256. 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 }));
  16257. if (this._reusable) {
  16258. 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 }));
  16259. }
  16260. if (this.onSizeChanged) {
  16261. this.onSizeChanged();
  16262. }
  16263. }
  16264. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16265. if (this.onActivate) {
  16266. this.onActivate(camera);
  16267. }
  16268. // Clear
  16269. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16270. if (this._reusable) {
  16271. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16272. }
  16273. };
  16274. PostProcess.prototype.apply = function () {
  16275. // Check
  16276. if (!this._effect.isReady())
  16277. return null;
  16278. // States
  16279. this._engine.enableEffect(this._effect);
  16280. this._engine.setState(false);
  16281. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16282. this._engine.setDepthBuffer(false);
  16283. this._engine.setDepthWrite(false);
  16284. // Texture
  16285. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16286. // Parameters
  16287. if (this.onApply) {
  16288. this.onApply(this._effect);
  16289. }
  16290. return this._effect;
  16291. };
  16292. PostProcess.prototype.dispose = function (camera) {
  16293. camera = camera || this._camera;
  16294. if (this._textures.length > 0) {
  16295. for (var i = 0; i < this._textures.length; i++) {
  16296. this._engine._releaseTexture(this._textures.data[i]);
  16297. }
  16298. this._textures.reset();
  16299. }
  16300. camera.detachPostProcess(this);
  16301. var index = camera._postProcesses.indexOf(this);
  16302. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  16303. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  16304. }
  16305. };
  16306. return PostProcess;
  16307. })();
  16308. BABYLON.PostProcess = PostProcess;
  16309. })(BABYLON || (BABYLON = {}));
  16310. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  16311. (function (BABYLON) {
  16312. var PostProcessManager = (function () {
  16313. function PostProcessManager(scene) {
  16314. this._vertexDeclaration = [2];
  16315. this._vertexStrideSize = 2 * 4;
  16316. this._scene = scene;
  16317. // VBO
  16318. var vertices = [];
  16319. vertices.push(1, 1);
  16320. vertices.push(-1, 1);
  16321. vertices.push(-1, -1);
  16322. vertices.push(1, -1);
  16323. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16324. // Indices
  16325. var indices = [];
  16326. indices.push(0);
  16327. indices.push(1);
  16328. indices.push(2);
  16329. indices.push(0);
  16330. indices.push(2);
  16331. indices.push(3);
  16332. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16333. }
  16334. // Methods
  16335. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16336. var postProcesses = this._scene.activeCamera._postProcesses;
  16337. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16338. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16339. return false;
  16340. }
  16341. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16342. return true;
  16343. };
  16344. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  16345. var postProcesses = this._scene.activeCamera._postProcesses;
  16346. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16347. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16348. return;
  16349. }
  16350. var engine = this._scene.getEngine();
  16351. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  16352. if (index < postProcessesTakenIndices.length - 1) {
  16353. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  16354. }
  16355. else {
  16356. if (targetTexture) {
  16357. engine.bindFramebuffer(targetTexture);
  16358. }
  16359. else {
  16360. engine.restoreDefaultFramebuffer();
  16361. }
  16362. }
  16363. if (doNotPresent) {
  16364. break;
  16365. }
  16366. var pp = postProcesses[postProcessesTakenIndices[index]];
  16367. var effect = pp.apply();
  16368. if (effect) {
  16369. if (pp.onBeforeRender) {
  16370. pp.onBeforeRender(effect);
  16371. }
  16372. // VBOs
  16373. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16374. // Draw order
  16375. engine.draw(true, 0, 6);
  16376. }
  16377. }
  16378. // Restore depth buffer
  16379. engine.setDepthBuffer(true);
  16380. engine.setDepthWrite(true);
  16381. };
  16382. PostProcessManager.prototype.dispose = function () {
  16383. if (this._vertexBuffer) {
  16384. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16385. this._vertexBuffer = null;
  16386. }
  16387. if (this._indexBuffer) {
  16388. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16389. this._indexBuffer = null;
  16390. }
  16391. };
  16392. return PostProcessManager;
  16393. })();
  16394. BABYLON.PostProcessManager = PostProcessManager;
  16395. })(BABYLON || (BABYLON = {}));
  16396. //# sourceMappingURL=babylon.postProcessManager.js.map
  16397. var BABYLON;
  16398. (function (BABYLON) {
  16399. var PassPostProcess = (function (_super) {
  16400. __extends(PassPostProcess, _super);
  16401. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16402. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  16403. }
  16404. return PassPostProcess;
  16405. })(BABYLON.PostProcess);
  16406. BABYLON.PassPostProcess = PassPostProcess;
  16407. })(BABYLON || (BABYLON = {}));
  16408. //# sourceMappingURL=babylon.passPostProcess.js.map
  16409. var BABYLON;
  16410. (function (BABYLON) {
  16411. var BlurPostProcess = (function (_super) {
  16412. __extends(BlurPostProcess, _super);
  16413. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  16414. var _this = this;
  16415. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  16416. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  16417. this.direction = direction;
  16418. this.blurWidth = blurWidth;
  16419. this.onApply = function (effect) {
  16420. effect.setFloat2("screenSize", _this.width, _this.height);
  16421. effect.setVector2("direction", _this.direction);
  16422. effect.setFloat("blurWidth", _this.blurWidth);
  16423. };
  16424. }
  16425. return BlurPostProcess;
  16426. })(BABYLON.PostProcess);
  16427. BABYLON.BlurPostProcess = BlurPostProcess;
  16428. })(BABYLON || (BABYLON = {}));
  16429. //# sourceMappingURL=babylon.blurPostProcess.js.map
  16430. var BABYLON;
  16431. (function (BABYLON) {
  16432. var FilterPostProcess = (function (_super) {
  16433. __extends(FilterPostProcess, _super);
  16434. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  16435. var _this = this;
  16436. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  16437. this.kernelMatrix = kernelMatrix;
  16438. this.onApply = function (effect) {
  16439. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  16440. };
  16441. }
  16442. return FilterPostProcess;
  16443. })(BABYLON.PostProcess);
  16444. BABYLON.FilterPostProcess = FilterPostProcess;
  16445. })(BABYLON || (BABYLON = {}));
  16446. //# sourceMappingURL=babylon.filterPostProcess.js.map
  16447. var BABYLON;
  16448. (function (BABYLON) {
  16449. var RefractionPostProcess = (function (_super) {
  16450. __extends(RefractionPostProcess, _super);
  16451. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  16452. var _this = this;
  16453. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  16454. this.color = color;
  16455. this.depth = depth;
  16456. this.colorLevel = colorLevel;
  16457. this.onActivate = function (cam) {
  16458. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  16459. };
  16460. this.onApply = function (effect) {
  16461. effect.setColor3("baseColor", _this.color);
  16462. effect.setFloat("depth", _this.depth);
  16463. effect.setFloat("colorLevel", _this.colorLevel);
  16464. effect.setTexture("refractionSampler", _this._refRexture);
  16465. };
  16466. }
  16467. // Methods
  16468. RefractionPostProcess.prototype.dispose = function (camera) {
  16469. if (this._refRexture) {
  16470. this._refRexture.dispose();
  16471. }
  16472. _super.prototype.dispose.call(this, camera);
  16473. };
  16474. return RefractionPostProcess;
  16475. })(BABYLON.PostProcess);
  16476. BABYLON.RefractionPostProcess = RefractionPostProcess;
  16477. })(BABYLON || (BABYLON = {}));
  16478. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  16479. var BABYLON;
  16480. (function (BABYLON) {
  16481. var BlackAndWhitePostProcess = (function (_super) {
  16482. __extends(BlackAndWhitePostProcess, _super);
  16483. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16484. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  16485. }
  16486. return BlackAndWhitePostProcess;
  16487. })(BABYLON.PostProcess);
  16488. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  16489. })(BABYLON || (BABYLON = {}));
  16490. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  16491. var BABYLON;
  16492. (function (BABYLON) {
  16493. var ConvolutionPostProcess = (function (_super) {
  16494. __extends(ConvolutionPostProcess, _super);
  16495. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  16496. var _this = this;
  16497. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  16498. this.kernel = kernel;
  16499. this.onApply = function (effect) {
  16500. effect.setFloat2("screenSize", _this.width, _this.height);
  16501. effect.setArray("kernel", _this.kernel);
  16502. };
  16503. }
  16504. // Statics
  16505. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  16506. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  16507. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  16508. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  16509. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  16510. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  16511. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  16512. return ConvolutionPostProcess;
  16513. })(BABYLON.PostProcess);
  16514. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  16515. })(BABYLON || (BABYLON = {}));
  16516. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  16517. var BABYLON;
  16518. (function (BABYLON) {
  16519. var FxaaPostProcess = (function (_super) {
  16520. __extends(FxaaPostProcess, _super);
  16521. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16522. var _this = this;
  16523. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  16524. this.onSizeChanged = function () {
  16525. _this.texelWidth = 1.0 / _this.width;
  16526. _this.texelHeight = 1.0 / _this.height;
  16527. };
  16528. this.onApply = function (effect) {
  16529. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  16530. };
  16531. }
  16532. return FxaaPostProcess;
  16533. })(BABYLON.PostProcess);
  16534. BABYLON.FxaaPostProcess = FxaaPostProcess;
  16535. })(BABYLON || (BABYLON = {}));
  16536. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  16537. (function (BABYLON) {
  16538. var LensFlare = (function () {
  16539. function LensFlare(size, position, color, imgUrl, system) {
  16540. this.size = size;
  16541. this.position = position;
  16542. this.dispose = function () {
  16543. if (this.texture) {
  16544. this.texture.dispose();
  16545. }
  16546. // Remove from scene
  16547. var index = this._system.lensFlares.indexOf(this);
  16548. this._system.lensFlares.splice(index, 1);
  16549. };
  16550. this.color = color || new BABYLON.Color3(1, 1, 1);
  16551. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  16552. this._system = system;
  16553. system.lensFlares.push(this);
  16554. }
  16555. return LensFlare;
  16556. })();
  16557. BABYLON.LensFlare = LensFlare;
  16558. })(BABYLON || (BABYLON = {}));
  16559. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  16560. (function (BABYLON) {
  16561. var LensFlareSystem = (function () {
  16562. function LensFlareSystem(name, emitter, scene) {
  16563. this.name = name;
  16564. this.lensFlares = new Array();
  16565. this.borderLimit = 300;
  16566. this._vertexDeclaration = [2];
  16567. this._vertexStrideSize = 2 * 4;
  16568. this._isEnabled = true;
  16569. this._scene = scene;
  16570. this._emitter = emitter;
  16571. scene.lensFlareSystems.push(this);
  16572. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  16573. // VBO
  16574. var vertices = [];
  16575. vertices.push(1, 1);
  16576. vertices.push(-1, 1);
  16577. vertices.push(-1, -1);
  16578. vertices.push(1, -1);
  16579. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16580. // Indices
  16581. var indices = [];
  16582. indices.push(0);
  16583. indices.push(1);
  16584. indices.push(2);
  16585. indices.push(0);
  16586. indices.push(2);
  16587. indices.push(3);
  16588. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16589. // Effects
  16590. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  16591. }
  16592. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  16593. get: function () {
  16594. return this._isEnabled;
  16595. },
  16596. set: function (value) {
  16597. this._isEnabled = value;
  16598. },
  16599. enumerable: true,
  16600. configurable: true
  16601. });
  16602. LensFlareSystem.prototype.getScene = function () {
  16603. return this._scene;
  16604. };
  16605. LensFlareSystem.prototype.getEmitter = function () {
  16606. return this._emitter;
  16607. };
  16608. LensFlareSystem.prototype.getEmitterPosition = function () {
  16609. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  16610. };
  16611. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  16612. var position = this.getEmitterPosition();
  16613. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  16614. this._positionX = position.x;
  16615. this._positionY = position.y;
  16616. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  16617. if (position.z > 0) {
  16618. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  16619. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  16620. return true;
  16621. }
  16622. }
  16623. return false;
  16624. };
  16625. LensFlareSystem.prototype._isVisible = function () {
  16626. if (!this._isEnabled) {
  16627. return false;
  16628. }
  16629. var emitterPosition = this.getEmitterPosition();
  16630. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  16631. var distance = direction.length();
  16632. direction.normalize();
  16633. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  16634. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  16635. return !pickInfo.hit || pickInfo.distance > distance;
  16636. };
  16637. LensFlareSystem.prototype.render = function () {
  16638. if (!this._effect.isReady())
  16639. return false;
  16640. var engine = this._scene.getEngine();
  16641. var viewport = this._scene.activeCamera.viewport;
  16642. var globalViewport = viewport.toGlobal(engine);
  16643. // Position
  16644. if (!this.computeEffectivePosition(globalViewport)) {
  16645. return false;
  16646. }
  16647. // Visibility
  16648. if (!this._isVisible()) {
  16649. return false;
  16650. }
  16651. // Intensity
  16652. var awayX;
  16653. var awayY;
  16654. if (this._positionX < this.borderLimit + globalViewport.x) {
  16655. awayX = this.borderLimit + globalViewport.x - this._positionX;
  16656. }
  16657. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  16658. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  16659. }
  16660. else {
  16661. awayX = 0;
  16662. }
  16663. if (this._positionY < this.borderLimit + globalViewport.y) {
  16664. awayY = this.borderLimit + globalViewport.y - this._positionY;
  16665. }
  16666. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  16667. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  16668. }
  16669. else {
  16670. awayY = 0;
  16671. }
  16672. var away = (awayX > awayY) ? awayX : awayY;
  16673. if (away > this.borderLimit) {
  16674. away = this.borderLimit;
  16675. }
  16676. var intensity = 1.0 - (away / this.borderLimit);
  16677. if (intensity < 0) {
  16678. return false;
  16679. }
  16680. if (intensity > 1.0) {
  16681. intensity = 1.0;
  16682. }
  16683. // Position
  16684. var centerX = globalViewport.x + globalViewport.width / 2;
  16685. var centerY = globalViewport.y + globalViewport.height / 2;
  16686. var distX = centerX - this._positionX;
  16687. var distY = centerY - this._positionY;
  16688. // Effects
  16689. engine.enableEffect(this._effect);
  16690. engine.setState(false);
  16691. engine.setDepthBuffer(false);
  16692. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16693. // VBOs
  16694. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16695. for (var index = 0; index < this.lensFlares.length; index++) {
  16696. var flare = this.lensFlares[index];
  16697. var x = centerX - (distX * flare.position);
  16698. var y = centerY - (distY * flare.position);
  16699. var cw = flare.size;
  16700. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  16701. var cx = 2 * (x / globalViewport.width) - 1.0;
  16702. var cy = 1.0 - 2 * (y / globalViewport.height);
  16703. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  16704. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  16705. // Texture
  16706. this._effect.setTexture("textureSampler", flare.texture);
  16707. // Color
  16708. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  16709. // Draw order
  16710. engine.draw(true, 0, 6);
  16711. }
  16712. engine.setDepthBuffer(true);
  16713. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16714. return true;
  16715. };
  16716. LensFlareSystem.prototype.dispose = function () {
  16717. if (this._vertexBuffer) {
  16718. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16719. this._vertexBuffer = null;
  16720. }
  16721. if (this._indexBuffer) {
  16722. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16723. this._indexBuffer = null;
  16724. }
  16725. while (this.lensFlares.length) {
  16726. this.lensFlares[0].dispose();
  16727. }
  16728. // Remove from scene
  16729. var index = this._scene.lensFlareSystems.indexOf(this);
  16730. this._scene.lensFlareSystems.splice(index, 1);
  16731. };
  16732. return LensFlareSystem;
  16733. })();
  16734. BABYLON.LensFlareSystem = LensFlareSystem;
  16735. })(BABYLON || (BABYLON = {}));
  16736. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  16737. (function (BABYLON) {
  16738. var IntersectionInfo = (function () {
  16739. function IntersectionInfo(bu, bv, distance) {
  16740. this.bu = bu;
  16741. this.bv = bv;
  16742. this.distance = distance;
  16743. this.faceId = 0;
  16744. }
  16745. return IntersectionInfo;
  16746. })();
  16747. BABYLON.IntersectionInfo = IntersectionInfo;
  16748. var PickingInfo = (function () {
  16749. function PickingInfo() {
  16750. this.hit = false;
  16751. this.distance = 0;
  16752. this.pickedPoint = null;
  16753. this.pickedMesh = null;
  16754. this.bu = 0;
  16755. this.bv = 0;
  16756. this.faceId = -1;
  16757. }
  16758. // Methods
  16759. PickingInfo.prototype.getNormal = function () {
  16760. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16761. return null;
  16762. }
  16763. var indices = this.pickedMesh.getIndices();
  16764. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16765. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  16766. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  16767. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  16768. normal0 = normal0.scale(this.bu);
  16769. normal1 = normal1.scale(this.bv);
  16770. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  16771. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  16772. };
  16773. PickingInfo.prototype.getTextureCoordinates = function () {
  16774. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16775. return null;
  16776. }
  16777. var indices = this.pickedMesh.getIndices();
  16778. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16779. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  16780. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  16781. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  16782. uv0 = uv0.scale(this.bu);
  16783. uv1 = uv1.scale(this.bv);
  16784. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  16785. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  16786. };
  16787. return PickingInfo;
  16788. })();
  16789. BABYLON.PickingInfo = PickingInfo;
  16790. })(BABYLON || (BABYLON = {}));
  16791. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  16792. (function (BABYLON) {
  16793. var FilesInput = (function () {
  16794. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  16795. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  16796. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  16797. this.engine = p_engine;
  16798. this.canvas = p_canvas;
  16799. this.currentScene = p_scene;
  16800. this.sceneLoadedCallback = p_sceneLoadedCallback;
  16801. this.progressCallback = p_progressCallback;
  16802. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  16803. this.textureLoadingCallback = p_textureLoadingCallback;
  16804. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  16805. }
  16806. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  16807. var _this = this;
  16808. if (p_elementToMonitor) {
  16809. this.elementToMonitor = p_elementToMonitor;
  16810. this.elementToMonitor.addEventListener("dragenter", function (e) {
  16811. _this.drag(e);
  16812. }, false);
  16813. this.elementToMonitor.addEventListener("dragover", function (e) {
  16814. _this.drag(e);
  16815. }, false);
  16816. this.elementToMonitor.addEventListener("drop", function (e) {
  16817. _this.drop(e);
  16818. }, false);
  16819. }
  16820. };
  16821. FilesInput.prototype.renderFunction = function () {
  16822. if (this.additionnalRenderLoopLogicCallback) {
  16823. this.additionnalRenderLoopLogicCallback();
  16824. }
  16825. if (this.currentScene) {
  16826. if (this.textureLoadingCallback) {
  16827. var remaining = this.currentScene.getWaitingItemsCount();
  16828. if (remaining > 0) {
  16829. this.textureLoadingCallback(remaining);
  16830. }
  16831. }
  16832. this.currentScene.render();
  16833. }
  16834. };
  16835. FilesInput.prototype.drag = function (e) {
  16836. e.stopPropagation();
  16837. e.preventDefault();
  16838. };
  16839. FilesInput.prototype.drop = function (eventDrop) {
  16840. eventDrop.stopPropagation();
  16841. eventDrop.preventDefault();
  16842. this.loadFiles(eventDrop);
  16843. };
  16844. FilesInput.prototype.loadFiles = function (event) {
  16845. var _this = this;
  16846. var that = this;
  16847. if (this.startingProcessingFilesCallback)
  16848. this.startingProcessingFilesCallback();
  16849. var sceneFileToLoad;
  16850. var filesToLoad;
  16851. // Handling data transfer via drag'n'drop
  16852. if (event && event.dataTransfer && event.dataTransfer.files) {
  16853. filesToLoad = event.dataTransfer.files;
  16854. }
  16855. // Handling files from input files
  16856. if (event && event.target && event.target.files) {
  16857. filesToLoad = event.target.files;
  16858. }
  16859. if (filesToLoad && filesToLoad.length > 0) {
  16860. for (var i = 0; i < filesToLoad.length; i++) {
  16861. switch (filesToLoad[i].type) {
  16862. case "image/jpeg":
  16863. case "image/png":
  16864. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  16865. break;
  16866. case "image/targa":
  16867. case "image/vnd.ms-dds":
  16868. case "audio/wav":
  16869. case "audio/x-wav":
  16870. case "audio/mpeg":
  16871. case "audio/mpeg3":
  16872. case "audio/x-mpeg-3":
  16873. case "audio/ogg":
  16874. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  16875. break;
  16876. default:
  16877. 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) {
  16878. sceneFileToLoad = filesToLoad[i];
  16879. }
  16880. break;
  16881. }
  16882. }
  16883. // If a ".babylon" file has been provided
  16884. if (sceneFileToLoad) {
  16885. if (this.currentScene) {
  16886. this.engine.stopRenderLoop();
  16887. this.currentScene.dispose();
  16888. }
  16889. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  16890. that.currentScene = newScene;
  16891. // Wait for textures and shaders to be ready
  16892. that.currentScene.executeWhenReady(function () {
  16893. // Attach camera to canvas inputs
  16894. if (that.currentScene.activeCamera) {
  16895. that.currentScene.activeCamera.attachControl(that.canvas);
  16896. }
  16897. if (that.sceneLoadedCallback) {
  16898. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  16899. }
  16900. that.engine.runRenderLoop(function () {
  16901. that.renderFunction();
  16902. });
  16903. });
  16904. }, function (progress) {
  16905. if (_this.progressCallback) {
  16906. _this.progressCallback(progress);
  16907. }
  16908. });
  16909. }
  16910. else {
  16911. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  16912. }
  16913. }
  16914. };
  16915. FilesInput.FilesTextures = new Array();
  16916. FilesInput.FilesToLoad = new Array();
  16917. return FilesInput;
  16918. })();
  16919. BABYLON.FilesInput = FilesInput;
  16920. })(BABYLON || (BABYLON = {}));
  16921. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  16922. (function (BABYLON) {
  16923. var OimoJSPlugin = (function () {
  16924. function OimoJSPlugin() {
  16925. this._registeredMeshes = [];
  16926. /**
  16927. * Update the body position according to the mesh position
  16928. * @param mesh
  16929. */
  16930. this.updateBodyPosition = function (mesh) {
  16931. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16932. var registeredMesh = this._registeredMeshes[index];
  16933. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16934. var body = registeredMesh.body.body;
  16935. mesh.computeWorldMatrix(true);
  16936. var center = mesh.getBoundingInfo().boundingBox.center;
  16937. body.setPosition(center.x, center.y, center.z);
  16938. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  16939. return;
  16940. }
  16941. // Case where the parent has been updated
  16942. if (registeredMesh.mesh.parent === mesh) {
  16943. mesh.computeWorldMatrix(true);
  16944. registeredMesh.mesh.computeWorldMatrix(true);
  16945. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  16946. var absoluteRotation = mesh.rotation;
  16947. body = registeredMesh.body.body;
  16948. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  16949. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  16950. return;
  16951. }
  16952. }
  16953. };
  16954. }
  16955. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  16956. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  16957. };
  16958. OimoJSPlugin.prototype.initialize = function (iterations) {
  16959. this._world = new OIMO.World();
  16960. this._world.clear();
  16961. };
  16962. OimoJSPlugin.prototype.setGravity = function (gravity) {
  16963. this._world.gravity = gravity;
  16964. };
  16965. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  16966. var body = null;
  16967. this.unregisterMesh(mesh);
  16968. mesh.computeWorldMatrix(true);
  16969. switch (impostor) {
  16970. case BABYLON.PhysicsEngine.SphereImpostor:
  16971. var initialRotation = null;
  16972. if (mesh.rotationQuaternion) {
  16973. initialRotation = mesh.rotationQuaternion.clone();
  16974. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16975. mesh.computeWorldMatrix(true);
  16976. }
  16977. var bbox = mesh.getBoundingInfo().boundingBox;
  16978. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16979. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16980. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16981. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16982. // The delta between the mesh position and the mesh bounding box center
  16983. var deltaPosition = mesh.position.subtract(bbox.center);
  16984. // Transform delta position with the rotation
  16985. if (initialRotation) {
  16986. var m = new BABYLON.Matrix();
  16987. initialRotation.toRotationMatrix(m);
  16988. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16989. }
  16990. body = new OIMO.Body({
  16991. type: 'sphere',
  16992. size: [size],
  16993. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16994. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16995. move: options.mass != 0,
  16996. config: [options.mass, options.friction, options.restitution],
  16997. world: this._world
  16998. });
  16999. // Restore rotation
  17000. if (initialRotation) {
  17001. body.setQuaternion(initialRotation);
  17002. }
  17003. this._registeredMeshes.push({
  17004. mesh: mesh,
  17005. body: body,
  17006. delta: deltaPosition
  17007. });
  17008. break;
  17009. case BABYLON.PhysicsEngine.PlaneImpostor:
  17010. case BABYLON.PhysicsEngine.BoxImpostor:
  17011. initialRotation = null;
  17012. if (mesh.rotationQuaternion) {
  17013. initialRotation = mesh.rotationQuaternion.clone();
  17014. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17015. mesh.computeWorldMatrix(true);
  17016. }
  17017. bbox = mesh.getBoundingInfo().boundingBox;
  17018. var min = bbox.minimumWorld;
  17019. var max = bbox.maximumWorld;
  17020. var box = max.subtract(min);
  17021. var sizeX = this._checkWithEpsilon(box.x);
  17022. var sizeY = this._checkWithEpsilon(box.y);
  17023. var sizeZ = this._checkWithEpsilon(box.z);
  17024. // The delta between the mesh position and the mesh boudning box center
  17025. deltaPosition = mesh.position.subtract(bbox.center);
  17026. // Transform delta position with the rotation
  17027. if (initialRotation) {
  17028. m = new BABYLON.Matrix();
  17029. initialRotation.toRotationMatrix(m);
  17030. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17031. }
  17032. body = new OIMO.Body({
  17033. type: 'box',
  17034. size: [sizeX, sizeY, sizeZ],
  17035. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17036. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17037. move: options.mass != 0,
  17038. config: [options.mass, options.friction, options.restitution],
  17039. world: this._world
  17040. });
  17041. if (initialRotation) {
  17042. body.setQuaternion(initialRotation);
  17043. }
  17044. this._registeredMeshes.push({
  17045. mesh: mesh,
  17046. body: body,
  17047. delta: deltaPosition
  17048. });
  17049. break;
  17050. }
  17051. return body;
  17052. };
  17053. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17054. var types = [], sizes = [], positions = [], rotations = [];
  17055. var initialMesh = parts[0].mesh;
  17056. for (var index = 0; index < parts.length; index++) {
  17057. var part = parts[index];
  17058. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  17059. types.push(bodyParameters.type);
  17060. sizes.push.apply(sizes, bodyParameters.size);
  17061. positions.push.apply(positions, bodyParameters.pos);
  17062. rotations.push.apply(rotations, bodyParameters.rot);
  17063. }
  17064. var body = new OIMO.Body({
  17065. type: types,
  17066. size: sizes,
  17067. pos: positions,
  17068. rot: rotations,
  17069. move: options.mass != 0,
  17070. config: [options.mass, options.friction, options.restitution],
  17071. world: this._world
  17072. });
  17073. this._registeredMeshes.push({
  17074. mesh: initialMesh,
  17075. body: body
  17076. });
  17077. return body;
  17078. };
  17079. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  17080. var bodyParameters = null;
  17081. var mesh = part.mesh;
  17082. // We need the bounding box/sphere info to compute the physics body
  17083. mesh.computeWorldMatrix();
  17084. switch (part.impostor) {
  17085. case BABYLON.PhysicsEngine.SphereImpostor:
  17086. var bbox = mesh.getBoundingInfo().boundingBox;
  17087. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17088. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17089. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17090. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17091. bodyParameters = {
  17092. type: 'sphere',
  17093. /* bug with oimo : sphere needs 3 sizes in this case */
  17094. size: [size, -1, -1],
  17095. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  17096. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17097. };
  17098. break;
  17099. case BABYLON.PhysicsEngine.PlaneImpostor:
  17100. case BABYLON.PhysicsEngine.BoxImpostor:
  17101. bbox = mesh.getBoundingInfo().boundingBox;
  17102. var min = bbox.minimumWorld;
  17103. var max = bbox.maximumWorld;
  17104. var box = max.subtract(min);
  17105. var sizeX = this._checkWithEpsilon(box.x);
  17106. var sizeY = this._checkWithEpsilon(box.y);
  17107. var sizeZ = this._checkWithEpsilon(box.z);
  17108. var relativePosition = mesh.position;
  17109. bodyParameters = {
  17110. type: 'box',
  17111. size: [sizeX, sizeY, sizeZ],
  17112. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  17113. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17114. };
  17115. break;
  17116. }
  17117. return bodyParameters;
  17118. };
  17119. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  17120. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17121. var registeredMesh = this._registeredMeshes[index];
  17122. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17123. if (registeredMesh.body) {
  17124. this._world.removeRigidBody(registeredMesh.body.body);
  17125. this._unbindBody(registeredMesh.body);
  17126. }
  17127. this._registeredMeshes.splice(index, 1);
  17128. return;
  17129. }
  17130. }
  17131. };
  17132. OimoJSPlugin.prototype._unbindBody = function (body) {
  17133. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17134. var registeredMesh = this._registeredMeshes[index];
  17135. if (registeredMesh.body === body) {
  17136. registeredMesh.body = null;
  17137. }
  17138. }
  17139. };
  17140. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17141. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17142. var registeredMesh = this._registeredMeshes[index];
  17143. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17144. // Get object mass to have a behaviour similar to cannon.js
  17145. var mass = registeredMesh.body.body.massInfo.mass;
  17146. // The force is scaled with the mass of object
  17147. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17148. return;
  17149. }
  17150. }
  17151. };
  17152. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17153. var body1 = null, body2 = null;
  17154. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17155. var registeredMesh = this._registeredMeshes[index];
  17156. if (registeredMesh.mesh === mesh1) {
  17157. body1 = registeredMesh.body.body;
  17158. }
  17159. else if (registeredMesh.mesh === mesh2) {
  17160. body2 = registeredMesh.body.body;
  17161. }
  17162. }
  17163. if (!body1 || !body2) {
  17164. return false;
  17165. }
  17166. if (!options) {
  17167. options = {};
  17168. }
  17169. new OIMO.Link({
  17170. type: options.type,
  17171. body1: body1,
  17172. body2: body2,
  17173. min: options.min,
  17174. max: options.max,
  17175. axe1: options.axe1,
  17176. axe2: options.axe2,
  17177. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17178. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17179. collision: options.collision,
  17180. spring: options.spring,
  17181. world: this._world
  17182. });
  17183. return true;
  17184. };
  17185. OimoJSPlugin.prototype.dispose = function () {
  17186. this._world.clear();
  17187. while (this._registeredMeshes.length) {
  17188. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17189. }
  17190. };
  17191. OimoJSPlugin.prototype.isSupported = function () {
  17192. return OIMO !== undefined;
  17193. };
  17194. OimoJSPlugin.prototype._getLastShape = function (body) {
  17195. var lastShape = body.shapes;
  17196. while (lastShape.next) {
  17197. lastShape = lastShape.next;
  17198. }
  17199. return lastShape;
  17200. };
  17201. OimoJSPlugin.prototype.runOneStep = function (time) {
  17202. this._world.step();
  17203. // Update the position of all registered meshes
  17204. var i = this._registeredMeshes.length;
  17205. var m;
  17206. while (i--) {
  17207. var body = this._registeredMeshes[i].body.body;
  17208. var mesh = this._registeredMeshes[i].mesh;
  17209. var delta = this._registeredMeshes[i].delta;
  17210. if (!body.sleeping) {
  17211. if (body.shapes.next) {
  17212. var parentShape = this._getLastShape(body);
  17213. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17214. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17215. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17216. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17217. if (!mesh.rotationQuaternion) {
  17218. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17219. }
  17220. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17221. mesh.computeWorldMatrix();
  17222. }
  17223. else {
  17224. m = body.getMatrix();
  17225. mtx = BABYLON.Matrix.FromArray(m);
  17226. // Body position
  17227. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17228. if (!delta) {
  17229. mesh.position.x = bodyX;
  17230. mesh.position.y = bodyY;
  17231. mesh.position.z = bodyZ;
  17232. }
  17233. else {
  17234. mesh.position.x = bodyX + delta.x;
  17235. mesh.position.y = bodyY + delta.y;
  17236. mesh.position.z = bodyZ + delta.z;
  17237. }
  17238. if (!mesh.rotationQuaternion) {
  17239. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17240. }
  17241. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17242. mesh.computeWorldMatrix();
  17243. }
  17244. }
  17245. }
  17246. };
  17247. return OimoJSPlugin;
  17248. })();
  17249. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17250. })(BABYLON || (BABYLON = {}));
  17251. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17252. (function (BABYLON) {
  17253. var PhysicsEngine = (function () {
  17254. function PhysicsEngine(plugin) {
  17255. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17256. }
  17257. PhysicsEngine.prototype._initialize = function (gravity) {
  17258. this._currentPlugin.initialize();
  17259. this._setGravity(gravity);
  17260. };
  17261. PhysicsEngine.prototype._runOneStep = function (delta) {
  17262. if (delta > 0.1) {
  17263. delta = 0.1;
  17264. }
  17265. else if (delta <= 0) {
  17266. delta = 1.0 / 60.0;
  17267. }
  17268. this._currentPlugin.runOneStep(delta);
  17269. };
  17270. PhysicsEngine.prototype._setGravity = function (gravity) {
  17271. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17272. this._currentPlugin.setGravity(this.gravity);
  17273. };
  17274. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17275. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17276. };
  17277. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17278. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17279. };
  17280. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17281. this._currentPlugin.unregisterMesh(mesh);
  17282. };
  17283. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  17284. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  17285. };
  17286. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17287. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  17288. };
  17289. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  17290. this._currentPlugin.updateBodyPosition(mesh);
  17291. };
  17292. PhysicsEngine.prototype.dispose = function () {
  17293. this._currentPlugin.dispose();
  17294. };
  17295. PhysicsEngine.prototype.isSupported = function () {
  17296. return this._currentPlugin.isSupported();
  17297. };
  17298. // Statics
  17299. PhysicsEngine.NoImpostor = 0;
  17300. PhysicsEngine.SphereImpostor = 1;
  17301. PhysicsEngine.BoxImpostor = 2;
  17302. PhysicsEngine.PlaneImpostor = 3;
  17303. PhysicsEngine.MeshImpostor = 4;
  17304. PhysicsEngine.CapsuleImpostor = 5;
  17305. PhysicsEngine.ConeImpostor = 6;
  17306. PhysicsEngine.CylinderImpostor = 7;
  17307. PhysicsEngine.ConvexHullImpostor = 8;
  17308. PhysicsEngine.Epsilon = 0.001;
  17309. return PhysicsEngine;
  17310. })();
  17311. BABYLON.PhysicsEngine = PhysicsEngine;
  17312. })(BABYLON || (BABYLON = {}));
  17313. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  17314. (function (BABYLON) {
  17315. var serializeLight = function (light) {
  17316. var serializationObject = {};
  17317. serializationObject.name = light.name;
  17318. serializationObject.id = light.id;
  17319. serializationObject.tags = BABYLON.Tags.GetTags(light);
  17320. if (light instanceof BABYLON.PointLight) {
  17321. serializationObject.type = 0;
  17322. serializationObject.position = light.position.asArray();
  17323. }
  17324. else if (light instanceof BABYLON.DirectionalLight) {
  17325. serializationObject.type = 1;
  17326. var directionalLight = light;
  17327. serializationObject.position = directionalLight.position.asArray();
  17328. serializationObject.direction = directionalLight.direction.asArray();
  17329. }
  17330. else if (light instanceof BABYLON.SpotLight) {
  17331. serializationObject.type = 2;
  17332. var spotLight = light;
  17333. serializationObject.position = spotLight.position.asArray();
  17334. serializationObject.direction = spotLight.position.asArray();
  17335. serializationObject.angle = spotLight.angle;
  17336. serializationObject.exponent = spotLight.exponent;
  17337. }
  17338. else if (light instanceof BABYLON.HemisphericLight) {
  17339. serializationObject.type = 3;
  17340. var hemisphericLight = light;
  17341. serializationObject.direction = hemisphericLight.direction.asArray();
  17342. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  17343. }
  17344. if (light.intensity) {
  17345. serializationObject.intensity = light.intensity;
  17346. }
  17347. serializationObject.range = light.range;
  17348. serializationObject.diffuse = light.diffuse.asArray();
  17349. serializationObject.specular = light.specular.asArray();
  17350. return serializationObject;
  17351. };
  17352. var serializeFresnelParameter = function (fresnelParameter) {
  17353. var serializationObject = {};
  17354. serializationObject.isEnabled = fresnelParameter.isEnabled;
  17355. serializationObject.leftColor = fresnelParameter.leftColor;
  17356. serializationObject.rightColor = fresnelParameter.rightColor;
  17357. serializationObject.bias = fresnelParameter.bias;
  17358. serializationObject.power = fresnelParameter.power;
  17359. return serializationObject;
  17360. };
  17361. var serializeCamera = function (camera) {
  17362. var serializationObject = {};
  17363. serializationObject.name = camera.name;
  17364. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  17365. serializationObject.id = camera.id;
  17366. serializationObject.position = camera.position.asArray();
  17367. // Parent
  17368. if (camera.parent) {
  17369. serializationObject.parentId = camera.parent.id;
  17370. }
  17371. // Target
  17372. serializationObject.rotation = camera.rotation.asArray();
  17373. // Locked target
  17374. if (camera.lockedTarget && camera.lockedTarget.id) {
  17375. serializationObject.lockedTargetId = camera.lockedTarget.id;
  17376. }
  17377. serializationObject.fov = camera.fov;
  17378. serializationObject.minZ = camera.minZ;
  17379. serializationObject.maxZ = camera.maxZ;
  17380. serializationObject.speed = camera.speed;
  17381. serializationObject.inertia = camera.inertia;
  17382. serializationObject.checkCollisions = camera.checkCollisions;
  17383. serializationObject.applyGravity = camera.applyGravity;
  17384. if (camera.ellipsoid) {
  17385. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  17386. }
  17387. // Animations
  17388. appendAnimations(camera, serializationObject);
  17389. // Layer mask
  17390. serializationObject.layerMask = camera.layerMask;
  17391. return serializationObject;
  17392. };
  17393. var appendAnimations = function (source, destination) {
  17394. if (source.animations) {
  17395. destination.animations = [];
  17396. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  17397. var animation = source.animations[animationIndex];
  17398. destination.animations.push(serializeAnimation(animation));
  17399. }
  17400. }
  17401. };
  17402. var serializeAnimation = function (animation) {
  17403. var serializationObject = {};
  17404. serializationObject.name = animation.name;
  17405. serializationObject.property = animation.targetProperty;
  17406. serializationObject.framePerSecond = animation.framePerSecond;
  17407. serializationObject.dataType = animation.dataType;
  17408. serializationObject.loopBehavior = animation.loopMode;
  17409. var dataType = animation.dataType;
  17410. serializationObject.keys = [];
  17411. var keys = animation.getKeys();
  17412. for (var index = 0; index < keys.length; index++) {
  17413. var animationKey = keys[index];
  17414. var key = {};
  17415. key.frame = animationKey.frame;
  17416. switch (dataType) {
  17417. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17418. key.values = [animationKey.value];
  17419. break;
  17420. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17421. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17422. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17423. key.values = animationKey.value.asArray();
  17424. break;
  17425. }
  17426. serializationObject.keys.push(key);
  17427. }
  17428. return serializationObject;
  17429. };
  17430. var serializeMultiMaterial = function (material) {
  17431. var serializationObject = {};
  17432. serializationObject.name = material.name;
  17433. serializationObject.id = material.id;
  17434. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17435. serializationObject.materials = [];
  17436. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  17437. var subMat = material.subMaterials[matIndex];
  17438. if (subMat) {
  17439. serializationObject.materials.push(subMat.id);
  17440. }
  17441. else {
  17442. serializationObject.materials.push(null);
  17443. }
  17444. }
  17445. return serializationObject;
  17446. };
  17447. var serializeMaterial = function (material) {
  17448. var serializationObject = {};
  17449. serializationObject.name = material.name;
  17450. serializationObject.ambient = material.ambientColor.asArray();
  17451. serializationObject.diffuse = material.diffuseColor.asArray();
  17452. serializationObject.specular = material.specularColor.asArray();
  17453. serializationObject.specularPower = material.specularPower;
  17454. serializationObject.emissive = material.emissiveColor.asArray();
  17455. serializationObject.alpha = material.alpha;
  17456. serializationObject.id = material.id;
  17457. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17458. serializationObject.backFaceCulling = material.backFaceCulling;
  17459. if (material.diffuseTexture) {
  17460. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  17461. }
  17462. if (material.diffuseFresnelParameters) {
  17463. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  17464. }
  17465. if (material.ambientTexture) {
  17466. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  17467. }
  17468. if (material.opacityTexture) {
  17469. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  17470. }
  17471. if (material.opacityFresnelParameters) {
  17472. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  17473. }
  17474. if (material.reflectionTexture) {
  17475. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  17476. }
  17477. if (material.reflectionFresnelParameters) {
  17478. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  17479. }
  17480. if (material.emissiveTexture) {
  17481. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  17482. }
  17483. if (material.emissiveFresnelParameters) {
  17484. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  17485. }
  17486. if (material.specularTexture) {
  17487. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  17488. }
  17489. if (material.bumpTexture) {
  17490. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  17491. }
  17492. return serializationObject;
  17493. };
  17494. var serializeTexture = function (texture) {
  17495. var serializationObject = {};
  17496. if (!texture.name) {
  17497. return null;
  17498. }
  17499. if (texture instanceof BABYLON.CubeTexture) {
  17500. serializationObject.name = texture.name;
  17501. serializationObject.hasAlpha = texture.hasAlpha;
  17502. serializationObject.level = texture.level;
  17503. serializationObject.coordinatesMode = texture.coordinatesMode;
  17504. return serializationObject;
  17505. }
  17506. if (texture instanceof BABYLON.MirrorTexture) {
  17507. var mirrorTexture = texture;
  17508. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  17509. serializationObject.renderList = [];
  17510. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  17511. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  17512. }
  17513. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  17514. }
  17515. else if (texture instanceof BABYLON.RenderTargetTexture) {
  17516. var renderTargetTexture = texture;
  17517. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  17518. serializationObject.renderList = [];
  17519. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  17520. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  17521. }
  17522. }
  17523. var regularTexture = texture;
  17524. serializationObject.name = texture.name;
  17525. serializationObject.hasAlpha = texture.hasAlpha;
  17526. serializationObject.level = texture.level;
  17527. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  17528. serializationObject.coordinatesMode = texture.coordinatesMode;
  17529. serializationObject.uOffset = regularTexture.uOffset;
  17530. serializationObject.vOffset = regularTexture.vOffset;
  17531. serializationObject.uScale = regularTexture.uScale;
  17532. serializationObject.vScale = regularTexture.vScale;
  17533. serializationObject.uAng = regularTexture.uAng;
  17534. serializationObject.vAng = regularTexture.vAng;
  17535. serializationObject.wAng = regularTexture.wAng;
  17536. serializationObject.wrapU = texture.wrapU;
  17537. serializationObject.wrapV = texture.wrapV;
  17538. // Animations
  17539. appendAnimations(texture, serializationObject);
  17540. return serializationObject;
  17541. };
  17542. var serializeSkeleton = function (skeleton) {
  17543. var serializationObject = {};
  17544. serializationObject.name = skeleton.name;
  17545. serializationObject.id = skeleton.id;
  17546. serializationObject.bones = [];
  17547. for (var index = 0; index < skeleton.bones.length; index++) {
  17548. var bone = skeleton.bones[index];
  17549. var serializedBone = {
  17550. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  17551. name: bone.name,
  17552. matrix: bone.getLocalMatrix().toArray()
  17553. };
  17554. serializationObject.bones.push(serializedBone);
  17555. if (bone.animations && bone.animations.length > 0) {
  17556. serializedBone.animation = serializeAnimation(bone.animations[0]);
  17557. }
  17558. }
  17559. return serializationObject;
  17560. };
  17561. var serializeParticleSystem = function (particleSystem) {
  17562. var serializationObject = {};
  17563. serializationObject.emitterId = particleSystem.emitter.id;
  17564. serializationObject.capacity = particleSystem.getCapacity();
  17565. if (particleSystem.particleTexture) {
  17566. serializationObject.textureName = particleSystem.particleTexture.name;
  17567. }
  17568. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  17569. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  17570. serializationObject.minSize = particleSystem.minSize;
  17571. serializationObject.maxSize = particleSystem.maxSize;
  17572. serializationObject.minLifeTime = particleSystem.minLifeTime;
  17573. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  17574. serializationObject.emitRate = particleSystem.emitRate;
  17575. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  17576. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  17577. serializationObject.gravity = particleSystem.gravity.asArray();
  17578. serializationObject.direction1 = particleSystem.direction1.asArray();
  17579. serializationObject.direction2 = particleSystem.direction2.asArray();
  17580. serializationObject.color1 = particleSystem.color1.asArray();
  17581. serializationObject.color2 = particleSystem.color2.asArray();
  17582. serializationObject.colorDead = particleSystem.colorDead.asArray();
  17583. serializationObject.updateSpeed = particleSystem.updateSpeed;
  17584. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  17585. serializationObject.textureMask = particleSystem.textureMask.asArray();
  17586. serializationObject.blendMode = particleSystem.blendMode;
  17587. return serializationObject;
  17588. };
  17589. var serializeLensFlareSystem = function (lensFlareSystem) {
  17590. var serializationObject = {};
  17591. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  17592. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  17593. serializationObject.flares = [];
  17594. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  17595. var flare = lensFlareSystem.lensFlares[index];
  17596. serializationObject.flares.push({
  17597. size: flare.size,
  17598. position: flare.position,
  17599. color: flare.color.asArray(),
  17600. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  17601. });
  17602. }
  17603. return serializationObject;
  17604. };
  17605. var serializeShadowGenerator = function (light) {
  17606. var serializationObject = {};
  17607. var shadowGenerator = light.getShadowGenerator();
  17608. serializationObject.lightId = light.id;
  17609. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  17610. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  17611. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  17612. serializationObject.renderList = [];
  17613. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  17614. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  17615. serializationObject.renderList.push(mesh.id);
  17616. }
  17617. return serializationObject;
  17618. };
  17619. var serializedGeometries = [];
  17620. var serializeGeometry = function (geometry, serializationGeometries) {
  17621. if (serializedGeometries[geometry.id]) {
  17622. return;
  17623. }
  17624. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  17625. serializationGeometries.boxes.push(serializeBox(geometry));
  17626. }
  17627. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  17628. serializationGeometries.spheres.push(serializeSphere(geometry));
  17629. }
  17630. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  17631. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  17632. }
  17633. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  17634. serializationGeometries.toruses.push(serializeTorus(geometry));
  17635. }
  17636. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  17637. serializationGeometries.grounds.push(serializeGround(geometry));
  17638. }
  17639. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  17640. serializationGeometries.planes.push(serializePlane(geometry));
  17641. }
  17642. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  17643. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  17644. }
  17645. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  17646. throw new Error("Unknow primitive type");
  17647. }
  17648. else {
  17649. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  17650. }
  17651. serializedGeometries[geometry.id] = true;
  17652. };
  17653. var serializeGeometryBase = function (geometry) {
  17654. var serializationObject = {};
  17655. serializationObject.id = geometry.id;
  17656. if (BABYLON.Tags.HasTags(geometry)) {
  17657. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  17658. }
  17659. return serializationObject;
  17660. };
  17661. var serializeVertexData = function (vertexData) {
  17662. var serializationObject = serializeGeometryBase(vertexData);
  17663. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17664. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17665. }
  17666. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17667. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17668. }
  17669. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17670. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17671. }
  17672. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17673. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17674. }
  17675. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17676. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17677. }
  17678. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17679. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17680. serializationObject.matricesIndices._isExpanded = true;
  17681. }
  17682. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17683. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17684. }
  17685. serializationObject.indices = vertexData.getIndices();
  17686. return serializationObject;
  17687. };
  17688. var serializePrimitive = function (primitive) {
  17689. var serializationObject = serializeGeometryBase(primitive);
  17690. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  17691. return serializationObject;
  17692. };
  17693. var serializeBox = function (box) {
  17694. var serializationObject = serializePrimitive(box);
  17695. serializationObject.size = box.size;
  17696. return serializationObject;
  17697. };
  17698. var serializeSphere = function (sphere) {
  17699. var serializationObject = serializePrimitive(sphere);
  17700. serializationObject.segments = sphere.segments;
  17701. serializationObject.diameter = sphere.diameter;
  17702. return serializationObject;
  17703. };
  17704. var serializeCylinder = function (cylinder) {
  17705. var serializationObject = serializePrimitive(cylinder);
  17706. serializationObject.height = cylinder.height;
  17707. serializationObject.diameterTop = cylinder.diameterTop;
  17708. serializationObject.diameterBottom = cylinder.diameterBottom;
  17709. serializationObject.tessellation = cylinder.tessellation;
  17710. return serializationObject;
  17711. };
  17712. var serializeTorus = function (torus) {
  17713. var serializationObject = serializePrimitive(torus);
  17714. serializationObject.diameter = torus.diameter;
  17715. serializationObject.thickness = torus.thickness;
  17716. serializationObject.tessellation = torus.tessellation;
  17717. return serializationObject;
  17718. };
  17719. var serializeGround = function (ground) {
  17720. var serializationObject = serializePrimitive(ground);
  17721. serializationObject.width = ground.width;
  17722. serializationObject.height = ground.height;
  17723. serializationObject.subdivisions = ground.subdivisions;
  17724. return serializationObject;
  17725. };
  17726. var serializePlane = function (plane) {
  17727. var serializationObject = serializePrimitive(plane);
  17728. serializationObject.size = plane.size;
  17729. return serializationObject;
  17730. };
  17731. var serializeTorusKnot = function (torusKnot) {
  17732. var serializationObject = serializePrimitive(torusKnot);
  17733. serializationObject.radius = torusKnot.radius;
  17734. serializationObject.tube = torusKnot.tube;
  17735. serializationObject.radialSegments = torusKnot.radialSegments;
  17736. serializationObject.tubularSegments = torusKnot.tubularSegments;
  17737. serializationObject.p = torusKnot.p;
  17738. serializationObject.q = torusKnot.q;
  17739. return serializationObject;
  17740. };
  17741. var serializeMesh = function (mesh, serializationScene) {
  17742. var serializationObject = {};
  17743. serializationObject.name = mesh.name;
  17744. serializationObject.id = mesh.id;
  17745. if (BABYLON.Tags.HasTags(mesh)) {
  17746. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  17747. }
  17748. serializationObject.position = mesh.position.asArray();
  17749. if (mesh.rotationQuaternion) {
  17750. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  17751. }
  17752. else if (mesh.rotation) {
  17753. serializationObject.rotation = mesh.rotation.asArray();
  17754. }
  17755. serializationObject.scaling = mesh.scaling.asArray();
  17756. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  17757. serializationObject.isEnabled = mesh.isEnabled();
  17758. serializationObject.isVisible = mesh.isVisible;
  17759. serializationObject.infiniteDistance = mesh.infiniteDistance;
  17760. serializationObject.pickable = mesh.isPickable;
  17761. serializationObject.receiveShadows = mesh.receiveShadows;
  17762. serializationObject.billboardMode = mesh.billboardMode;
  17763. serializationObject.visibility = mesh.visibility;
  17764. serializationObject.checkCollisions = mesh.checkCollisions;
  17765. // Parent
  17766. if (mesh.parent) {
  17767. serializationObject.parentId = mesh.parent.id;
  17768. }
  17769. // Geometry
  17770. var geometry = mesh._geometry;
  17771. if (geometry) {
  17772. var geometryId = geometry.id;
  17773. serializationObject.geometryId = geometryId;
  17774. if (!mesh.getScene().getGeometryByID(geometryId)) {
  17775. // geometry was in the memory but not added to the scene, nevertheless it's better to serialize too be able to reload the mesh with its geometry
  17776. serializeGeometry(geometry, serializationScene.geometries);
  17777. }
  17778. // SubMeshes
  17779. serializationObject.subMeshes = [];
  17780. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17781. var subMesh = mesh.subMeshes[subIndex];
  17782. serializationObject.subMeshes.push({
  17783. materialIndex: subMesh.materialIndex,
  17784. verticesStart: subMesh.verticesStart,
  17785. verticesCount: subMesh.verticesCount,
  17786. indexStart: subMesh.indexStart,
  17787. indexCount: subMesh.indexCount
  17788. });
  17789. }
  17790. }
  17791. // Material
  17792. if (mesh.material) {
  17793. serializationObject.materialId = mesh.material.id;
  17794. }
  17795. else {
  17796. mesh.material = null;
  17797. }
  17798. // Skeleton
  17799. if (mesh.skeleton) {
  17800. serializationObject.skeletonId = mesh.skeleton.id;
  17801. }
  17802. // Physics
  17803. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  17804. serializationObject.physicsMass = mesh.getPhysicsMass();
  17805. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  17806. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  17807. switch (mesh.getPhysicsImpostor()) {
  17808. case BABYLON.PhysicsEngine.BoxImpostor:
  17809. serializationObject.physicsImpostor = 1;
  17810. break;
  17811. case BABYLON.PhysicsEngine.SphereImpostor:
  17812. serializationObject.physicsImpostor = 2;
  17813. break;
  17814. }
  17815. }
  17816. // Instances
  17817. serializationObject.instances = [];
  17818. for (var index = 0; index < mesh.instances.length; index++) {
  17819. var instance = mesh.instances[index];
  17820. var serializationInstance = {
  17821. name: instance.name,
  17822. position: instance.position,
  17823. rotation: instance.rotation,
  17824. rotationQuaternion: instance.rotationQuaternion,
  17825. scaling: instance.scaling
  17826. };
  17827. serializationObject.instances.push(serializationInstance);
  17828. // Animations
  17829. appendAnimations(instance, serializationInstance);
  17830. }
  17831. // Animations
  17832. appendAnimations(mesh, serializationObject);
  17833. // Layer mask
  17834. serializationObject.layerMask = mesh.layerMask;
  17835. return serializationObject;
  17836. };
  17837. var SceneSerializer = (function () {
  17838. function SceneSerializer() {
  17839. }
  17840. SceneSerializer.Serialize = function (scene) {
  17841. var serializationObject = {};
  17842. // Scene
  17843. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  17844. serializationObject.autoClear = scene.autoClear;
  17845. serializationObject.clearColor = scene.clearColor.asArray();
  17846. serializationObject.ambientColor = scene.ambientColor.asArray();
  17847. serializationObject.gravity = scene.gravity.asArray();
  17848. // Fog
  17849. if (scene.fogMode && scene.fogMode !== 0) {
  17850. serializationObject.fogMode = scene.fogMode;
  17851. serializationObject.fogColor = scene.fogColor.asArray();
  17852. serializationObject.fogStart = scene.fogStart;
  17853. serializationObject.fogEnd = scene.fogEnd;
  17854. serializationObject.fogDensity = scene.fogDensity;
  17855. }
  17856. // Lights
  17857. serializationObject.lights = [];
  17858. for (var index = 0; index < scene.lights.length; index++) {
  17859. var light = scene.lights[index];
  17860. serializationObject.lights.push(serializeLight(light));
  17861. }
  17862. // Cameras
  17863. serializationObject.cameras = [];
  17864. for (index = 0; index < scene.cameras.length; index++) {
  17865. var camera = scene.cameras[index];
  17866. if (camera instanceof BABYLON.FreeCamera) {
  17867. serializationObject.cameras.push(serializeCamera(camera));
  17868. }
  17869. }
  17870. if (scene.activeCamera) {
  17871. serializationObject.activeCameraID = scene.activeCamera.id;
  17872. }
  17873. // Materials
  17874. serializationObject.materials = [];
  17875. serializationObject.multiMaterials = [];
  17876. for (index = 0; index < scene.materials.length; index++) {
  17877. var material = scene.materials[index];
  17878. if (material instanceof BABYLON.StandardMaterial) {
  17879. serializationObject.materials.push(serializeMaterial(material));
  17880. }
  17881. else if (material instanceof BABYLON.MultiMaterial) {
  17882. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  17883. }
  17884. }
  17885. // Skeletons
  17886. serializationObject.skeletons = [];
  17887. for (index = 0; index < scene.skeletons.length; index++) {
  17888. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  17889. }
  17890. // Geometries
  17891. serializationObject.geometries = {};
  17892. serializationObject.geometries.boxes = [];
  17893. serializationObject.geometries.spheres = [];
  17894. serializationObject.geometries.cylinders = [];
  17895. serializationObject.geometries.toruses = [];
  17896. serializationObject.geometries.grounds = [];
  17897. serializationObject.geometries.planes = [];
  17898. serializationObject.geometries.torusKnots = [];
  17899. serializationObject.geometries.vertexData = [];
  17900. serializedGeometries = [];
  17901. var geometries = scene.getGeometries();
  17902. for (var index = 0; index < geometries.length; index++) {
  17903. var geometry = geometries[index];
  17904. if (geometry.isReady()) {
  17905. serializeGeometry(geometry, serializationObject.geometries);
  17906. }
  17907. }
  17908. // Meshes
  17909. serializationObject.meshes = [];
  17910. for (index = 0; index < scene.meshes.length; index++) {
  17911. var abstractMesh = scene.meshes[index];
  17912. if (abstractMesh instanceof BABYLON.Mesh) {
  17913. var mesh = abstractMesh;
  17914. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  17915. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  17916. }
  17917. }
  17918. }
  17919. // Particles Systems
  17920. serializationObject.particleSystems = [];
  17921. for (index = 0; index < scene.particleSystems.length; index++) {
  17922. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  17923. }
  17924. // Lens flares
  17925. serializationObject.lensFlareSystems = [];
  17926. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  17927. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  17928. }
  17929. // Shadows
  17930. serializationObject.shadowGenerators = [];
  17931. for (index = 0; index < scene.lights.length; index++) {
  17932. light = scene.lights[index];
  17933. if (light.getShadowGenerator()) {
  17934. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  17935. }
  17936. }
  17937. return serializationObject;
  17938. };
  17939. return SceneSerializer;
  17940. })();
  17941. BABYLON.SceneSerializer = SceneSerializer;
  17942. })(BABYLON || (BABYLON = {}));
  17943. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  17944. (function (BABYLON) {
  17945. var SceneLoader = (function () {
  17946. function SceneLoader() {
  17947. }
  17948. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  17949. get: function () {
  17950. return SceneLoader._ForceFullSceneLoadingForIncremental;
  17951. },
  17952. set: function (value) {
  17953. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  17954. },
  17955. enumerable: true,
  17956. configurable: true
  17957. });
  17958. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  17959. get: function () {
  17960. return SceneLoader._ShowLoadingScreen;
  17961. },
  17962. set: function (value) {
  17963. SceneLoader._ShowLoadingScreen = value;
  17964. },
  17965. enumerable: true,
  17966. configurable: true
  17967. });
  17968. SceneLoader._getPluginForFilename = function (sceneFilename) {
  17969. var dotPosition = sceneFilename.lastIndexOf(".");
  17970. var queryStringPosition = sceneFilename.indexOf("?");
  17971. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17972. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17973. var plugin = this._registeredPlugins[index];
  17974. if (plugin.extensions.indexOf(extension) !== -1) {
  17975. return plugin;
  17976. }
  17977. }
  17978. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17979. };
  17980. // Public functions
  17981. SceneLoader.RegisterPlugin = function (plugin) {
  17982. plugin.extensions = plugin.extensions.toLowerCase();
  17983. SceneLoader._registeredPlugins.push(plugin);
  17984. };
  17985. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17986. var manifestChecked = function (success) {
  17987. scene.database = database;
  17988. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17989. var importMeshFromData = function (data) {
  17990. var meshes = [];
  17991. var particleSystems = [];
  17992. var skeletons = [];
  17993. try {
  17994. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17995. if (onerror) {
  17996. onerror(scene, 'unable to load the scene');
  17997. }
  17998. return;
  17999. }
  18000. }
  18001. catch (e) {
  18002. if (onerror) {
  18003. onerror(scene, e);
  18004. }
  18005. return;
  18006. }
  18007. if (onsuccess) {
  18008. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18009. onsuccess(meshes, particleSystems, skeletons);
  18010. }
  18011. };
  18012. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18013. // Direct load
  18014. importMeshFromData(sceneFilename.substr(5));
  18015. return;
  18016. }
  18017. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18018. importMeshFromData(data);
  18019. }, progressCallBack, database);
  18020. };
  18021. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18022. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18023. };
  18024. /**
  18025. * Load a scene
  18026. * @param rootUrl a string that defines the root url for scene and resources
  18027. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18028. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18029. */
  18030. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18031. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18032. };
  18033. /**
  18034. * Append a scene
  18035. * @param rootUrl a string that defines the root url for scene and resources
  18036. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18037. * @param scene is the instance of BABYLON.Scene to append to
  18038. */
  18039. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18040. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18041. var database;
  18042. if (SceneLoader.ShowLoadingScreen) {
  18043. scene.getEngine().displayLoadingUI();
  18044. }
  18045. var loadSceneFromData = function (data) {
  18046. scene.database = database;
  18047. if (!plugin.load(scene, data, rootUrl)) {
  18048. if (onerror) {
  18049. onerror(scene);
  18050. }
  18051. scene.getEngine().hideLoadingUI();
  18052. return;
  18053. }
  18054. if (onsuccess) {
  18055. onsuccess(scene);
  18056. }
  18057. if (SceneLoader.ShowLoadingScreen) {
  18058. scene.executeWhenReady(function () {
  18059. scene.getEngine().hideLoadingUI();
  18060. });
  18061. }
  18062. };
  18063. var manifestChecked = function (success) {
  18064. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18065. };
  18066. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18067. // Direct load
  18068. loadSceneFromData(sceneFilename.substr(5));
  18069. return;
  18070. }
  18071. if (rootUrl.indexOf("file:") === -1) {
  18072. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18073. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18074. }
  18075. else {
  18076. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18077. }
  18078. };
  18079. // Flags
  18080. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18081. SceneLoader._ShowLoadingScreen = true;
  18082. // Members
  18083. SceneLoader._registeredPlugins = new Array();
  18084. return SceneLoader;
  18085. })();
  18086. BABYLON.SceneLoader = SceneLoader;
  18087. ;
  18088. })(BABYLON || (BABYLON = {}));
  18089. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  18090. (function (BABYLON) {
  18091. var Internals;
  18092. (function (Internals) {
  18093. var checkColors4 = function (colors, count) {
  18094. // Check if color3 was used
  18095. if (colors.length === count * 3) {
  18096. var colors4 = [];
  18097. for (var index = 0; index < colors.length; index += 3) {
  18098. var newIndex = (index / 3) * 4;
  18099. colors4[newIndex] = colors[index];
  18100. colors4[newIndex + 1] = colors[index + 1];
  18101. colors4[newIndex + 2] = colors[index + 2];
  18102. colors4[newIndex + 3] = 1.0;
  18103. }
  18104. return colors4;
  18105. }
  18106. return colors;
  18107. };
  18108. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18109. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18110. texture.name = parsedTexture.name;
  18111. texture.hasAlpha = parsedTexture.hasAlpha;
  18112. texture.level = parsedTexture.level;
  18113. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18114. return texture;
  18115. };
  18116. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18117. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18118. return null;
  18119. }
  18120. if (parsedTexture.isCube) {
  18121. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18122. }
  18123. var texture;
  18124. if (parsedTexture.mirrorPlane) {
  18125. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18126. texture._waitingRenderList = parsedTexture.renderList;
  18127. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18128. }
  18129. else if (parsedTexture.isRenderTarget) {
  18130. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18131. texture._waitingRenderList = parsedTexture.renderList;
  18132. }
  18133. else {
  18134. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18135. }
  18136. texture.name = parsedTexture.name;
  18137. texture.hasAlpha = parsedTexture.hasAlpha;
  18138. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18139. texture.level = parsedTexture.level;
  18140. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18141. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18142. texture.uOffset = parsedTexture.uOffset;
  18143. texture.vOffset = parsedTexture.vOffset;
  18144. texture.uScale = parsedTexture.uScale;
  18145. texture.vScale = parsedTexture.vScale;
  18146. texture.uAng = parsedTexture.uAng;
  18147. texture.vAng = parsedTexture.vAng;
  18148. texture.wAng = parsedTexture.wAng;
  18149. texture.wrapU = parsedTexture.wrapU;
  18150. texture.wrapV = parsedTexture.wrapV;
  18151. // Animations
  18152. if (parsedTexture.animations) {
  18153. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18154. var parsedAnimation = parsedTexture.animations[animationIndex];
  18155. texture.animations.push(parseAnimation(parsedAnimation));
  18156. }
  18157. }
  18158. return texture;
  18159. };
  18160. var parseSkeleton = function (parsedSkeleton, scene) {
  18161. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18162. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18163. var parsedBone = parsedSkeleton.bones[index];
  18164. var parentBone = null;
  18165. if (parsedBone.parentBoneIndex > -1) {
  18166. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18167. }
  18168. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18169. if (parsedBone.animation) {
  18170. bone.animations.push(parseAnimation(parsedBone.animation));
  18171. }
  18172. }
  18173. return skeleton;
  18174. };
  18175. var parseFresnelParameters = function (parsedFresnelParameters) {
  18176. var fresnelParameters = new BABYLON.FresnelParameters();
  18177. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18178. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18179. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18180. fresnelParameters.bias = parsedFresnelParameters.bias;
  18181. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18182. return fresnelParameters;
  18183. };
  18184. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18185. var material;
  18186. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18187. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18188. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18189. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18190. material.specularPower = parsedMaterial.specularPower;
  18191. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18192. material.alpha = parsedMaterial.alpha;
  18193. material.id = parsedMaterial.id;
  18194. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18195. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18196. material.wireframe = parsedMaterial.wireframe;
  18197. if (parsedMaterial.diffuseTexture) {
  18198. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18199. }
  18200. if (parsedMaterial.diffuseFresnelParameters) {
  18201. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18202. }
  18203. if (parsedMaterial.ambientTexture) {
  18204. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18205. }
  18206. if (parsedMaterial.opacityTexture) {
  18207. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18208. }
  18209. if (parsedMaterial.opacityFresnelParameters) {
  18210. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18211. }
  18212. if (parsedMaterial.reflectionTexture) {
  18213. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18214. }
  18215. if (parsedMaterial.reflectionFresnelParameters) {
  18216. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18217. }
  18218. if (parsedMaterial.emissiveTexture) {
  18219. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18220. }
  18221. if (parsedMaterial.emissiveFresnelParameters) {
  18222. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18223. }
  18224. if (parsedMaterial.specularTexture) {
  18225. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18226. }
  18227. if (parsedMaterial.bumpTexture) {
  18228. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18229. }
  18230. return material;
  18231. };
  18232. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18233. for (var index = 0; index < parsedData.materials.length; index++) {
  18234. var parsedMaterial = parsedData.materials[index];
  18235. if (parsedMaterial.id === id) {
  18236. return parseMaterial(parsedMaterial, scene, rootUrl);
  18237. }
  18238. }
  18239. return null;
  18240. };
  18241. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18242. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18243. multiMaterial.id = parsedMultiMaterial.id;
  18244. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18245. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18246. var subMatId = parsedMultiMaterial.materials[matIndex];
  18247. if (subMatId) {
  18248. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18249. }
  18250. else {
  18251. multiMaterial.subMaterials.push(null);
  18252. }
  18253. }
  18254. return multiMaterial;
  18255. };
  18256. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18257. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18258. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18259. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18260. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18261. var parsedFlare = parsedLensFlareSystem.flares[index];
  18262. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18263. }
  18264. return lensFlareSystem;
  18265. };
  18266. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18267. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18268. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18269. if (parsedParticleSystem.textureName) {
  18270. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18271. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18272. }
  18273. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18274. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18275. particleSystem.minSize = parsedParticleSystem.minSize;
  18276. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18277. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18278. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18279. particleSystem.emitter = emitter;
  18280. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18281. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18282. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18283. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18284. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18285. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18286. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18287. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18288. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18289. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18290. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18291. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18292. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18293. particleSystem.start();
  18294. return particleSystem;
  18295. };
  18296. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18297. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18298. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18299. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18300. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18301. shadowGenerator.getShadowMap().renderList.push(mesh);
  18302. }
  18303. if (parsedShadowGenerator.usePoissonSampling) {
  18304. shadowGenerator.usePoissonSampling = true;
  18305. }
  18306. else {
  18307. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  18308. }
  18309. return shadowGenerator;
  18310. };
  18311. var parseAnimation = function (parsedAnimation) {
  18312. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18313. var dataType = parsedAnimation.dataType;
  18314. var keys = [];
  18315. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18316. var key = parsedAnimation.keys[index];
  18317. var data;
  18318. switch (dataType) {
  18319. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18320. data = key.values[0];
  18321. break;
  18322. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18323. data = BABYLON.Quaternion.FromArray(key.values);
  18324. break;
  18325. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18326. data = BABYLON.Matrix.FromArray(key.values);
  18327. break;
  18328. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18329. default:
  18330. data = BABYLON.Vector3.FromArray(key.values);
  18331. break;
  18332. }
  18333. keys.push({
  18334. frame: key.frame,
  18335. value: data
  18336. });
  18337. }
  18338. animation.setKeys(keys);
  18339. return animation;
  18340. };
  18341. var parseLight = function (parsedLight, scene) {
  18342. var light;
  18343. switch (parsedLight.type) {
  18344. case 0:
  18345. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18346. break;
  18347. case 1:
  18348. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18349. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  18350. break;
  18351. case 2:
  18352. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18353. break;
  18354. case 3:
  18355. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18356. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18357. break;
  18358. }
  18359. light.id = parsedLight.id;
  18360. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18361. if (parsedLight.intensity !== undefined) {
  18362. light.intensity = parsedLight.intensity;
  18363. }
  18364. if (parsedLight.range) {
  18365. light.range = parsedLight.range;
  18366. }
  18367. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18368. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18369. if (parsedLight.excludedMeshesIds) {
  18370. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18371. }
  18372. // Parent
  18373. if (parsedLight.parentId) {
  18374. light._waitingParentId = parsedLight.parentId;
  18375. }
  18376. if (parsedLight.includedOnlyMeshesIds) {
  18377. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18378. }
  18379. // Animations
  18380. if (parsedLight.animations) {
  18381. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18382. var parsedAnimation = parsedLight.animations[animationIndex];
  18383. light.animations.push(parseAnimation(parsedAnimation));
  18384. }
  18385. }
  18386. if (parsedLight.autoAnimate) {
  18387. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  18388. }
  18389. };
  18390. var parseCamera = function (parsedCamera, scene) {
  18391. var camera;
  18392. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  18393. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  18394. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  18395. var alpha = parsedCamera.alpha;
  18396. var beta = parsedCamera.beta;
  18397. var radius = parsedCamera.radius;
  18398. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18399. var eye_space = parsedCamera.eye_space;
  18400. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18401. }
  18402. else {
  18403. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18404. }
  18405. }
  18406. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18407. eye_space = parsedCamera.eye_space;
  18408. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18409. }
  18410. else if (parsedCamera.type === "DeviceOrientationCamera") {
  18411. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18412. }
  18413. else if (parsedCamera.type === "FollowCamera") {
  18414. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18415. camera.heightOffset = parsedCamera.heightOffset;
  18416. camera.radius = parsedCamera.radius;
  18417. camera.rotationOffset = parsedCamera.rotationOffset;
  18418. if (lockedTargetMesh)
  18419. camera.target = lockedTargetMesh;
  18420. }
  18421. else if (parsedCamera.type === "GamepadCamera") {
  18422. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  18423. }
  18424. else if (parsedCamera.type === "OculusCamera") {
  18425. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  18426. }
  18427. else if (parsedCamera.type === "OculusGamepadCamera") {
  18428. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  18429. }
  18430. else if (parsedCamera.type === "TouchCamera") {
  18431. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  18432. }
  18433. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  18434. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  18435. }
  18436. else if (parsedCamera.type === "WebVRCamera") {
  18437. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  18438. }
  18439. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  18440. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  18441. }
  18442. else {
  18443. // Free Camera is the default value
  18444. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  18445. }
  18446. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  18447. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  18448. camera.lockedTarget = lockedTargetMesh;
  18449. }
  18450. camera.id = parsedCamera.id;
  18451. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  18452. // Parent
  18453. if (parsedCamera.parentId) {
  18454. camera._waitingParentId = parsedCamera.parentId;
  18455. }
  18456. // Target
  18457. if (parsedCamera.target) {
  18458. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18459. }
  18460. else {
  18461. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  18462. }
  18463. camera.fov = parsedCamera.fov;
  18464. camera.minZ = parsedCamera.minZ;
  18465. camera.maxZ = parsedCamera.maxZ;
  18466. camera.speed = parsedCamera.speed;
  18467. camera.inertia = parsedCamera.inertia;
  18468. camera.checkCollisions = parsedCamera.checkCollisions;
  18469. camera.applyGravity = parsedCamera.applyGravity;
  18470. if (parsedCamera.ellipsoid) {
  18471. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  18472. }
  18473. // Animations
  18474. if (parsedCamera.animations) {
  18475. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18476. var parsedAnimation = parsedCamera.animations[animationIndex];
  18477. camera.animations.push(parseAnimation(parsedAnimation));
  18478. }
  18479. }
  18480. if (parsedCamera.autoAnimate) {
  18481. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  18482. }
  18483. // Layer Mask
  18484. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  18485. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  18486. }
  18487. else {
  18488. camera.layerMask = 0xFFFFFFFF;
  18489. }
  18490. return camera;
  18491. };
  18492. var parseGeometry = function (parsedGeometry, scene) {
  18493. var id = parsedGeometry.id;
  18494. return scene.getGeometryByID(id);
  18495. };
  18496. var parseBox = function (parsedBox, scene) {
  18497. if (parseGeometry(parsedBox, scene)) {
  18498. return null; // null since geometry could be something else than a box...
  18499. }
  18500. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  18501. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  18502. scene.pushGeometry(box, true);
  18503. return box;
  18504. };
  18505. var parseSphere = function (parsedSphere, scene) {
  18506. if (parseGeometry(parsedSphere, scene)) {
  18507. return null; // null since geometry could be something else than a sphere...
  18508. }
  18509. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18510. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18511. scene.pushGeometry(sphere, true);
  18512. return sphere;
  18513. };
  18514. var parseCylinder = function (parsedCylinder, scene) {
  18515. if (parseGeometry(parsedCylinder, scene)) {
  18516. return null; // null since geometry could be something else than a cylinder...
  18517. }
  18518. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18519. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18520. scene.pushGeometry(cylinder, true);
  18521. return cylinder;
  18522. };
  18523. var parseTorus = function (parsedTorus, scene) {
  18524. if (parseGeometry(parsedTorus, scene)) {
  18525. return null; // null since geometry could be something else than a torus...
  18526. }
  18527. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18528. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18529. scene.pushGeometry(torus, true);
  18530. return torus;
  18531. };
  18532. var parseGround = function (parsedGround, scene) {
  18533. if (parseGeometry(parsedGround, scene)) {
  18534. return null; // null since geometry could be something else than a ground...
  18535. }
  18536. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18537. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18538. scene.pushGeometry(ground, true);
  18539. return ground;
  18540. };
  18541. var parsePlane = function (parsedPlane, scene) {
  18542. if (parseGeometry(parsedPlane, scene)) {
  18543. return null; // null since geometry could be something else than a plane...
  18544. }
  18545. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18546. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18547. scene.pushGeometry(plane, true);
  18548. return plane;
  18549. };
  18550. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18551. if (parseGeometry(parsedTorusKnot, scene)) {
  18552. return null; // null since geometry could be something else than a torusKnot...
  18553. }
  18554. 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);
  18555. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18556. scene.pushGeometry(torusKnot, true);
  18557. return torusKnot;
  18558. };
  18559. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18560. if (parseGeometry(parsedVertexData, scene)) {
  18561. return null; // null since geometry could be a primitive
  18562. }
  18563. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18564. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18565. if (parsedVertexData.delayLoadingFile) {
  18566. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18567. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18568. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18569. geometry._delayInfo = [];
  18570. if (parsedVertexData.hasUVs) {
  18571. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18572. }
  18573. if (parsedVertexData.hasUVs2) {
  18574. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18575. }
  18576. if (parsedVertexData.hasColors) {
  18577. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18578. }
  18579. if (parsedVertexData.hasMatricesIndices) {
  18580. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18581. }
  18582. if (parsedVertexData.hasMatricesWeights) {
  18583. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18584. }
  18585. geometry._delayLoadingFunction = importVertexData;
  18586. }
  18587. else {
  18588. importVertexData(parsedVertexData, geometry);
  18589. }
  18590. scene.pushGeometry(geometry, true);
  18591. return geometry;
  18592. };
  18593. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18594. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18595. mesh.id = parsedMesh.id;
  18596. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18597. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18598. if (parsedMesh.rotationQuaternion) {
  18599. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18600. }
  18601. else if (parsedMesh.rotation) {
  18602. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18603. }
  18604. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18605. if (parsedMesh.localMatrix) {
  18606. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18607. }
  18608. else if (parsedMesh.pivotMatrix) {
  18609. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18610. }
  18611. mesh.setEnabled(parsedMesh.isEnabled);
  18612. mesh.isVisible = parsedMesh.isVisible;
  18613. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18614. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18615. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18616. if (parsedMesh.applyFog !== undefined) {
  18617. mesh.applyFog = parsedMesh.applyFog;
  18618. }
  18619. if (parsedMesh.pickable !== undefined) {
  18620. mesh.isPickable = parsedMesh.pickable;
  18621. }
  18622. if (parsedMesh.alphaIndex !== undefined) {
  18623. mesh.alphaIndex = parsedMesh.alphaIndex;
  18624. }
  18625. mesh.receiveShadows = parsedMesh.receiveShadows;
  18626. mesh.billboardMode = parsedMesh.billboardMode;
  18627. if (parsedMesh.visibility !== undefined) {
  18628. mesh.visibility = parsedMesh.visibility;
  18629. }
  18630. mesh.checkCollisions = parsedMesh.checkCollisions;
  18631. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18632. // Parent
  18633. if (parsedMesh.parentId) {
  18634. mesh._waitingParentId = parsedMesh.parentId;
  18635. }
  18636. // Actions
  18637. if (parsedMesh.actions !== undefined) {
  18638. mesh._waitingActions = parsedMesh.actions;
  18639. }
  18640. // Geometry
  18641. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18642. if (parsedMesh.delayLoadingFile) {
  18643. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18644. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18645. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18646. if (parsedMesh._binaryInfo) {
  18647. mesh._binaryInfo = parsedMesh._binaryInfo;
  18648. }
  18649. mesh._delayInfo = [];
  18650. if (parsedMesh.hasUVs) {
  18651. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18652. }
  18653. if (parsedMesh.hasUVs2) {
  18654. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18655. }
  18656. if (parsedMesh.hasColors) {
  18657. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18658. }
  18659. if (parsedMesh.hasMatricesIndices) {
  18660. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18661. }
  18662. if (parsedMesh.hasMatricesWeights) {
  18663. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18664. }
  18665. mesh._delayLoadingFunction = importGeometry;
  18666. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18667. mesh._checkDelayState();
  18668. }
  18669. }
  18670. else {
  18671. importGeometry(parsedMesh, mesh);
  18672. }
  18673. // Material
  18674. if (parsedMesh.materialId) {
  18675. mesh.setMaterialByID(parsedMesh.materialId);
  18676. }
  18677. else {
  18678. mesh.material = null;
  18679. }
  18680. // Skeleton
  18681. if (parsedMesh.skeletonId > -1) {
  18682. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18683. }
  18684. // Physics
  18685. if (parsedMesh.physicsImpostor) {
  18686. if (!scene.isPhysicsEnabled()) {
  18687. scene.enablePhysics();
  18688. }
  18689. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18690. }
  18691. // Animations
  18692. if (parsedMesh.animations) {
  18693. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18694. var parsedAnimation = parsedMesh.animations[animationIndex];
  18695. mesh.animations.push(parseAnimation(parsedAnimation));
  18696. }
  18697. }
  18698. if (parsedMesh.autoAnimate) {
  18699. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18700. }
  18701. // Layer Mask
  18702. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18703. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18704. }
  18705. else {
  18706. mesh.layerMask = 0xFFFFFFFF;
  18707. }
  18708. // Instances
  18709. if (parsedMesh.instances) {
  18710. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18711. var parsedInstance = parsedMesh.instances[index];
  18712. var instance = mesh.createInstance(parsedInstance.name);
  18713. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18714. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18715. if (parsedInstance.rotationQuaternion) {
  18716. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18717. }
  18718. else if (parsedInstance.rotation) {
  18719. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18720. }
  18721. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18722. instance.checkCollisions = mesh.checkCollisions;
  18723. if (parsedMesh.animations) {
  18724. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18725. parsedAnimation = parsedMesh.animations[animationIndex];
  18726. instance.animations.push(parseAnimation(parsedAnimation));
  18727. }
  18728. }
  18729. }
  18730. }
  18731. return mesh;
  18732. };
  18733. var parseActions = function (parsedActions, object, scene) {
  18734. var actionManager = new BABYLON.ActionManager(scene);
  18735. if (object === null)
  18736. scene.actionManager = actionManager;
  18737. else
  18738. object.actionManager = actionManager;
  18739. // instanciate a new object
  18740. var instanciate = function (name, params) {
  18741. var newInstance = Object.create(BABYLON[name].prototype);
  18742. newInstance.constructor.apply(newInstance, params);
  18743. return newInstance;
  18744. };
  18745. var parseParameter = function (name, value, target, propertyPath) {
  18746. if (propertyPath === null) {
  18747. // String, boolean or float
  18748. var floatValue = parseFloat(value);
  18749. if (value === "true" || value === "false")
  18750. return value === "true";
  18751. else
  18752. return isNaN(floatValue) ? value : floatValue;
  18753. }
  18754. var effectiveTarget = propertyPath.split(".");
  18755. var values = value.split(",");
  18756. for (var i = 0; i < effectiveTarget.length; i++) {
  18757. target = target[effectiveTarget[i]];
  18758. }
  18759. // Return appropriate value with its type
  18760. if (target instanceof Boolean)
  18761. return values[0] === "true";
  18762. if (target instanceof String)
  18763. return values[0];
  18764. // Parameters with multiple values such as Vector3 etc.
  18765. var split = new Array();
  18766. for (var i = 0; i < values.length; i++)
  18767. split.push(parseFloat(values[i]));
  18768. if (target instanceof BABYLON.Vector3)
  18769. return BABYLON.Vector3.FromArray(split);
  18770. if (target instanceof BABYLON.Vector4)
  18771. return BABYLON.Vector4.FromArray(split);
  18772. if (target instanceof BABYLON.Color3)
  18773. return BABYLON.Color3.FromArray(split);
  18774. if (target instanceof BABYLON.Color4)
  18775. return BABYLON.Color4.FromArray(split);
  18776. return parseFloat(values[0]);
  18777. };
  18778. // traverse graph per trigger
  18779. var traverse = function (parsedAction, trigger, condition, action) {
  18780. var parameters = new Array();
  18781. var target = null;
  18782. var propertyPath = null;
  18783. // Parameters
  18784. if (parsedAction.type === 2)
  18785. parameters.push(actionManager);
  18786. else
  18787. parameters.push(trigger);
  18788. for (var i = 0; i < parsedAction.properties.length; i++) {
  18789. var value = parsedAction.properties[i].value;
  18790. var name = parsedAction.properties[i].name;
  18791. if (name === "target")
  18792. value = target = scene.getNodeByName(value);
  18793. else if (name === "parent")
  18794. value = scene.getNodeByName(value);
  18795. else if (name === "sound")
  18796. value = scene.getSoundByName(value);
  18797. else if (name !== "propertyPath") {
  18798. if (parsedAction.type === 2 && name === "operator")
  18799. value = BABYLON.ValueCondition[value];
  18800. else
  18801. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  18802. }
  18803. else {
  18804. propertyPath = value;
  18805. }
  18806. parameters.push(value);
  18807. }
  18808. parameters.push(condition);
  18809. // If interpolate value action
  18810. if (parsedAction.name === "InterpolateValueAction") {
  18811. var param = parameters[parameters.length - 2];
  18812. parameters[parameters.length - 1] = param;
  18813. parameters[parameters.length - 2] = condition;
  18814. }
  18815. // Action or condition(s)
  18816. var newAction = instanciate(parsedAction.name, parameters);
  18817. if (newAction instanceof BABYLON.Condition) {
  18818. condition = newAction;
  18819. newAction = action;
  18820. }
  18821. else {
  18822. condition = null;
  18823. if (action)
  18824. action.then(newAction);
  18825. else
  18826. actionManager.registerAction(newAction);
  18827. }
  18828. for (var i = 0; i < parsedAction.children.length; i++)
  18829. traverse(parsedAction.children[i], trigger, condition, newAction);
  18830. };
  18831. for (var i = 0; i < parsedActions.children.length; i++) {
  18832. var triggerParams;
  18833. var trigger = parsedActions.children[i];
  18834. if (trigger.properties.length > 0) {
  18835. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  18836. }
  18837. else
  18838. triggerParams = BABYLON.ActionManager[trigger.name];
  18839. for (var j = 0; j < trigger.children.length; j++)
  18840. traverse(trigger.children[j], triggerParams, null, null);
  18841. }
  18842. };
  18843. var parseSound = function (parsedSound, scene, rootUrl) {
  18844. var soundName = parsedSound.name;
  18845. var soundUrl = rootUrl + soundName;
  18846. var options = {
  18847. autoplay: parsedSound.autoplay,
  18848. loop: parsedSound.loop,
  18849. volume: parsedSound.volume,
  18850. spatialSound: parsedSound.spatialSound,
  18851. maxDistance: parsedSound.maxDistance,
  18852. rolloffFactor: parsedSound.rolloffFactor,
  18853. refDistance: parsedSound.refDistance,
  18854. distanceModel: parsedSound.distanceModel,
  18855. panningModel: parsedSound.panningModel,
  18856. playbackRate: parsedSound.playbackRate
  18857. };
  18858. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  18859. scene._removePendingData(newSound);
  18860. }, options);
  18861. scene._addPendingData(newSound);
  18862. if (parsedSound.position) {
  18863. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  18864. newSound.setPosition(soundPosition);
  18865. }
  18866. if (parsedSound.isDirectional) {
  18867. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  18868. if (parsedSound.localDirectionToMesh) {
  18869. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  18870. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  18871. }
  18872. }
  18873. if (parsedSound.connectedMeshId) {
  18874. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  18875. if (connectedMesh) {
  18876. newSound.attachToMesh(connectedMesh);
  18877. }
  18878. }
  18879. };
  18880. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18881. names = (names instanceof Array) ? names : [names];
  18882. for (var i in names) {
  18883. if (mesh.name === names[i]) {
  18884. hierarchyIds.push(mesh.id);
  18885. return true;
  18886. }
  18887. }
  18888. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18889. hierarchyIds.push(mesh.id);
  18890. return true;
  18891. }
  18892. return false;
  18893. };
  18894. var importVertexData = function (parsedVertexData, geometry) {
  18895. var vertexData = new BABYLON.VertexData();
  18896. // positions
  18897. var positions = parsedVertexData.positions;
  18898. if (positions) {
  18899. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18900. }
  18901. // normals
  18902. var normals = parsedVertexData.normals;
  18903. if (normals) {
  18904. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18905. }
  18906. // uvs
  18907. var uvs = parsedVertexData.uvs;
  18908. if (uvs) {
  18909. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  18910. }
  18911. // uv2s
  18912. var uv2s = parsedVertexData.uv2s;
  18913. if (uv2s) {
  18914. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  18915. }
  18916. // colors
  18917. var colors = parsedVertexData.colors;
  18918. if (colors) {
  18919. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  18920. }
  18921. // matricesIndices
  18922. var matricesIndices = parsedVertexData.matricesIndices;
  18923. if (matricesIndices) {
  18924. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  18925. }
  18926. // matricesWeights
  18927. var matricesWeights = parsedVertexData.matricesWeights;
  18928. if (matricesWeights) {
  18929. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  18930. }
  18931. // indices
  18932. var indices = parsedVertexData.indices;
  18933. if (indices) {
  18934. vertexData.indices = indices;
  18935. }
  18936. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  18937. };
  18938. var importGeometry = function (parsedGeometry, mesh) {
  18939. var scene = mesh.getScene();
  18940. // Geometry
  18941. var geometryId = parsedGeometry.geometryId;
  18942. if (geometryId) {
  18943. var geometry = scene.getGeometryByID(geometryId);
  18944. if (geometry) {
  18945. geometry.applyToMesh(mesh);
  18946. }
  18947. }
  18948. else if (parsedGeometry instanceof ArrayBuffer) {
  18949. var binaryInfo = mesh._binaryInfo;
  18950. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  18951. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  18952. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  18953. }
  18954. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  18955. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  18956. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  18957. }
  18958. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  18959. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  18960. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  18961. }
  18962. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  18963. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  18964. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  18965. }
  18966. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  18967. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  18968. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  18969. }
  18970. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  18971. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  18972. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  18973. }
  18974. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  18975. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  18976. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  18977. }
  18978. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  18979. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  18980. mesh.setIndices(indicesData);
  18981. }
  18982. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  18983. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  18984. mesh.subMeshes = [];
  18985. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  18986. var materialIndex = subMeshesData[(i * 5) + 0];
  18987. var verticesStart = subMeshesData[(i * 5) + 1];
  18988. var verticesCount = subMeshesData[(i * 5) + 2];
  18989. var indexStart = subMeshesData[(i * 5) + 3];
  18990. var indexCount = subMeshesData[(i * 5) + 4];
  18991. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  18992. }
  18993. }
  18994. }
  18995. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  18996. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  18997. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  18998. if (parsedGeometry.uvs) {
  18999. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19000. }
  19001. if (parsedGeometry.uvs2) {
  19002. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19003. }
  19004. if (parsedGeometry.colors) {
  19005. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19006. }
  19007. if (parsedGeometry.matricesIndices) {
  19008. if (!parsedGeometry.matricesIndices._isExpanded) {
  19009. var floatIndices = [];
  19010. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19011. var matricesIndex = parsedGeometry.matricesIndices[i];
  19012. floatIndices.push(matricesIndex & 0x000000FF);
  19013. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19014. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19015. floatIndices.push(matricesIndex >> 24);
  19016. }
  19017. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19018. }
  19019. else {
  19020. delete parsedGeometry.matricesIndices._isExpanded;
  19021. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19022. }
  19023. }
  19024. if (parsedGeometry.matricesWeights) {
  19025. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19026. }
  19027. mesh.setIndices(parsedGeometry.indices);
  19028. // SubMeshes
  19029. if (parsedGeometry.subMeshes) {
  19030. mesh.subMeshes = [];
  19031. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19032. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19033. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19034. }
  19035. }
  19036. }
  19037. // Flat shading
  19038. if (mesh._shouldGenerateFlatShading) {
  19039. mesh.convertToFlatShadedMesh();
  19040. delete mesh._shouldGenerateFlatShading;
  19041. }
  19042. // Update
  19043. mesh.computeWorldMatrix(true);
  19044. // Octree
  19045. if (scene._selectionOctree) {
  19046. scene._selectionOctree.addMesh(mesh);
  19047. }
  19048. };
  19049. BABYLON.SceneLoader.RegisterPlugin({
  19050. extensions: ".babylon",
  19051. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19052. var parsedData = JSON.parse(data);
  19053. var loadedSkeletonsIds = [];
  19054. var loadedMaterialsIds = [];
  19055. var hierarchyIds = [];
  19056. for (var index = 0; index < parsedData.meshes.length; index++) {
  19057. var parsedMesh = parsedData.meshes[index];
  19058. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19059. if (meshesNames instanceof Array) {
  19060. // Remove found mesh name from list.
  19061. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19062. }
  19063. // Material ?
  19064. if (parsedMesh.materialId) {
  19065. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19066. if (!materialFound) {
  19067. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19068. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19069. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19070. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19071. var subMatId = parsedMultiMaterial.materials[matIndex];
  19072. loadedMaterialsIds.push(subMatId);
  19073. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19074. }
  19075. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19076. parseMultiMaterial(parsedMultiMaterial, scene);
  19077. materialFound = true;
  19078. break;
  19079. }
  19080. }
  19081. }
  19082. if (!materialFound) {
  19083. loadedMaterialsIds.push(parsedMesh.materialId);
  19084. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19085. }
  19086. }
  19087. // Skeleton ?
  19088. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19089. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19090. if (!skeletonAlreadyLoaded) {
  19091. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19092. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19093. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19094. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19095. loadedSkeletonsIds.push(parsedSkeleton.id);
  19096. }
  19097. }
  19098. }
  19099. }
  19100. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19101. meshes.push(mesh);
  19102. }
  19103. }
  19104. for (index = 0; index < scene.meshes.length; index++) {
  19105. var currentMesh = scene.meshes[index];
  19106. if (currentMesh._waitingParentId) {
  19107. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19108. currentMesh._waitingParentId = undefined;
  19109. }
  19110. }
  19111. // Particles
  19112. if (parsedData.particleSystems) {
  19113. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19114. var parsedParticleSystem = parsedData.particleSystems[index];
  19115. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19116. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19117. }
  19118. }
  19119. }
  19120. return true;
  19121. },
  19122. load: function (scene, data, rootUrl) {
  19123. var parsedData = JSON.parse(data);
  19124. // Scene
  19125. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19126. scene.autoClear = parsedData.autoClear;
  19127. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19128. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19129. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19130. // Fog
  19131. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19132. scene.fogMode = parsedData.fogMode;
  19133. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19134. scene.fogStart = parsedData.fogStart;
  19135. scene.fogEnd = parsedData.fogEnd;
  19136. scene.fogDensity = parsedData.fogDensity;
  19137. }
  19138. for (var index = 0; index < parsedData.lights.length; index++) {
  19139. var parsedLight = parsedData.lights[index];
  19140. parseLight(parsedLight, scene);
  19141. }
  19142. // Materials
  19143. if (parsedData.materials) {
  19144. for (index = 0; index < parsedData.materials.length; index++) {
  19145. var parsedMaterial = parsedData.materials[index];
  19146. parseMaterial(parsedMaterial, scene, rootUrl);
  19147. }
  19148. }
  19149. if (parsedData.multiMaterials) {
  19150. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19151. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19152. parseMultiMaterial(parsedMultiMaterial, scene);
  19153. }
  19154. }
  19155. // Skeletons
  19156. if (parsedData.skeletons) {
  19157. for (index = 0; index < parsedData.skeletons.length; index++) {
  19158. var parsedSkeleton = parsedData.skeletons[index];
  19159. parseSkeleton(parsedSkeleton, scene);
  19160. }
  19161. }
  19162. // Geometries
  19163. var geometries = parsedData.geometries;
  19164. if (geometries) {
  19165. // Boxes
  19166. var boxes = geometries.boxes;
  19167. if (boxes) {
  19168. for (index = 0; index < boxes.length; index++) {
  19169. var parsedBox = boxes[index];
  19170. parseBox(parsedBox, scene);
  19171. }
  19172. }
  19173. // Spheres
  19174. var spheres = geometries.spheres;
  19175. if (spheres) {
  19176. for (index = 0; index < spheres.length; index++) {
  19177. var parsedSphere = spheres[index];
  19178. parseSphere(parsedSphere, scene);
  19179. }
  19180. }
  19181. // Cylinders
  19182. var cylinders = geometries.cylinders;
  19183. if (cylinders) {
  19184. for (index = 0; index < cylinders.length; index++) {
  19185. var parsedCylinder = cylinders[index];
  19186. parseCylinder(parsedCylinder, scene);
  19187. }
  19188. }
  19189. // Toruses
  19190. var toruses = geometries.toruses;
  19191. if (toruses) {
  19192. for (index = 0; index < toruses.length; index++) {
  19193. var parsedTorus = toruses[index];
  19194. parseTorus(parsedTorus, scene);
  19195. }
  19196. }
  19197. // Grounds
  19198. var grounds = geometries.grounds;
  19199. if (grounds) {
  19200. for (index = 0; index < grounds.length; index++) {
  19201. var parsedGround = grounds[index];
  19202. parseGround(parsedGround, scene);
  19203. }
  19204. }
  19205. // Planes
  19206. var planes = geometries.planes;
  19207. if (planes) {
  19208. for (index = 0; index < planes.length; index++) {
  19209. var parsedPlane = planes[index];
  19210. parsePlane(parsedPlane, scene);
  19211. }
  19212. }
  19213. // TorusKnots
  19214. var torusKnots = geometries.torusKnots;
  19215. if (torusKnots) {
  19216. for (index = 0; index < torusKnots.length; index++) {
  19217. var parsedTorusKnot = torusKnots[index];
  19218. parseTorusKnot(parsedTorusKnot, scene);
  19219. }
  19220. }
  19221. // VertexData
  19222. var vertexData = geometries.vertexData;
  19223. if (vertexData) {
  19224. for (index = 0; index < vertexData.length; index++) {
  19225. var parsedVertexData = vertexData[index];
  19226. parseVertexData(parsedVertexData, scene, rootUrl);
  19227. }
  19228. }
  19229. }
  19230. for (index = 0; index < parsedData.meshes.length; index++) {
  19231. var parsedMesh = parsedData.meshes[index];
  19232. parseMesh(parsedMesh, scene, rootUrl);
  19233. }
  19234. for (index = 0; index < parsedData.cameras.length; index++) {
  19235. var parsedCamera = parsedData.cameras[index];
  19236. parseCamera(parsedCamera, scene);
  19237. }
  19238. if (parsedData.activeCameraID) {
  19239. scene.setActiveCameraByID(parsedData.activeCameraID);
  19240. }
  19241. for (index = 0; index < scene.cameras.length; index++) {
  19242. var camera = scene.cameras[index];
  19243. if (camera._waitingParentId) {
  19244. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19245. camera._waitingParentId = undefined;
  19246. }
  19247. }
  19248. for (index = 0; index < scene.lights.length; index++) {
  19249. var light = scene.lights[index];
  19250. if (light._waitingParentId) {
  19251. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19252. light._waitingParentId = undefined;
  19253. }
  19254. }
  19255. // Sounds
  19256. if (parsedData.sounds && BABYLON.Engine.audioEngine.canUseWebAudio) {
  19257. for (index = 0; index < parsedData.sounds.length; index++) {
  19258. var parsedSound = parsedData.sounds[index];
  19259. parseSound(parsedSound, scene, rootUrl);
  19260. }
  19261. }
  19262. for (index = 0; index < scene.meshes.length; index++) {
  19263. var mesh = scene.meshes[index];
  19264. if (mesh._waitingParentId) {
  19265. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19266. mesh._waitingParentId = undefined;
  19267. }
  19268. if (mesh._waitingActions) {
  19269. parseActions(mesh._waitingActions, mesh, scene);
  19270. mesh._waitingActions = undefined;
  19271. }
  19272. }
  19273. // Particles Systems
  19274. if (parsedData.particleSystems) {
  19275. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19276. var parsedParticleSystem = parsedData.particleSystems[index];
  19277. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19278. }
  19279. }
  19280. // Lens flares
  19281. if (parsedData.lensFlareSystems) {
  19282. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19283. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19284. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19285. }
  19286. }
  19287. // Shadows
  19288. if (parsedData.shadowGenerators) {
  19289. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  19290. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  19291. parseShadowGenerator(parsedShadowGenerator, scene);
  19292. }
  19293. }
  19294. // Actions (scene)
  19295. if (parsedData.actions) {
  19296. parseActions(parsedData.actions, null, scene);
  19297. }
  19298. // Finish
  19299. return true;
  19300. }
  19301. });
  19302. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  19303. })(BABYLON || (BABYLON = {}));
  19304. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  19305. (function (BABYLON) {
  19306. // Unique ID when we import meshes from Babylon to CSG
  19307. var currentCSGMeshId = 0;
  19308. // # class Vertex
  19309. // Represents a vertex of a polygon. Use your own vertex class instead of this
  19310. // one to provide additional features like texture coordinates and vertex
  19311. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  19312. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  19313. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  19314. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  19315. // is not used anywhere else.
  19316. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  19317. var Vertex = (function () {
  19318. function Vertex(pos, normal, uv) {
  19319. this.pos = pos;
  19320. this.normal = normal;
  19321. this.uv = uv;
  19322. }
  19323. Vertex.prototype.clone = function () {
  19324. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  19325. };
  19326. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  19327. // orientation of a polygon is flipped.
  19328. Vertex.prototype.flip = function () {
  19329. this.normal = this.normal.scale(-1);
  19330. };
  19331. // Create a new vertex between this vertex and `other` by linearly
  19332. // interpolating all properties using a parameter of `t`. Subclasses should
  19333. // override this to interpolate additional properties.
  19334. Vertex.prototype.interpolate = function (other, t) {
  19335. 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));
  19336. };
  19337. return Vertex;
  19338. })();
  19339. // # class Plane
  19340. // Represents a plane in 3D space.
  19341. var Plane = (function () {
  19342. function Plane(normal, w) {
  19343. this.normal = normal;
  19344. this.w = w;
  19345. }
  19346. Plane.FromPoints = function (a, b, c) {
  19347. var v0 = c.subtract(a);
  19348. var v1 = b.subtract(a);
  19349. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  19350. return null;
  19351. }
  19352. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  19353. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  19354. };
  19355. Plane.prototype.clone = function () {
  19356. return new Plane(this.normal.clone(), this.w);
  19357. };
  19358. Plane.prototype.flip = function () {
  19359. this.normal.scaleInPlace(-1);
  19360. this.w = -this.w;
  19361. };
  19362. // Split `polygon` by this plane if needed, then put the polygon or polygon
  19363. // fragments in the appropriate lists. Coplanar polygons go into either
  19364. // `coplanarFront` or `coplanarBack` depending on their orientation with
  19365. // respect to this plane. Polygons in front or in back of this plane go into
  19366. // either `front` or `back`.
  19367. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  19368. var COPLANAR = 0;
  19369. var FRONT = 1;
  19370. var BACK = 2;
  19371. var SPANNING = 3;
  19372. // Classify each point as well as the entire polygon into one of the above
  19373. // four classes.
  19374. var polygonType = 0;
  19375. var types = [];
  19376. for (var i = 0; i < polygon.vertices.length; i++) {
  19377. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  19378. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  19379. polygonType |= type;
  19380. types.push(type);
  19381. }
  19382. switch (polygonType) {
  19383. case COPLANAR:
  19384. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  19385. break;
  19386. case FRONT:
  19387. front.push(polygon);
  19388. break;
  19389. case BACK:
  19390. back.push(polygon);
  19391. break;
  19392. case SPANNING:
  19393. var f = [], b = [];
  19394. for (i = 0; i < polygon.vertices.length; i++) {
  19395. var j = (i + 1) % polygon.vertices.length;
  19396. var ti = types[i], tj = types[j];
  19397. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  19398. if (ti != BACK)
  19399. f.push(vi);
  19400. if (ti != FRONT)
  19401. b.push(ti != BACK ? vi.clone() : vi);
  19402. if ((ti | tj) == SPANNING) {
  19403. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  19404. var v = vi.interpolate(vj, t);
  19405. f.push(v);
  19406. b.push(v.clone());
  19407. }
  19408. }
  19409. if (f.length >= 3) {
  19410. var poly = new Polygon(f, polygon.shared);
  19411. if (poly.plane)
  19412. front.push(poly);
  19413. }
  19414. if (b.length >= 3) {
  19415. poly = new Polygon(b, polygon.shared);
  19416. if (poly.plane)
  19417. back.push(poly);
  19418. }
  19419. break;
  19420. }
  19421. };
  19422. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  19423. // point is on the plane.
  19424. Plane.EPSILON = 1e-5;
  19425. return Plane;
  19426. })();
  19427. // # class Polygon
  19428. // Represents a convex polygon. The vertices used to initialize a polygon must
  19429. // be coplanar and form a convex loop.
  19430. //
  19431. // Each convex polygon has a `shared` property, which is shared between all
  19432. // polygons that are clones of each other or were split from the same polygon.
  19433. // This can be used to define per-polygon properties (such as surface color).
  19434. var Polygon = (function () {
  19435. function Polygon(vertices, shared) {
  19436. this.vertices = vertices;
  19437. this.shared = shared;
  19438. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  19439. }
  19440. Polygon.prototype.clone = function () {
  19441. var vertices = this.vertices.map(function (v) { return v.clone(); });
  19442. return new Polygon(vertices, this.shared);
  19443. };
  19444. Polygon.prototype.flip = function () {
  19445. this.vertices.reverse().map(function (v) {
  19446. v.flip();
  19447. });
  19448. this.plane.flip();
  19449. };
  19450. return Polygon;
  19451. })();
  19452. // # class Node
  19453. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  19454. // by picking a polygon to split along. That polygon (and all other coplanar
  19455. // polygons) are added directly to that node and the other polygons are added to
  19456. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  19457. // no distinction between internal and leaf nodes.
  19458. var Node = (function () {
  19459. function Node(polygons) {
  19460. this.plane = null;
  19461. this.front = null;
  19462. this.back = null;
  19463. this.polygons = [];
  19464. if (polygons) {
  19465. this.build(polygons);
  19466. }
  19467. }
  19468. Node.prototype.clone = function () {
  19469. var node = new Node();
  19470. node.plane = this.plane && this.plane.clone();
  19471. node.front = this.front && this.front.clone();
  19472. node.back = this.back && this.back.clone();
  19473. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  19474. return node;
  19475. };
  19476. // Convert solid space to empty space and empty space to solid space.
  19477. Node.prototype.invert = function () {
  19478. for (var i = 0; i < this.polygons.length; i++) {
  19479. this.polygons[i].flip();
  19480. }
  19481. if (this.plane) {
  19482. this.plane.flip();
  19483. }
  19484. if (this.front) {
  19485. this.front.invert();
  19486. }
  19487. if (this.back) {
  19488. this.back.invert();
  19489. }
  19490. var temp = this.front;
  19491. this.front = this.back;
  19492. this.back = temp;
  19493. };
  19494. // Recursively remove all polygons in `polygons` that are inside this BSP
  19495. // tree.
  19496. Node.prototype.clipPolygons = function (polygons) {
  19497. if (!this.plane)
  19498. return polygons.slice();
  19499. var front = [], back = [];
  19500. for (var i = 0; i < polygons.length; i++) {
  19501. this.plane.splitPolygon(polygons[i], front, back, front, back);
  19502. }
  19503. if (this.front) {
  19504. front = this.front.clipPolygons(front);
  19505. }
  19506. if (this.back) {
  19507. back = this.back.clipPolygons(back);
  19508. }
  19509. else {
  19510. back = [];
  19511. }
  19512. return front.concat(back);
  19513. };
  19514. // Remove all polygons in this BSP tree that are inside the other BSP tree
  19515. // `bsp`.
  19516. Node.prototype.clipTo = function (bsp) {
  19517. this.polygons = bsp.clipPolygons(this.polygons);
  19518. if (this.front)
  19519. this.front.clipTo(bsp);
  19520. if (this.back)
  19521. this.back.clipTo(bsp);
  19522. };
  19523. // Return a list of all polygons in this BSP tree.
  19524. Node.prototype.allPolygons = function () {
  19525. var polygons = this.polygons.slice();
  19526. if (this.front)
  19527. polygons = polygons.concat(this.front.allPolygons());
  19528. if (this.back)
  19529. polygons = polygons.concat(this.back.allPolygons());
  19530. return polygons;
  19531. };
  19532. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  19533. // new polygons are filtered down to the bottom of the tree and become new
  19534. // nodes there. Each set of polygons is partitioned using the first polygon
  19535. // (no heuristic is used to pick a good split).
  19536. Node.prototype.build = function (polygons) {
  19537. if (!polygons.length)
  19538. return;
  19539. if (!this.plane)
  19540. this.plane = polygons[0].plane.clone();
  19541. var front = [], back = [];
  19542. for (var i = 0; i < polygons.length; i++) {
  19543. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  19544. }
  19545. if (front.length) {
  19546. if (!this.front)
  19547. this.front = new Node();
  19548. this.front.build(front);
  19549. }
  19550. if (back.length) {
  19551. if (!this.back)
  19552. this.back = new Node();
  19553. this.back.build(back);
  19554. }
  19555. };
  19556. return Node;
  19557. })();
  19558. var CSG = (function () {
  19559. function CSG() {
  19560. this.polygons = new Array();
  19561. }
  19562. // Convert BABYLON.Mesh to BABYLON.CSG
  19563. CSG.FromMesh = function (mesh) {
  19564. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  19565. if (mesh instanceof BABYLON.Mesh) {
  19566. mesh.computeWorldMatrix(true);
  19567. var matrix = mesh.getWorldMatrix();
  19568. var meshPosition = mesh.position.clone();
  19569. var meshRotation = mesh.rotation.clone();
  19570. var meshScaling = mesh.scaling.clone();
  19571. }
  19572. else {
  19573. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  19574. }
  19575. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19576. var subMeshes = mesh.subMeshes;
  19577. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  19578. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  19579. vertices = [];
  19580. for (var j = 0; j < 3; j++) {
  19581. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  19582. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  19583. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  19584. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  19585. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  19586. vertex = new Vertex(position, normal, uv);
  19587. vertices.push(vertex);
  19588. }
  19589. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  19590. // To handle the case of degenerated triangle
  19591. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  19592. if (polygon.plane)
  19593. polygons.push(polygon);
  19594. }
  19595. }
  19596. var csg = CSG.FromPolygons(polygons);
  19597. csg.matrix = matrix;
  19598. csg.position = meshPosition;
  19599. csg.rotation = meshRotation;
  19600. csg.scaling = meshScaling;
  19601. currentCSGMeshId++;
  19602. return csg;
  19603. };
  19604. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  19605. CSG.FromPolygons = function (polygons) {
  19606. var csg = new BABYLON.CSG();
  19607. csg.polygons = polygons;
  19608. return csg;
  19609. };
  19610. CSG.prototype.clone = function () {
  19611. var csg = new BABYLON.CSG();
  19612. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  19613. csg.copyTransformAttributes(this);
  19614. return csg;
  19615. };
  19616. CSG.prototype.toPolygons = function () {
  19617. return this.polygons;
  19618. };
  19619. CSG.prototype.union = function (csg) {
  19620. var a = new Node(this.clone().polygons);
  19621. var b = new Node(csg.clone().polygons);
  19622. a.clipTo(b);
  19623. b.clipTo(a);
  19624. b.invert();
  19625. b.clipTo(a);
  19626. b.invert();
  19627. a.build(b.allPolygons());
  19628. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19629. };
  19630. CSG.prototype.unionInPlace = function (csg) {
  19631. var a = new Node(this.polygons);
  19632. var b = new Node(csg.polygons);
  19633. a.clipTo(b);
  19634. b.clipTo(a);
  19635. b.invert();
  19636. b.clipTo(a);
  19637. b.invert();
  19638. a.build(b.allPolygons());
  19639. this.polygons = a.allPolygons();
  19640. };
  19641. CSG.prototype.subtract = function (csg) {
  19642. var a = new Node(this.clone().polygons);
  19643. var b = new Node(csg.clone().polygons);
  19644. a.invert();
  19645. a.clipTo(b);
  19646. b.clipTo(a);
  19647. b.invert();
  19648. b.clipTo(a);
  19649. b.invert();
  19650. a.build(b.allPolygons());
  19651. a.invert();
  19652. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19653. };
  19654. CSG.prototype.subtractInPlace = function (csg) {
  19655. var a = new Node(this.polygons);
  19656. var b = new Node(csg.polygons);
  19657. a.invert();
  19658. a.clipTo(b);
  19659. b.clipTo(a);
  19660. b.invert();
  19661. b.clipTo(a);
  19662. b.invert();
  19663. a.build(b.allPolygons());
  19664. a.invert();
  19665. this.polygons = a.allPolygons();
  19666. };
  19667. CSG.prototype.intersect = function (csg) {
  19668. var a = new Node(this.clone().polygons);
  19669. var b = new Node(csg.clone().polygons);
  19670. a.invert();
  19671. b.clipTo(a);
  19672. b.invert();
  19673. a.clipTo(b);
  19674. b.clipTo(a);
  19675. a.build(b.allPolygons());
  19676. a.invert();
  19677. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19678. };
  19679. CSG.prototype.intersectInPlace = function (csg) {
  19680. var a = new Node(this.polygons);
  19681. var b = new Node(csg.polygons);
  19682. a.invert();
  19683. b.clipTo(a);
  19684. b.invert();
  19685. a.clipTo(b);
  19686. b.clipTo(a);
  19687. a.build(b.allPolygons());
  19688. a.invert();
  19689. this.polygons = a.allPolygons();
  19690. };
  19691. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  19692. // not modified.
  19693. CSG.prototype.inverse = function () {
  19694. var csg = this.clone();
  19695. csg.inverseInPlace();
  19696. return csg;
  19697. };
  19698. CSG.prototype.inverseInPlace = function () {
  19699. this.polygons.map(function (p) {
  19700. p.flip();
  19701. });
  19702. };
  19703. // This is used to keep meshes transformations so they can be restored
  19704. // when we build back a Babylon Mesh
  19705. // NB : All CSG operations are performed in world coordinates
  19706. CSG.prototype.copyTransformAttributes = function (csg) {
  19707. this.matrix = csg.matrix;
  19708. this.position = csg.position;
  19709. this.rotation = csg.rotation;
  19710. this.scaling = csg.scaling;
  19711. return this;
  19712. };
  19713. // Build Raw mesh from CSG
  19714. // Coordinates here are in world space
  19715. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  19716. var matrix = this.matrix.clone();
  19717. matrix.invert();
  19718. 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;
  19719. if (keepSubMeshes) {
  19720. // Sort Polygons, since subMeshes are indices range
  19721. polygons.sort(function (a, b) {
  19722. if (a.shared.meshId === b.shared.meshId) {
  19723. return a.shared.subMeshId - b.shared.subMeshId;
  19724. }
  19725. else {
  19726. return a.shared.meshId - b.shared.meshId;
  19727. }
  19728. });
  19729. }
  19730. for (var i = 0, il = polygons.length; i < il; i++) {
  19731. polygon = polygons[i];
  19732. // Building SubMeshes
  19733. if (!subMesh_dict[polygon.shared.meshId]) {
  19734. subMesh_dict[polygon.shared.meshId] = {};
  19735. }
  19736. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  19737. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  19738. indexStart: +Infinity,
  19739. indexEnd: -Infinity,
  19740. materialIndex: polygon.shared.materialIndex
  19741. };
  19742. }
  19743. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  19744. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  19745. polygonIndices[0] = 0;
  19746. polygonIndices[1] = j - 1;
  19747. polygonIndices[2] = j;
  19748. for (var k = 0; k < 3; k++) {
  19749. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  19750. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  19751. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  19752. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  19753. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  19754. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  19755. // Check if 2 points can be merged
  19756. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === localNormal.x && normals[vertex_idx * 3 + 1] === localNormal.y && normals[vertex_idx * 3 + 2] === localNormal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  19757. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  19758. uvs.push(uv.x, uv.y);
  19759. normals.push(normal.x, normal.y, normal.z);
  19760. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  19761. }
  19762. indices.push(vertex_idx);
  19763. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  19764. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  19765. currentIndex++;
  19766. }
  19767. }
  19768. }
  19769. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  19770. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19771. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  19772. mesh.setIndices(indices);
  19773. if (keepSubMeshes) {
  19774. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  19775. var materialIndexOffset = 0, materialMaxIndex;
  19776. mesh.subMeshes.length = 0;
  19777. for (var m in subMesh_dict) {
  19778. materialMaxIndex = -1;
  19779. for (var sm in subMesh_dict[m]) {
  19780. subMesh_obj = subMesh_dict[m][sm];
  19781. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  19782. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  19783. }
  19784. materialIndexOffset += ++materialMaxIndex;
  19785. }
  19786. }
  19787. return mesh;
  19788. };
  19789. // Build Mesh from CSG taking material and transforms into account
  19790. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  19791. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  19792. mesh.material = material;
  19793. mesh.position.copyFrom(this.position);
  19794. mesh.rotation.copyFrom(this.rotation);
  19795. mesh.scaling.copyFrom(this.scaling);
  19796. mesh.computeWorldMatrix(true);
  19797. return mesh;
  19798. };
  19799. return CSG;
  19800. })();
  19801. BABYLON.CSG = CSG;
  19802. })(BABYLON || (BABYLON = {}));
  19803. //# sourceMappingURL=babylon.csg.js.map
  19804. var BABYLON;
  19805. (function (BABYLON) {
  19806. var OculusDistortionCorrectionPostProcess = (function (_super) {
  19807. __extends(OculusDistortionCorrectionPostProcess, _super);
  19808. //ANY
  19809. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  19810. var _this = this;
  19811. _super.call(this, name, "oculusDistortionCorrection", [
  19812. 'LensCenter',
  19813. 'Scale',
  19814. 'ScaleIn',
  19815. 'HmdWarpParam'
  19816. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  19817. this._isRightEye = isRightEye;
  19818. this._distortionFactors = cameraSettings.DistortionK;
  19819. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  19820. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  19821. this.onSizeChanged = function () {
  19822. _this.aspectRatio = _this.width * .5 / _this.height;
  19823. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  19824. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  19825. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  19826. };
  19827. this.onApply = function (effect) {
  19828. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  19829. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  19830. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  19831. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  19832. };
  19833. }
  19834. return OculusDistortionCorrectionPostProcess;
  19835. })(BABYLON.PostProcess);
  19836. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  19837. })(BABYLON || (BABYLON = {}));
  19838. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  19839. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  19840. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  19841. var BABYLON;
  19842. (function (BABYLON) {
  19843. (function (JoystickAxis) {
  19844. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  19845. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  19846. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  19847. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  19848. var JoystickAxis = BABYLON.JoystickAxis;
  19849. var VirtualJoystick = (function () {
  19850. function VirtualJoystick(leftJoystick) {
  19851. var _this = this;
  19852. if (leftJoystick) {
  19853. this._leftJoystick = true;
  19854. }
  19855. else {
  19856. this._leftJoystick = false;
  19857. }
  19858. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  19859. VirtualJoystick._globalJoystickIndex++;
  19860. // By default left & right arrow keys are moving the X
  19861. // and up & down keys are moving the Y
  19862. this._axisTargetedByLeftAndRight = 0 /* X */;
  19863. this._axisTargetedByUpAndDown = 1 /* Y */;
  19864. this.reverseLeftRight = false;
  19865. this.reverseUpDown = false;
  19866. // collections of pointers
  19867. this._touches = new BABYLON.VirtualJoystick.Collection();
  19868. this.deltaPosition = BABYLON.Vector3.Zero();
  19869. this._joystickSensibility = 25;
  19870. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19871. this._rotationSpeed = 25;
  19872. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  19873. this._rotateOnAxisRelativeToMesh = false;
  19874. // injecting a canvas element on top of the canvas 3D game
  19875. if (!VirtualJoystick.vjCanvas) {
  19876. window.addEventListener("resize", function () {
  19877. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19878. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19879. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  19880. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  19881. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  19882. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  19883. }, false);
  19884. VirtualJoystick.vjCanvas = document.createElement("canvas");
  19885. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19886. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19887. VirtualJoystick.vjCanvas.width = window.innerWidth;
  19888. VirtualJoystick.vjCanvas.height = window.innerHeight;
  19889. VirtualJoystick.vjCanvas.style.width = "100%";
  19890. VirtualJoystick.vjCanvas.style.height = "100%";
  19891. VirtualJoystick.vjCanvas.style.position = "absolute";
  19892. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  19893. VirtualJoystick.vjCanvas.style.top = "0px";
  19894. VirtualJoystick.vjCanvas.style.left = "0px";
  19895. VirtualJoystick.vjCanvas.style.zIndex = "5";
  19896. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  19897. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  19898. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  19899. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19900. document.body.appendChild(VirtualJoystick.vjCanvas);
  19901. }
  19902. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  19903. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  19904. this.pressed = false;
  19905. // default joystick color
  19906. this._joystickColor = "cyan";
  19907. this._joystickPointerID = -1;
  19908. // current joystick position
  19909. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  19910. // origin joystick position
  19911. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  19912. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  19913. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  19914. _this._onPointerDown(evt);
  19915. }, false);
  19916. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  19917. _this._onPointerMove(evt);
  19918. }, false);
  19919. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  19920. _this._onPointerUp(evt);
  19921. }, false);
  19922. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  19923. _this._onPointerUp(evt);
  19924. }, false);
  19925. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  19926. evt.preventDefault(); // Disables system menu
  19927. }, false);
  19928. requestAnimationFrame(function () {
  19929. _this._drawVirtualJoystick();
  19930. });
  19931. }
  19932. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  19933. this._joystickSensibility = newJoystickSensibility;
  19934. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19935. };
  19936. VirtualJoystick.prototype._onPointerDown = function (e) {
  19937. var positionOnScreenCondition;
  19938. e.preventDefault();
  19939. if (this._leftJoystick === true) {
  19940. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  19941. }
  19942. else {
  19943. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  19944. }
  19945. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  19946. // First contact will be dedicated to the virtual joystick
  19947. this._joystickPointerID = e.pointerId;
  19948. this._joystickPointerStartPos.x = e.clientX;
  19949. this._joystickPointerStartPos.y = e.clientY;
  19950. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  19951. this._deltaJoystickVector.x = 0;
  19952. this._deltaJoystickVector.y = 0;
  19953. this.pressed = true;
  19954. this._touches.add(e.pointerId.toString(), e);
  19955. }
  19956. else {
  19957. // You can only trigger the action buttons with a joystick declared
  19958. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  19959. this._action();
  19960. this._touches.add(e.pointerId.toString(), e);
  19961. }
  19962. }
  19963. };
  19964. VirtualJoystick.prototype._onPointerMove = function (e) {
  19965. // If the current pointer is the one associated to the joystick (first touch contact)
  19966. if (this._joystickPointerID == e.pointerId) {
  19967. this._joystickPointerPos.x = e.clientX;
  19968. this._joystickPointerPos.y = e.clientY;
  19969. this._deltaJoystickVector = this._joystickPointerPos.clone();
  19970. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  19971. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  19972. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  19973. switch (this._axisTargetedByLeftAndRight) {
  19974. case 0 /* X */:
  19975. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  19976. break;
  19977. case 1 /* Y */:
  19978. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  19979. break;
  19980. case 2 /* Z */:
  19981. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  19982. break;
  19983. }
  19984. var directionUpDown = this.reverseUpDown ? 1 : -1;
  19985. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  19986. switch (this._axisTargetedByUpAndDown) {
  19987. case 0 /* X */:
  19988. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  19989. break;
  19990. case 1 /* Y */:
  19991. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  19992. break;
  19993. case 2 /* Z */:
  19994. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  19995. break;
  19996. }
  19997. }
  19998. else {
  19999. if (this._touches.item(e.pointerId.toString())) {
  20000. this._touches.item(e.pointerId.toString()).x = e.clientX;
  20001. this._touches.item(e.pointerId.toString()).y = e.clientY;
  20002. }
  20003. }
  20004. };
  20005. VirtualJoystick.prototype._onPointerUp = function (e) {
  20006. this._clearCanvas();
  20007. if (this._joystickPointerID == e.pointerId) {
  20008. this._joystickPointerID = -1;
  20009. this.pressed = false;
  20010. }
  20011. this._deltaJoystickVector.x = 0;
  20012. this._deltaJoystickVector.y = 0;
  20013. this._touches.remove(e.pointerId.toString());
  20014. };
  20015. /**
  20016. * Change the color of the virtual joystick
  20017. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  20018. */
  20019. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  20020. this._joystickColor = newColor;
  20021. };
  20022. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  20023. this._action = action;
  20024. };
  20025. // Define which axis you'd like to control for left & right
  20026. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  20027. switch (axis) {
  20028. case 0 /* X */:
  20029. case 1 /* Y */:
  20030. case 2 /* Z */:
  20031. this._axisTargetedByLeftAndRight = axis;
  20032. break;
  20033. default:
  20034. this._axisTargetedByLeftAndRight = 0 /* X */;
  20035. break;
  20036. }
  20037. };
  20038. // Define which axis you'd like to control for up & down
  20039. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  20040. switch (axis) {
  20041. case 0 /* X */:
  20042. case 1 /* Y */:
  20043. case 2 /* Z */:
  20044. this._axisTargetedByUpAndDown = axis;
  20045. break;
  20046. default:
  20047. this._axisTargetedByUpAndDown = 1 /* Y */;
  20048. break;
  20049. }
  20050. };
  20051. VirtualJoystick.prototype._clearCanvas = function () {
  20052. if (this._leftJoystick) {
  20053. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  20054. }
  20055. else {
  20056. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  20057. }
  20058. };
  20059. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  20060. var _this = this;
  20061. if (this.pressed) {
  20062. this._clearCanvas();
  20063. this._touches.forEach(function (touch) {
  20064. if (touch.pointerId === _this._joystickPointerID) {
  20065. VirtualJoystick.vjCanvasContext.beginPath();
  20066. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20067. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20068. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  20069. VirtualJoystick.vjCanvasContext.stroke();
  20070. VirtualJoystick.vjCanvasContext.beginPath();
  20071. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20072. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20073. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  20074. VirtualJoystick.vjCanvasContext.stroke();
  20075. VirtualJoystick.vjCanvasContext.beginPath();
  20076. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20077. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  20078. VirtualJoystick.vjCanvasContext.stroke();
  20079. }
  20080. else {
  20081. VirtualJoystick.vjCanvasContext.beginPath();
  20082. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  20083. VirtualJoystick.vjCanvasContext.beginPath();
  20084. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  20085. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20086. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  20087. VirtualJoystick.vjCanvasContext.stroke();
  20088. }
  20089. ;
  20090. });
  20091. }
  20092. requestAnimationFrame(function () {
  20093. _this._drawVirtualJoystick();
  20094. });
  20095. };
  20096. VirtualJoystick.prototype.releaseCanvas = function () {
  20097. if (VirtualJoystick.vjCanvas) {
  20098. document.body.removeChild(VirtualJoystick.vjCanvas);
  20099. VirtualJoystick.vjCanvas = null;
  20100. }
  20101. };
  20102. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  20103. VirtualJoystick._globalJoystickIndex = 0;
  20104. return VirtualJoystick;
  20105. })();
  20106. BABYLON.VirtualJoystick = VirtualJoystick;
  20107. })(BABYLON || (BABYLON = {}));
  20108. var BABYLON;
  20109. (function (BABYLON) {
  20110. var VirtualJoystick;
  20111. (function (VirtualJoystick) {
  20112. var Collection = (function () {
  20113. function Collection() {
  20114. this._count = 0;
  20115. this._collection = new Array();
  20116. }
  20117. Collection.prototype.Count = function () {
  20118. return this._count;
  20119. };
  20120. Collection.prototype.add = function (key, item) {
  20121. if (this._collection[key] != undefined) {
  20122. return undefined;
  20123. }
  20124. this._collection[key] = item;
  20125. return ++this._count;
  20126. };
  20127. Collection.prototype.remove = function (key) {
  20128. if (this._collection[key] == undefined) {
  20129. return undefined;
  20130. }
  20131. delete this._collection[key];
  20132. return --this._count;
  20133. };
  20134. Collection.prototype.item = function (key) {
  20135. return this._collection[key];
  20136. };
  20137. Collection.prototype.forEach = function (block) {
  20138. var key;
  20139. for (key in this._collection) {
  20140. if (this._collection.hasOwnProperty(key)) {
  20141. block(this._collection[key]);
  20142. }
  20143. }
  20144. };
  20145. return Collection;
  20146. })();
  20147. VirtualJoystick.Collection = Collection;
  20148. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20149. })(BABYLON || (BABYLON = {}));
  20150. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20151. var BABYLON;
  20152. (function (BABYLON) {
  20153. var OculusRiftDevKit2013_Metric = {
  20154. HResolution: 1280,
  20155. VResolution: 800,
  20156. HScreenSize: 0.149759993,
  20157. VScreenSize: 0.0935999975,
  20158. VScreenCenter: 0.0467999987,
  20159. EyeToScreenDistance: 0.0410000011,
  20160. LensSeparationDistance: 0.0635000020,
  20161. InterpupillaryDistance: 0.0640000030,
  20162. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20163. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20164. PostProcessScaleFactor: 1.714605507808412,
  20165. LensCenterOffset: 0.151976421
  20166. };
  20167. var _OculusInnerCamera = (function (_super) {
  20168. __extends(_OculusInnerCamera, _super);
  20169. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20170. _super.call(this, name, position, scene);
  20171. this._workMatrix = new BABYLON.Matrix();
  20172. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20173. // Constants
  20174. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20175. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20176. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20177. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20178. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20179. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20180. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20181. // Postprocess
  20182. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20183. }
  20184. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  20185. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20186. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20187. return this._projectionMatrix;
  20188. };
  20189. _OculusInnerCamera.prototype._getViewMatrix = function () {
  20190. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20191. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20192. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20193. // Computing target and final matrix
  20194. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20195. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20196. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20197. return this._viewMatrix;
  20198. };
  20199. return _OculusInnerCamera;
  20200. })(BABYLON.FreeCamera);
  20201. var OculusCamera = (function (_super) {
  20202. __extends(OculusCamera, _super);
  20203. function OculusCamera(name, position, scene) {
  20204. _super.call(this, name, position, scene);
  20205. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  20206. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  20207. this.subCameras.push(this._leftCamera);
  20208. this.subCameras.push(this._rightCamera);
  20209. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20210. }
  20211. OculusCamera.prototype._update = function () {
  20212. this._leftCamera.position.copyFrom(this.position);
  20213. this._rightCamera.position.copyFrom(this.position);
  20214. this._updateCamera(this._leftCamera);
  20215. this._updateCamera(this._rightCamera);
  20216. _super.prototype._update.call(this);
  20217. };
  20218. OculusCamera.prototype._updateCamera = function (camera) {
  20219. camera.minZ = this.minZ;
  20220. camera.maxZ = this.maxZ;
  20221. camera.rotation.x = this.rotation.x;
  20222. camera.rotation.y = this.rotation.y;
  20223. camera.rotation.z = this.rotation.z;
  20224. };
  20225. // Oculus events
  20226. OculusCamera.prototype._onOrientationEvent = function (evt) {
  20227. var yaw = evt.alpha / 180 * Math.PI;
  20228. var pitch = evt.beta / 180 * Math.PI;
  20229. var roll = evt.gamma / 180 * Math.PI;
  20230. if (!this._offsetOrientation) {
  20231. this._offsetOrientation = {
  20232. yaw: yaw,
  20233. pitch: pitch,
  20234. roll: roll
  20235. };
  20236. return;
  20237. }
  20238. else {
  20239. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20240. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20241. this.rotation.z += this._offsetOrientation.roll - roll;
  20242. this._offsetOrientation.yaw = yaw;
  20243. this._offsetOrientation.pitch = pitch;
  20244. this._offsetOrientation.roll = roll;
  20245. }
  20246. };
  20247. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  20248. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20249. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20250. };
  20251. OculusCamera.prototype.detachControl = function (element) {
  20252. _super.prototype.detachControl.call(this, element);
  20253. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20254. };
  20255. return OculusCamera;
  20256. })(BABYLON.FreeCamera);
  20257. BABYLON.OculusCamera = OculusCamera;
  20258. })(BABYLON || (BABYLON = {}));
  20259. //# sourceMappingURL=babylon.oculusCamera.js.map
  20260. var BABYLON;
  20261. (function (BABYLON) {
  20262. var OculusRiftDevKit2013_Metric = {
  20263. HResolution: 1280,
  20264. VResolution: 800,
  20265. HScreenSize: 0.149759993,
  20266. VScreenSize: 0.0935999975,
  20267. VScreenCenter: 0.0467999987,
  20268. EyeToScreenDistance: 0.0410000011,
  20269. LensSeparationDistance: 0.0635000020,
  20270. InterpupillaryDistance: 0.0640000030,
  20271. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20272. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20273. PostProcessScaleFactor: 1.714605507808412,
  20274. LensCenterOffset: 0.151976421
  20275. };
  20276. var _OculusInnerGamepadCamera = (function (_super) {
  20277. __extends(_OculusInnerGamepadCamera, _super);
  20278. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  20279. _super.call(this, name, position, scene);
  20280. this._workMatrix = new BABYLON.Matrix();
  20281. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20282. // Constants
  20283. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20284. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20285. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20286. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20287. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20288. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20289. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20290. // Postprocess
  20291. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20292. }
  20293. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  20294. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20295. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20296. return this._projectionMatrix;
  20297. };
  20298. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  20299. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20300. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20301. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20302. // Computing target and final matrix
  20303. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20304. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20305. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20306. return this._viewMatrix;
  20307. };
  20308. return _OculusInnerGamepadCamera;
  20309. })(BABYLON.FreeCamera);
  20310. var OculusGamepadCamera = (function (_super) {
  20311. __extends(OculusGamepadCamera, _super);
  20312. function OculusGamepadCamera(name, position, scene) {
  20313. var _this = this;
  20314. _super.call(this, name, position, scene);
  20315. this.angularSensibility = 200;
  20316. this.moveSensibility = 75;
  20317. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  20318. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  20319. this.subCameras.push(this._leftCamera);
  20320. this.subCameras.push(this._rightCamera);
  20321. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20322. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20323. _this._onNewGameConnected(gamepad);
  20324. });
  20325. }
  20326. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20327. // Only the first gamepad can control the camera
  20328. if (gamepad.index === 0) {
  20329. this._gamepad = gamepad;
  20330. }
  20331. };
  20332. OculusGamepadCamera.prototype._update = function () {
  20333. this._leftCamera.position.copyFrom(this.position);
  20334. this._rightCamera.position.copyFrom(this.position);
  20335. this._updateCamera(this._leftCamera);
  20336. this._updateCamera(this._rightCamera);
  20337. _super.prototype._update.call(this);
  20338. };
  20339. OculusGamepadCamera.prototype._checkInputs = function () {
  20340. if (!this._gamepad) {
  20341. return;
  20342. }
  20343. var LSValues = this._gamepad.leftStick;
  20344. var normalizedLX = LSValues.x / this.moveSensibility;
  20345. var normalizedLY = LSValues.y / this.moveSensibility;
  20346. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20347. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20348. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20349. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20350. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20351. };
  20352. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  20353. camera.minZ = this.minZ;
  20354. camera.maxZ = this.maxZ;
  20355. camera.rotation.x = this.rotation.x;
  20356. camera.rotation.y = this.rotation.y;
  20357. camera.rotation.z = this.rotation.z;
  20358. };
  20359. // Oculus events
  20360. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  20361. var yaw = evt.alpha / 180 * Math.PI;
  20362. var pitch = evt.beta / 180 * Math.PI;
  20363. var roll = evt.gamma / 180 * Math.PI;
  20364. if (!this._offsetOrientation) {
  20365. this._offsetOrientation = {
  20366. yaw: yaw,
  20367. pitch: pitch,
  20368. roll: roll
  20369. };
  20370. return;
  20371. }
  20372. else {
  20373. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20374. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20375. this.rotation.z += this._offsetOrientation.roll - roll;
  20376. this._offsetOrientation.yaw = yaw;
  20377. this._offsetOrientation.pitch = pitch;
  20378. this._offsetOrientation.roll = roll;
  20379. }
  20380. };
  20381. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  20382. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20383. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20384. };
  20385. OculusGamepadCamera.prototype.detachControl = function (element) {
  20386. _super.prototype.detachControl.call(this, element);
  20387. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20388. };
  20389. OculusGamepadCamera.prototype.dispose = function () {
  20390. this._gamepads.dispose();
  20391. _super.prototype.dispose.call(this);
  20392. };
  20393. return OculusGamepadCamera;
  20394. })(BABYLON.FreeCamera);
  20395. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  20396. })(BABYLON || (BABYLON = {}));
  20397. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  20398. var BABYLON;
  20399. (function (BABYLON) {
  20400. // We're mainly based on the logic defined into the FreeCamera code
  20401. var VirtualJoysticksCamera = (function (_super) {
  20402. __extends(VirtualJoysticksCamera, _super);
  20403. function VirtualJoysticksCamera(name, position, scene) {
  20404. _super.call(this, name, position, scene);
  20405. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  20406. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  20407. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  20408. this._leftjoystick.setJoystickSensibility(0.15);
  20409. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  20410. this._rightjoystick.setAxisForUpDown(0 /* X */);
  20411. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  20412. this._rightjoystick.reverseUpDown = true;
  20413. this._rightjoystick.setJoystickSensibility(0.05);
  20414. this._rightjoystick.setJoystickColor("yellow");
  20415. }
  20416. VirtualJoysticksCamera.prototype._checkInputs = function () {
  20417. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20418. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  20419. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20420. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  20421. if (!this._leftjoystick.pressed) {
  20422. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  20423. }
  20424. if (!this._rightjoystick.pressed) {
  20425. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  20426. }
  20427. };
  20428. VirtualJoysticksCamera.prototype.dispose = function () {
  20429. this._leftjoystick.releaseCanvas();
  20430. _super.prototype.dispose.call(this);
  20431. };
  20432. return VirtualJoysticksCamera;
  20433. })(BABYLON.FreeCamera);
  20434. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  20435. })(BABYLON || (BABYLON = {}));
  20436. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  20437. var BABYLON;
  20438. (function (BABYLON) {
  20439. var ShaderMaterial = (function (_super) {
  20440. __extends(ShaderMaterial, _super);
  20441. function ShaderMaterial(name, scene, shaderPath, options) {
  20442. _super.call(this, name, scene);
  20443. this._textures = new Array();
  20444. this._floats = new Array();
  20445. this._floatsArrays = {};
  20446. this._colors3 = new Array();
  20447. this._colors4 = new Array();
  20448. this._vectors2 = new Array();
  20449. this._vectors3 = new Array();
  20450. this._matrices = new Array();
  20451. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  20452. this._shaderPath = shaderPath;
  20453. options.needAlphaBlending = options.needAlphaBlending || false;
  20454. options.needAlphaTesting = options.needAlphaTesting || false;
  20455. options.attributes = options.attributes || ["position", "normal", "uv"];
  20456. options.uniforms = options.uniforms || ["worldViewProjection"];
  20457. options.samplers = options.samplers || [];
  20458. this._options = options;
  20459. }
  20460. ShaderMaterial.prototype.needAlphaBlending = function () {
  20461. return this._options.needAlphaBlending;
  20462. };
  20463. ShaderMaterial.prototype.needAlphaTesting = function () {
  20464. return this._options.needAlphaTesting;
  20465. };
  20466. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  20467. if (this._options.uniforms.indexOf(uniformName) === -1) {
  20468. this._options.uniforms.push(uniformName);
  20469. }
  20470. };
  20471. ShaderMaterial.prototype.setTexture = function (name, texture) {
  20472. if (this._options.samplers.indexOf(name) === -1) {
  20473. this._options.samplers.push(name);
  20474. }
  20475. this._textures[name] = texture;
  20476. return this;
  20477. };
  20478. ShaderMaterial.prototype.setFloat = function (name, value) {
  20479. this._checkUniform(name);
  20480. this._floats[name] = value;
  20481. return this;
  20482. };
  20483. ShaderMaterial.prototype.setFloats = function (name, value) {
  20484. this._checkUniform(name);
  20485. this._floatsArrays[name] = value;
  20486. return this;
  20487. };
  20488. ShaderMaterial.prototype.setColor3 = function (name, value) {
  20489. this._checkUniform(name);
  20490. this._colors3[name] = value;
  20491. return this;
  20492. };
  20493. ShaderMaterial.prototype.setColor4 = function (name, value) {
  20494. this._checkUniform(name);
  20495. this._colors4[name] = value;
  20496. return this;
  20497. };
  20498. ShaderMaterial.prototype.setVector2 = function (name, value) {
  20499. this._checkUniform(name);
  20500. this._vectors2[name] = value;
  20501. return this;
  20502. };
  20503. ShaderMaterial.prototype.setVector3 = function (name, value) {
  20504. this._checkUniform(name);
  20505. this._vectors3[name] = value;
  20506. return this;
  20507. };
  20508. ShaderMaterial.prototype.setMatrix = function (name, value) {
  20509. this._checkUniform(name);
  20510. this._matrices[name] = value;
  20511. return this;
  20512. };
  20513. ShaderMaterial.prototype.isReady = function () {
  20514. var scene = this.getScene();
  20515. var engine = scene.getEngine();
  20516. if (!this.checkReadyOnEveryCall) {
  20517. if (this._renderId === scene.getRenderId()) {
  20518. return true;
  20519. }
  20520. }
  20521. var previousEffect = this._effect;
  20522. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  20523. if (!this._effect.isReady()) {
  20524. return false;
  20525. }
  20526. if (previousEffect !== this._effect) {
  20527. scene.resetCachedMaterial();
  20528. }
  20529. this._renderId = scene.getRenderId();
  20530. return true;
  20531. };
  20532. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20533. var scene = this.getScene();
  20534. if (this._options.uniforms.indexOf("world") !== -1) {
  20535. this._effect.setMatrix("world", world);
  20536. }
  20537. if (this._options.uniforms.indexOf("worldView") !== -1) {
  20538. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  20539. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  20540. }
  20541. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  20542. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  20543. }
  20544. };
  20545. ShaderMaterial.prototype.bind = function (world) {
  20546. // Std values
  20547. this.bindOnlyWorldMatrix(world);
  20548. if (this.getScene().getCachedMaterial() !== this) {
  20549. if (this._options.uniforms.indexOf("view") !== -1) {
  20550. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  20551. }
  20552. if (this._options.uniforms.indexOf("projection") !== -1) {
  20553. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  20554. }
  20555. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  20556. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  20557. }
  20558. for (var name in this._textures) {
  20559. this._effect.setTexture(name, this._textures[name]);
  20560. }
  20561. for (name in this._floats) {
  20562. this._effect.setFloat(name, this._floats[name]);
  20563. }
  20564. for (name in this._floatsArrays) {
  20565. this._effect.setArray(name, this._floatsArrays[name]);
  20566. }
  20567. for (name in this._colors3) {
  20568. this._effect.setColor3(name, this._colors3[name]);
  20569. }
  20570. for (name in this._colors4) {
  20571. var color = this._colors4[name];
  20572. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  20573. }
  20574. for (name in this._vectors2) {
  20575. this._effect.setVector2(name, this._vectors2[name]);
  20576. }
  20577. for (name in this._vectors3) {
  20578. this._effect.setVector3(name, this._vectors3[name]);
  20579. }
  20580. for (name in this._matrices) {
  20581. this._effect.setMatrix(name, this._matrices[name]);
  20582. }
  20583. }
  20584. _super.prototype.bind.call(this, world, null);
  20585. };
  20586. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  20587. for (var name in this._textures) {
  20588. this._textures[name].dispose();
  20589. }
  20590. this._textures = [];
  20591. _super.prototype.dispose.call(this, forceDisposeEffect);
  20592. };
  20593. return ShaderMaterial;
  20594. })(BABYLON.Material);
  20595. BABYLON.ShaderMaterial = ShaderMaterial;
  20596. })(BABYLON || (BABYLON = {}));
  20597. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  20598. (function (BABYLON) {
  20599. var VertexData = (function () {
  20600. function VertexData() {
  20601. }
  20602. VertexData.prototype.set = function (data, kind) {
  20603. switch (kind) {
  20604. case BABYLON.VertexBuffer.PositionKind:
  20605. this.positions = data;
  20606. break;
  20607. case BABYLON.VertexBuffer.NormalKind:
  20608. this.normals = data;
  20609. break;
  20610. case BABYLON.VertexBuffer.UVKind:
  20611. this.uvs = data;
  20612. break;
  20613. case BABYLON.VertexBuffer.UV2Kind:
  20614. this.uv2s = data;
  20615. break;
  20616. case BABYLON.VertexBuffer.ColorKind:
  20617. this.colors = data;
  20618. break;
  20619. case BABYLON.VertexBuffer.MatricesIndicesKind:
  20620. this.matricesIndices = data;
  20621. break;
  20622. case BABYLON.VertexBuffer.MatricesWeightsKind:
  20623. this.matricesWeights = data;
  20624. break;
  20625. }
  20626. };
  20627. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  20628. this._applyTo(mesh, updatable);
  20629. };
  20630. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  20631. this._applyTo(geometry, updatable);
  20632. };
  20633. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  20634. this._update(mesh);
  20635. };
  20636. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  20637. this._update(geometry);
  20638. };
  20639. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  20640. if (this.positions) {
  20641. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  20642. }
  20643. if (this.normals) {
  20644. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  20645. }
  20646. if (this.uvs) {
  20647. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  20648. }
  20649. if (this.uv2s) {
  20650. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  20651. }
  20652. if (this.colors) {
  20653. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  20654. }
  20655. if (this.matricesIndices) {
  20656. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  20657. }
  20658. if (this.matricesWeights) {
  20659. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  20660. }
  20661. if (this.indices) {
  20662. meshOrGeometry.setIndices(this.indices);
  20663. }
  20664. };
  20665. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  20666. if (this.positions) {
  20667. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  20668. }
  20669. if (this.normals) {
  20670. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  20671. }
  20672. if (this.uvs) {
  20673. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  20674. }
  20675. if (this.uv2s) {
  20676. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  20677. }
  20678. if (this.colors) {
  20679. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  20680. }
  20681. if (this.matricesIndices) {
  20682. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  20683. }
  20684. if (this.matricesWeights) {
  20685. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  20686. }
  20687. if (this.indices) {
  20688. meshOrGeometry.setIndices(this.indices);
  20689. }
  20690. };
  20691. VertexData.prototype.transform = function (matrix) {
  20692. var transformed = BABYLON.Vector3.Zero();
  20693. if (this.positions) {
  20694. var position = BABYLON.Vector3.Zero();
  20695. for (var index = 0; index < this.positions.length; index += 3) {
  20696. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  20697. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  20698. this.positions[index] = transformed.x;
  20699. this.positions[index + 1] = transformed.y;
  20700. this.positions[index + 2] = transformed.z;
  20701. }
  20702. }
  20703. if (this.normals) {
  20704. var normal = BABYLON.Vector3.Zero();
  20705. for (index = 0; index < this.normals.length; index += 3) {
  20706. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  20707. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  20708. this.normals[index] = transformed.x;
  20709. this.normals[index + 1] = transformed.y;
  20710. this.normals[index + 2] = transformed.z;
  20711. }
  20712. }
  20713. };
  20714. VertexData.prototype.merge = function (other) {
  20715. if (other.indices) {
  20716. if (!this.indices) {
  20717. this.indices = [];
  20718. }
  20719. var offset = this.positions ? this.positions.length / 3 : 0;
  20720. for (var index = 0; index < other.indices.length; index++) {
  20721. this.indices.push(other.indices[index] + offset);
  20722. }
  20723. }
  20724. if (other.positions) {
  20725. if (!this.positions) {
  20726. this.positions = [];
  20727. }
  20728. for (index = 0; index < other.positions.length; index++) {
  20729. this.positions.push(other.positions[index]);
  20730. }
  20731. }
  20732. if (other.normals) {
  20733. if (!this.normals) {
  20734. this.normals = [];
  20735. }
  20736. for (index = 0; index < other.normals.length; index++) {
  20737. this.normals.push(other.normals[index]);
  20738. }
  20739. }
  20740. if (other.uvs) {
  20741. if (!this.uvs) {
  20742. this.uvs = [];
  20743. }
  20744. for (index = 0; index < other.uvs.length; index++) {
  20745. this.uvs.push(other.uvs[index]);
  20746. }
  20747. }
  20748. if (other.uv2s) {
  20749. if (!this.uv2s) {
  20750. this.uv2s = [];
  20751. }
  20752. for (index = 0; index < other.uv2s.length; index++) {
  20753. this.uv2s.push(other.uv2s[index]);
  20754. }
  20755. }
  20756. if (other.matricesIndices) {
  20757. if (!this.matricesIndices) {
  20758. this.matricesIndices = [];
  20759. }
  20760. for (index = 0; index < other.matricesIndices.length; index++) {
  20761. this.matricesIndices.push(other.matricesIndices[index]);
  20762. }
  20763. }
  20764. if (other.matricesWeights) {
  20765. if (!this.matricesWeights) {
  20766. this.matricesWeights = [];
  20767. }
  20768. for (index = 0; index < other.matricesWeights.length; index++) {
  20769. this.matricesWeights.push(other.matricesWeights[index]);
  20770. }
  20771. }
  20772. if (other.colors) {
  20773. if (!this.colors) {
  20774. this.colors = [];
  20775. }
  20776. for (index = 0; index < other.colors.length; index++) {
  20777. this.colors.push(other.colors[index]);
  20778. }
  20779. }
  20780. };
  20781. // Statics
  20782. VertexData.ExtractFromMesh = function (mesh) {
  20783. return VertexData._ExtractFrom(mesh);
  20784. };
  20785. VertexData.ExtractFromGeometry = function (geometry) {
  20786. return VertexData._ExtractFrom(geometry);
  20787. };
  20788. VertexData._ExtractFrom = function (meshOrGeometry) {
  20789. var result = new BABYLON.VertexData();
  20790. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20791. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20792. }
  20793. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20794. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20795. }
  20796. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20797. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20798. }
  20799. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20800. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  20801. }
  20802. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20803. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  20804. }
  20805. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20806. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20807. }
  20808. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20809. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20810. }
  20811. result.indices = meshOrGeometry.getIndices();
  20812. return result;
  20813. };
  20814. VertexData.CreateBox = function (size) {
  20815. var normalsSource = [
  20816. new BABYLON.Vector3(0, 0, 1),
  20817. new BABYLON.Vector3(0, 0, -1),
  20818. new BABYLON.Vector3(1, 0, 0),
  20819. new BABYLON.Vector3(-1, 0, 0),
  20820. new BABYLON.Vector3(0, 1, 0),
  20821. new BABYLON.Vector3(0, -1, 0)
  20822. ];
  20823. var indices = [];
  20824. var positions = [];
  20825. var normals = [];
  20826. var uvs = [];
  20827. size = size || 1;
  20828. for (var index = 0; index < normalsSource.length; index++) {
  20829. var normal = normalsSource[index];
  20830. // Get two vectors perpendicular to the face normal and to each other.
  20831. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  20832. var side2 = BABYLON.Vector3.Cross(normal, side1);
  20833. // Six indices (two triangles) per face.
  20834. var verticesLength = positions.length / 3;
  20835. indices.push(verticesLength);
  20836. indices.push(verticesLength + 1);
  20837. indices.push(verticesLength + 2);
  20838. indices.push(verticesLength);
  20839. indices.push(verticesLength + 2);
  20840. indices.push(verticesLength + 3);
  20841. // Four vertices per face.
  20842. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  20843. positions.push(vertex.x, vertex.y, vertex.z);
  20844. normals.push(normal.x, normal.y, normal.z);
  20845. uvs.push(1.0, 1.0);
  20846. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  20847. positions.push(vertex.x, vertex.y, vertex.z);
  20848. normals.push(normal.x, normal.y, normal.z);
  20849. uvs.push(0.0, 1.0);
  20850. vertex = normal.add(side1).add(side2).scale(size / 2);
  20851. positions.push(vertex.x, vertex.y, vertex.z);
  20852. normals.push(normal.x, normal.y, normal.z);
  20853. uvs.push(0.0, 0.0);
  20854. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  20855. positions.push(vertex.x, vertex.y, vertex.z);
  20856. normals.push(normal.x, normal.y, normal.z);
  20857. uvs.push(1.0, 0.0);
  20858. }
  20859. // Result
  20860. var vertexData = new BABYLON.VertexData();
  20861. vertexData.indices = indices;
  20862. vertexData.positions = positions;
  20863. vertexData.normals = normals;
  20864. vertexData.uvs = uvs;
  20865. return vertexData;
  20866. };
  20867. VertexData.CreateSphere = function (segments, diameter) {
  20868. segments = segments || 32;
  20869. diameter = diameter || 1;
  20870. var radius = diameter / 2;
  20871. var totalZRotationSteps = 2 + segments;
  20872. var totalYRotationSteps = 2 * totalZRotationSteps;
  20873. var indices = [];
  20874. var positions = [];
  20875. var normals = [];
  20876. var uvs = [];
  20877. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  20878. var normalizedZ = zRotationStep / totalZRotationSteps;
  20879. var angleZ = (normalizedZ * Math.PI);
  20880. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  20881. var normalizedY = yRotationStep / totalYRotationSteps;
  20882. var angleY = normalizedY * Math.PI * 2;
  20883. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  20884. var rotationY = BABYLON.Matrix.RotationY(angleY);
  20885. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  20886. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  20887. var vertex = complete.scale(radius);
  20888. var normal = BABYLON.Vector3.Normalize(vertex);
  20889. positions.push(vertex.x, vertex.y, vertex.z);
  20890. normals.push(normal.x, normal.y, normal.z);
  20891. uvs.push(normalizedZ, normalizedY);
  20892. }
  20893. if (zRotationStep > 0) {
  20894. var verticesCount = positions.length / 3;
  20895. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  20896. indices.push((firstIndex));
  20897. indices.push((firstIndex + 1));
  20898. indices.push(firstIndex + totalYRotationSteps + 1);
  20899. indices.push((firstIndex + totalYRotationSteps + 1));
  20900. indices.push((firstIndex + 1));
  20901. indices.push((firstIndex + totalYRotationSteps + 2));
  20902. }
  20903. }
  20904. }
  20905. // Result
  20906. var vertexData = new BABYLON.VertexData();
  20907. vertexData.indices = indices;
  20908. vertexData.positions = positions;
  20909. vertexData.normals = normals;
  20910. vertexData.uvs = uvs;
  20911. return vertexData;
  20912. };
  20913. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  20914. if (subdivisions === void 0) { subdivisions = 1; }
  20915. var radiusTop = diameterTop / 2;
  20916. var radiusBottom = diameterBottom / 2;
  20917. var indices = [];
  20918. var positions = [];
  20919. var normals = [];
  20920. var uvs = [];
  20921. height = height || 1;
  20922. diameterTop = diameterTop || 0.5;
  20923. diameterBottom = diameterBottom || 1;
  20924. tessellation = tessellation || 16;
  20925. subdivisions = subdivisions || 1;
  20926. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  20927. var getCircleVector = function (i) {
  20928. var angle = (i * 2.0 * Math.PI / tessellation);
  20929. var dx = Math.cos(angle);
  20930. var dz = Math.sin(angle);
  20931. return new BABYLON.Vector3(dx, 0, dz);
  20932. };
  20933. var createCylinderCap = function (isTop) {
  20934. var radius = isTop ? radiusTop : radiusBottom;
  20935. if (radius == 0) {
  20936. return;
  20937. }
  20938. var vbase = positions.length / 3;
  20939. var offset = new BABYLON.Vector3(0, height / 2, 0);
  20940. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  20941. if (!isTop) {
  20942. offset.scaleInPlace(-1);
  20943. textureScale.x = -textureScale.x;
  20944. }
  20945. for (i = 0; i < tessellation; i++) {
  20946. var circleVector = getCircleVector(i);
  20947. var position = circleVector.scale(radius).add(offset);
  20948. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  20949. positions.push(position.x, position.y, position.z);
  20950. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20951. }
  20952. for (var i = 0; i < tessellation - 2; i++) {
  20953. if (!isTop) {
  20954. indices.push(vbase);
  20955. indices.push(vbase + (i + 2) % tessellation);
  20956. indices.push(vbase + (i + 1) % tessellation);
  20957. }
  20958. else {
  20959. indices.push(vbase);
  20960. indices.push(vbase + (i + 1) % tessellation);
  20961. indices.push(vbase + (i + 2) % tessellation);
  20962. }
  20963. }
  20964. };
  20965. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  20966. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  20967. var stride = tessellation + 1;
  20968. for (var i = 0; i <= tessellation; i++) {
  20969. var circleVector = getCircleVector(i);
  20970. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  20971. var position, radius = radiusBottom;
  20972. for (var s = 0; s <= subdivisions; s++) {
  20973. // Update variables
  20974. position = circleVector.scale(radius);
  20975. position.addInPlace(base.add(offset.scale(s)));
  20976. textureCoordinate.y += 1 / subdivisions;
  20977. radius += (radiusTop - radiusBottom) / subdivisions;
  20978. // Push in arrays
  20979. positions.push(position.x, position.y, position.z);
  20980. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20981. }
  20982. }
  20983. subdivisions += 1;
  20984. for (var s = 0; s < subdivisions - 1; s++) {
  20985. for (var i = 0; i <= tessellation; i++) {
  20986. indices.push(i * subdivisions + s);
  20987. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20988. indices.push(i * subdivisions + (s + 1));
  20989. indices.push(i * subdivisions + (s + 1));
  20990. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20991. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  20992. }
  20993. }
  20994. // Create flat triangle fan caps to seal the top and bottom.
  20995. createCylinderCap(true);
  20996. createCylinderCap(false);
  20997. // Normals
  20998. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20999. // Result
  21000. var vertexData = new BABYLON.VertexData();
  21001. vertexData.indices = indices;
  21002. vertexData.positions = positions;
  21003. vertexData.normals = normals;
  21004. vertexData.uvs = uvs;
  21005. return vertexData;
  21006. };
  21007. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  21008. var indices = [];
  21009. var positions = [];
  21010. var normals = [];
  21011. var uvs = [];
  21012. diameter = diameter || 1;
  21013. thickness = thickness || 0.5;
  21014. tessellation = tessellation || 16;
  21015. var stride = tessellation + 1;
  21016. for (var i = 0; i <= tessellation; i++) {
  21017. var u = i / tessellation;
  21018. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  21019. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  21020. for (var j = 0; j <= tessellation; j++) {
  21021. var v = 1 - j / tessellation;
  21022. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  21023. var dx = Math.cos(innerAngle);
  21024. var dy = Math.sin(innerAngle);
  21025. // Create a vertex.
  21026. var normal = new BABYLON.Vector3(dx, dy, 0);
  21027. var position = normal.scale(thickness / 2);
  21028. var textureCoordinate = new BABYLON.Vector2(u, v);
  21029. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  21030. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  21031. positions.push(position.x, position.y, position.z);
  21032. normals.push(normal.x, normal.y, normal.z);
  21033. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21034. // And create indices for two triangles.
  21035. var nextI = (i + 1) % stride;
  21036. var nextJ = (j + 1) % stride;
  21037. indices.push(i * stride + j);
  21038. indices.push(i * stride + nextJ);
  21039. indices.push(nextI * stride + j);
  21040. indices.push(i * stride + nextJ);
  21041. indices.push(nextI * stride + nextJ);
  21042. indices.push(nextI * stride + j);
  21043. }
  21044. }
  21045. // Result
  21046. var vertexData = new BABYLON.VertexData();
  21047. vertexData.indices = indices;
  21048. vertexData.positions = positions;
  21049. vertexData.normals = normals;
  21050. vertexData.uvs = uvs;
  21051. return vertexData;
  21052. };
  21053. VertexData.CreateLines = function (points) {
  21054. var indices = [];
  21055. var positions = [];
  21056. for (var index = 0; index < points.length; index++) {
  21057. positions.push(points[index].x, points[index].y, points[index].z);
  21058. if (index > 0) {
  21059. indices.push(index - 1);
  21060. indices.push(index);
  21061. }
  21062. }
  21063. // Result
  21064. var vertexData = new BABYLON.VertexData();
  21065. vertexData.indices = indices;
  21066. vertexData.positions = positions;
  21067. return vertexData;
  21068. };
  21069. VertexData.CreateGround = function (width, height, subdivisions) {
  21070. var indices = [];
  21071. var positions = [];
  21072. var normals = [];
  21073. var uvs = [];
  21074. var row, col;
  21075. width = width || 1;
  21076. height = height || 1;
  21077. subdivisions = subdivisions || 1;
  21078. for (row = 0; row <= subdivisions; row++) {
  21079. for (col = 0; col <= subdivisions; col++) {
  21080. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21081. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21082. positions.push(position.x, position.y, position.z);
  21083. normals.push(normal.x, normal.y, normal.z);
  21084. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21085. }
  21086. }
  21087. for (row = 0; row < subdivisions; row++) {
  21088. for (col = 0; col < subdivisions; col++) {
  21089. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21090. indices.push(col + 1 + row * (subdivisions + 1));
  21091. indices.push(col + row * (subdivisions + 1));
  21092. indices.push(col + (row + 1) * (subdivisions + 1));
  21093. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21094. indices.push(col + row * (subdivisions + 1));
  21095. }
  21096. }
  21097. // Result
  21098. var vertexData = new BABYLON.VertexData();
  21099. vertexData.indices = indices;
  21100. vertexData.positions = positions;
  21101. vertexData.normals = normals;
  21102. vertexData.uvs = uvs;
  21103. return vertexData;
  21104. };
  21105. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  21106. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  21107. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  21108. var indices = [];
  21109. var positions = [];
  21110. var normals = [];
  21111. var uvs = [];
  21112. var row, col, tileRow, tileCol;
  21113. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  21114. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  21115. precision.w = (precision.w < 1) ? 1 : precision.w;
  21116. precision.h = (precision.h < 1) ? 1 : precision.h;
  21117. var tileSize = {
  21118. 'w': (xmax - xmin) / subdivisions.w,
  21119. 'h': (zmax - zmin) / subdivisions.h
  21120. };
  21121. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  21122. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  21123. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  21124. }
  21125. }
  21126. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  21127. // Indices
  21128. var base = positions.length / 3;
  21129. var rowLength = precision.w + 1;
  21130. for (row = 0; row < precision.h; row++) {
  21131. for (col = 0; col < precision.w; col++) {
  21132. var square = [
  21133. base + col + row * rowLength,
  21134. base + (col + 1) + row * rowLength,
  21135. base + (col + 1) + (row + 1) * rowLength,
  21136. base + col + (row + 1) * rowLength
  21137. ];
  21138. indices.push(square[1]);
  21139. indices.push(square[2]);
  21140. indices.push(square[3]);
  21141. indices.push(square[0]);
  21142. indices.push(square[1]);
  21143. indices.push(square[3]);
  21144. }
  21145. }
  21146. // Position, normals and uvs
  21147. var position = BABYLON.Vector3.Zero();
  21148. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21149. for (row = 0; row <= precision.h; row++) {
  21150. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  21151. for (col = 0; col <= precision.w; col++) {
  21152. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  21153. position.y = 0;
  21154. positions.push(position.x, position.y, position.z);
  21155. normals.push(normal.x, normal.y, normal.z);
  21156. uvs.push(col / precision.w, row / precision.h);
  21157. }
  21158. }
  21159. }
  21160. // Result
  21161. var vertexData = new BABYLON.VertexData();
  21162. vertexData.indices = indices;
  21163. vertexData.positions = positions;
  21164. vertexData.normals = normals;
  21165. vertexData.uvs = uvs;
  21166. return vertexData;
  21167. };
  21168. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  21169. var indices = [];
  21170. var positions = [];
  21171. var normals = [];
  21172. var uvs = [];
  21173. var row, col;
  21174. for (row = 0; row <= subdivisions; row++) {
  21175. for (col = 0; col <= subdivisions; col++) {
  21176. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21177. // Compute height
  21178. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  21179. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  21180. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  21181. var r = buffer[pos] / 255.0;
  21182. var g = buffer[pos + 1] / 255.0;
  21183. var b = buffer[pos + 2] / 255.0;
  21184. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21185. position.y = minHeight + (maxHeight - minHeight) * gradient;
  21186. // Add vertex
  21187. positions.push(position.x, position.y, position.z);
  21188. normals.push(0, 0, 0);
  21189. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21190. }
  21191. }
  21192. for (row = 0; row < subdivisions; row++) {
  21193. for (col = 0; col < subdivisions; col++) {
  21194. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21195. indices.push(col + 1 + row * (subdivisions + 1));
  21196. indices.push(col + row * (subdivisions + 1));
  21197. indices.push(col + (row + 1) * (subdivisions + 1));
  21198. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21199. indices.push(col + row * (subdivisions + 1));
  21200. }
  21201. }
  21202. // Normals
  21203. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21204. // Result
  21205. var vertexData = new BABYLON.VertexData();
  21206. vertexData.indices = indices;
  21207. vertexData.positions = positions;
  21208. vertexData.normals = normals;
  21209. vertexData.uvs = uvs;
  21210. return vertexData;
  21211. };
  21212. VertexData.CreatePlane = function (size) {
  21213. var indices = [];
  21214. var positions = [];
  21215. var normals = [];
  21216. var uvs = [];
  21217. size = size || 1;
  21218. // Vertices
  21219. var halfSize = size / 2.0;
  21220. positions.push(-halfSize, -halfSize, 0);
  21221. normals.push(0, 0, -1.0);
  21222. uvs.push(0.0, 0.0);
  21223. positions.push(halfSize, -halfSize, 0);
  21224. normals.push(0, 0, -1.0);
  21225. uvs.push(1.0, 0.0);
  21226. positions.push(halfSize, halfSize, 0);
  21227. normals.push(0, 0, -1.0);
  21228. uvs.push(1.0, 1.0);
  21229. positions.push(-halfSize, halfSize, 0);
  21230. normals.push(0, 0, -1.0);
  21231. uvs.push(0.0, 1.0);
  21232. // Indices
  21233. indices.push(0);
  21234. indices.push(1);
  21235. indices.push(2);
  21236. indices.push(0);
  21237. indices.push(2);
  21238. indices.push(3);
  21239. // Result
  21240. var vertexData = new BABYLON.VertexData();
  21241. vertexData.indices = indices;
  21242. vertexData.positions = positions;
  21243. vertexData.normals = normals;
  21244. vertexData.uvs = uvs;
  21245. return vertexData;
  21246. };
  21247. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  21248. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  21249. var indices = [];
  21250. var positions = [];
  21251. var normals = [];
  21252. var uvs = [];
  21253. radius = radius || 2;
  21254. tube = tube || 0.5;
  21255. radialSegments = radialSegments || 32;
  21256. tubularSegments = tubularSegments || 32;
  21257. p = p || 2;
  21258. q = q || 3;
  21259. // Helper
  21260. var getPos = function (angle) {
  21261. var cu = Math.cos(angle);
  21262. var su = Math.sin(angle);
  21263. var quOverP = q / p * angle;
  21264. var cs = Math.cos(quOverP);
  21265. var tx = radius * (2 + cs) * 0.5 * cu;
  21266. var ty = radius * (2 + cs) * su * 0.5;
  21267. var tz = radius * Math.sin(quOverP) * 0.5;
  21268. return new BABYLON.Vector3(tx, ty, tz);
  21269. };
  21270. for (var i = 0; i <= radialSegments; i++) {
  21271. var modI = i % radialSegments;
  21272. var u = modI / radialSegments * 2 * p * Math.PI;
  21273. var p1 = getPos(u);
  21274. var p2 = getPos(u + 0.01);
  21275. var tang = p2.subtract(p1);
  21276. var n = p2.add(p1);
  21277. var bitan = BABYLON.Vector3.Cross(tang, n);
  21278. n = BABYLON.Vector3.Cross(bitan, tang);
  21279. bitan.normalize();
  21280. n.normalize();
  21281. for (var j = 0; j < tubularSegments; j++) {
  21282. var modJ = j % tubularSegments;
  21283. var v = modJ / tubularSegments * 2 * Math.PI;
  21284. var cx = -tube * Math.cos(v);
  21285. var cy = tube * Math.sin(v);
  21286. positions.push(p1.x + cx * n.x + cy * bitan.x);
  21287. positions.push(p1.y + cx * n.y + cy * bitan.y);
  21288. positions.push(p1.z + cx * n.z + cy * bitan.z);
  21289. uvs.push(i / radialSegments);
  21290. uvs.push(j / tubularSegments);
  21291. }
  21292. }
  21293. for (i = 0; i < radialSegments; i++) {
  21294. for (j = 0; j < tubularSegments; j++) {
  21295. var jNext = (j + 1) % tubularSegments;
  21296. var a = i * tubularSegments + j;
  21297. var b = (i + 1) * tubularSegments + j;
  21298. var c = (i + 1) * tubularSegments + jNext;
  21299. var d = i * tubularSegments + jNext;
  21300. indices.push(d);
  21301. indices.push(b);
  21302. indices.push(a);
  21303. indices.push(d);
  21304. indices.push(c);
  21305. indices.push(b);
  21306. }
  21307. }
  21308. // Normals
  21309. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21310. // Result
  21311. var vertexData = new BABYLON.VertexData();
  21312. vertexData.indices = indices;
  21313. vertexData.positions = positions;
  21314. vertexData.normals = normals;
  21315. vertexData.uvs = uvs;
  21316. return vertexData;
  21317. };
  21318. // Tools
  21319. VertexData.ComputeNormals = function (positions, indices, normals) {
  21320. var positionVectors = [];
  21321. var facesOfVertices = [];
  21322. var index;
  21323. for (index = 0; index < positions.length; index += 3) {
  21324. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  21325. positionVectors.push(vector3);
  21326. facesOfVertices.push([]);
  21327. }
  21328. // Compute normals
  21329. var facesNormals = [];
  21330. for (index = 0; index < indices.length / 3; index++) {
  21331. var i1 = indices[index * 3];
  21332. var i2 = indices[index * 3 + 1];
  21333. var i3 = indices[index * 3 + 2];
  21334. var p1 = positionVectors[i1];
  21335. var p2 = positionVectors[i2];
  21336. var p3 = positionVectors[i3];
  21337. var p1p2 = p1.subtract(p2);
  21338. var p3p2 = p3.subtract(p2);
  21339. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21340. facesOfVertices[i1].push(index);
  21341. facesOfVertices[i2].push(index);
  21342. facesOfVertices[i3].push(index);
  21343. }
  21344. for (index = 0; index < positionVectors.length; index++) {
  21345. var faces = facesOfVertices[index];
  21346. var normal = BABYLON.Vector3.Zero();
  21347. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  21348. normal.addInPlace(facesNormals[faces[faceIndex]]);
  21349. }
  21350. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  21351. normals[index * 3] = normal.x;
  21352. normals[index * 3 + 1] = normal.y;
  21353. normals[index * 3 + 2] = normal.z;
  21354. }
  21355. };
  21356. return VertexData;
  21357. })();
  21358. BABYLON.VertexData = VertexData;
  21359. })(BABYLON || (BABYLON = {}));
  21360. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  21361. var BABYLON;
  21362. (function (BABYLON) {
  21363. var buildCamera = function (that, name) {
  21364. that._leftCamera.isIntermediate = true;
  21365. that.subCameras.push(that._leftCamera);
  21366. that.subCameras.push(that._rightCamera);
  21367. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  21368. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  21369. that._anaglyphPostProcess.onApply = function (effect) {
  21370. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  21371. };
  21372. that._update();
  21373. };
  21374. var AnaglyphArcRotateCamera = (function (_super) {
  21375. __extends(AnaglyphArcRotateCamera, _super);
  21376. // ANY
  21377. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  21378. _super.call(this, name, alpha, beta, radius, target, scene);
  21379. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21380. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  21381. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  21382. buildCamera(this, name);
  21383. }
  21384. AnaglyphArcRotateCamera.prototype._update = function () {
  21385. this._updateCamera(this._leftCamera);
  21386. this._updateCamera(this._rightCamera);
  21387. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  21388. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  21389. _super.prototype._update.call(this);
  21390. };
  21391. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  21392. camera.beta = this.beta;
  21393. camera.radius = this.radius;
  21394. camera.minZ = this.minZ;
  21395. camera.maxZ = this.maxZ;
  21396. camera.fov = this.fov;
  21397. camera.target = this.target;
  21398. };
  21399. return AnaglyphArcRotateCamera;
  21400. })(BABYLON.ArcRotateCamera);
  21401. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  21402. var AnaglyphFreeCamera = (function (_super) {
  21403. __extends(AnaglyphFreeCamera, _super);
  21404. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  21405. _super.call(this, name, position, scene);
  21406. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21407. this._transformMatrix = new BABYLON.Matrix();
  21408. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  21409. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  21410. buildCamera(this, name);
  21411. }
  21412. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  21413. var target = this.getTarget();
  21414. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  21415. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  21416. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  21417. };
  21418. AnaglyphFreeCamera.prototype._update = function () {
  21419. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  21420. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  21421. this._updateCamera(this._leftCamera);
  21422. this._updateCamera(this._rightCamera);
  21423. _super.prototype._update.call(this);
  21424. };
  21425. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  21426. camera.minZ = this.minZ;
  21427. camera.maxZ = this.maxZ;
  21428. camera.fov = this.fov;
  21429. camera.viewport = this.viewport;
  21430. camera.setTarget(this.getTarget());
  21431. };
  21432. return AnaglyphFreeCamera;
  21433. })(BABYLON.FreeCamera);
  21434. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  21435. })(BABYLON || (BABYLON = {}));
  21436. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  21437. var BABYLON;
  21438. (function (BABYLON) {
  21439. var AnaglyphPostProcess = (function (_super) {
  21440. __extends(AnaglyphPostProcess, _super);
  21441. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21442. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  21443. }
  21444. return AnaglyphPostProcess;
  21445. })(BABYLON.PostProcess);
  21446. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  21447. })(BABYLON || (BABYLON = {}));
  21448. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  21449. (function (BABYLON) {
  21450. var Tags = (function () {
  21451. function Tags() {
  21452. }
  21453. Tags.EnableFor = function (obj) {
  21454. obj._tags = obj._tags || {};
  21455. obj.hasTags = function () {
  21456. return Tags.HasTags(obj);
  21457. };
  21458. obj.addTags = function (tagsString) {
  21459. return Tags.AddTagsTo(obj, tagsString);
  21460. };
  21461. obj.removeTags = function (tagsString) {
  21462. return Tags.RemoveTagsFrom(obj, tagsString);
  21463. };
  21464. obj.matchesTagsQuery = function (tagsQuery) {
  21465. return Tags.MatchesQuery(obj, tagsQuery);
  21466. };
  21467. };
  21468. Tags.DisableFor = function (obj) {
  21469. delete obj._tags;
  21470. delete obj.hasTags;
  21471. delete obj.addTags;
  21472. delete obj.removeTags;
  21473. delete obj.matchesTagsQuery;
  21474. };
  21475. Tags.HasTags = function (obj) {
  21476. if (!obj._tags) {
  21477. return false;
  21478. }
  21479. return !BABYLON.Tools.IsEmpty(obj._tags);
  21480. };
  21481. Tags.GetTags = function (obj) {
  21482. if (!obj._tags) {
  21483. return null;
  21484. }
  21485. return obj._tags;
  21486. };
  21487. // the tags 'true' and 'false' are reserved and cannot be used as tags
  21488. // a tag cannot start with '||', '&&', and '!'
  21489. // it cannot contain whitespaces
  21490. Tags.AddTagsTo = function (obj, tagsString) {
  21491. if (!tagsString) {
  21492. return;
  21493. }
  21494. var tags = tagsString.split(" ");
  21495. for (var t in tags) {
  21496. Tags._AddTagTo(obj, tags[t]);
  21497. }
  21498. };
  21499. Tags._AddTagTo = function (obj, tag) {
  21500. tag = tag.trim();
  21501. if (tag === "" || tag === "true" || tag === "false") {
  21502. return;
  21503. }
  21504. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  21505. return;
  21506. }
  21507. Tags.EnableFor(obj);
  21508. obj._tags[tag] = true;
  21509. };
  21510. Tags.RemoveTagsFrom = function (obj, tagsString) {
  21511. if (!Tags.HasTags(obj)) {
  21512. return;
  21513. }
  21514. var tags = tagsString.split(" ");
  21515. for (var t in tags) {
  21516. Tags._RemoveTagFrom(obj, tags[t]);
  21517. }
  21518. };
  21519. Tags._RemoveTagFrom = function (obj, tag) {
  21520. delete obj._tags[tag];
  21521. };
  21522. Tags.MatchesQuery = function (obj, tagsQuery) {
  21523. if (tagsQuery === undefined) {
  21524. return true;
  21525. }
  21526. if (tagsQuery === "") {
  21527. return Tags.HasTags(obj);
  21528. }
  21529. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  21530. };
  21531. return Tags;
  21532. })();
  21533. BABYLON.Tags = Tags;
  21534. })(BABYLON || (BABYLON = {}));
  21535. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  21536. (function (BABYLON) {
  21537. var Internals;
  21538. (function (Internals) {
  21539. var AndOrNotEvaluator = (function () {
  21540. function AndOrNotEvaluator() {
  21541. }
  21542. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  21543. if (!query.match(/\([^\(\)]*\)/g)) {
  21544. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  21545. }
  21546. else {
  21547. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  21548. // remove parenthesis
  21549. r = r.slice(1, r.length - 1);
  21550. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  21551. });
  21552. }
  21553. if (query === "true") {
  21554. return true;
  21555. }
  21556. if (query === "false") {
  21557. return false;
  21558. }
  21559. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  21560. };
  21561. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  21562. evaluateCallback = evaluateCallback || (function (r) {
  21563. return r === "true" ? true : false;
  21564. });
  21565. var result;
  21566. var or = parenthesisContent.split("||");
  21567. for (var i in or) {
  21568. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  21569. var and = ori.split("&&");
  21570. if (and.length > 1) {
  21571. for (var j = 0; j < and.length; ++j) {
  21572. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  21573. if (andj !== "true" && andj !== "false") {
  21574. if (andj[0] === "!") {
  21575. result = !evaluateCallback(andj.substring(1));
  21576. }
  21577. else {
  21578. result = evaluateCallback(andj);
  21579. }
  21580. }
  21581. else {
  21582. result = andj === "true" ? true : false;
  21583. }
  21584. if (!result) {
  21585. ori = "false";
  21586. break;
  21587. }
  21588. }
  21589. }
  21590. if (result || ori === "true") {
  21591. result = true;
  21592. break;
  21593. }
  21594. // result equals false (or undefined)
  21595. if (ori !== "true" && ori !== "false") {
  21596. if (ori[0] === "!") {
  21597. result = !evaluateCallback(ori.substring(1));
  21598. }
  21599. else {
  21600. result = evaluateCallback(ori);
  21601. }
  21602. }
  21603. else {
  21604. result = ori === "true" ? true : false;
  21605. }
  21606. }
  21607. // the whole parenthesis scope is replaced by 'true' or 'false'
  21608. return result ? "true" : "false";
  21609. };
  21610. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  21611. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  21612. // remove whitespaces
  21613. r = r.replace(/[\s]/g, function () { return ""; });
  21614. return r.length % 2 ? "!" : "";
  21615. });
  21616. booleanString = booleanString.trim();
  21617. if (booleanString === "!true") {
  21618. booleanString = "false";
  21619. }
  21620. else if (booleanString === "!false") {
  21621. booleanString = "true";
  21622. }
  21623. return booleanString;
  21624. };
  21625. return AndOrNotEvaluator;
  21626. })();
  21627. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  21628. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21629. })(BABYLON || (BABYLON = {}));
  21630. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  21631. (function (BABYLON) {
  21632. var PostProcessRenderPass = (function () {
  21633. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  21634. this._enabled = true;
  21635. this._refCount = 0;
  21636. this._name = name;
  21637. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  21638. this.setRenderList(renderList);
  21639. this._renderTexture.onBeforeRender = beforeRender;
  21640. this._renderTexture.onAfterRender = afterRender;
  21641. this._scene = scene;
  21642. this._renderList = renderList;
  21643. }
  21644. // private
  21645. PostProcessRenderPass.prototype._incRefCount = function () {
  21646. if (this._refCount === 0) {
  21647. this._scene.customRenderTargets.push(this._renderTexture);
  21648. }
  21649. return ++this._refCount;
  21650. };
  21651. PostProcessRenderPass.prototype._decRefCount = function () {
  21652. this._refCount--;
  21653. if (this._refCount <= 0) {
  21654. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  21655. }
  21656. return this._refCount;
  21657. };
  21658. PostProcessRenderPass.prototype._update = function () {
  21659. this.setRenderList(this._renderList);
  21660. };
  21661. // public
  21662. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  21663. this._renderTexture.renderList = renderList;
  21664. };
  21665. PostProcessRenderPass.prototype.getRenderTexture = function () {
  21666. return this._renderTexture;
  21667. };
  21668. return PostProcessRenderPass;
  21669. })();
  21670. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  21671. })(BABYLON || (BABYLON = {}));
  21672. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  21673. (function (BABYLON) {
  21674. var PostProcessRenderEffect = (function () {
  21675. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  21676. this._engine = engine;
  21677. this._name = name;
  21678. this._singleInstance = singleInstance || true;
  21679. this._getPostProcess = getPostProcess;
  21680. this._cameras = [];
  21681. this._indicesForCamera = [];
  21682. this._postProcesses = {};
  21683. this._renderPasses = {};
  21684. this._renderEffectAsPasses = {};
  21685. }
  21686. PostProcessRenderEffect.prototype._update = function () {
  21687. for (var renderPassName in this._renderPasses) {
  21688. this._renderPasses[renderPassName]._update();
  21689. }
  21690. };
  21691. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  21692. this._renderPasses[renderPass._name] = renderPass;
  21693. this._linkParameters();
  21694. };
  21695. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  21696. delete this._renderPasses[renderPass._name];
  21697. this._linkParameters();
  21698. };
  21699. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  21700. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  21701. this._linkParameters();
  21702. };
  21703. PostProcessRenderEffect.prototype.getPass = function (passName) {
  21704. for (var renderPassName in this._renderPasses) {
  21705. if (renderPassName === passName) {
  21706. return this._renderPasses[passName];
  21707. }
  21708. }
  21709. };
  21710. PostProcessRenderEffect.prototype.emptyPasses = function () {
  21711. this._renderPasses = {};
  21712. this._linkParameters();
  21713. };
  21714. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  21715. var cameraKey;
  21716. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21717. for (var i = 0; i < _cam.length; i++) {
  21718. var camera = _cam[i];
  21719. var cameraName = camera.name;
  21720. if (this._singleInstance) {
  21721. cameraKey = 0;
  21722. }
  21723. else {
  21724. cameraKey = cameraName;
  21725. }
  21726. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  21727. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  21728. if (!this._indicesForCamera[cameraName]) {
  21729. this._indicesForCamera[cameraName] = [];
  21730. }
  21731. this._indicesForCamera[cameraName].push(index);
  21732. if (this._cameras.indexOf(camera) === -1) {
  21733. this._cameras[cameraName] = camera;
  21734. }
  21735. for (var passName in this._renderPasses) {
  21736. this._renderPasses[passName]._incRefCount();
  21737. }
  21738. }
  21739. this._linkParameters();
  21740. };
  21741. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  21742. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21743. for (var i = 0; i < _cam.length; i++) {
  21744. var camera = _cam[i];
  21745. var cameraName = camera.name;
  21746. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21747. var index = this._cameras.indexOf(cameraName);
  21748. this._indicesForCamera.splice(index, 1);
  21749. this._cameras.splice(index, 1);
  21750. for (var passName in this._renderPasses) {
  21751. this._renderPasses[passName]._decRefCount();
  21752. }
  21753. }
  21754. };
  21755. PostProcessRenderEffect.prototype._enable = function (cameras) {
  21756. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21757. for (var i = 0; i < _cam.length; i++) {
  21758. var camera = _cam[i];
  21759. var cameraName = camera.name;
  21760. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  21761. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  21762. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  21763. }
  21764. }
  21765. for (var passName in this._renderPasses) {
  21766. this._renderPasses[passName]._incRefCount();
  21767. }
  21768. }
  21769. };
  21770. PostProcessRenderEffect.prototype._disable = function (cameras) {
  21771. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21772. for (var i = 0; i < _cam.length; i++) {
  21773. var camera = _cam[i];
  21774. var cameraName = camera.Name;
  21775. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21776. for (var passName in this._renderPasses) {
  21777. this._renderPasses[passName]._decRefCount();
  21778. }
  21779. }
  21780. };
  21781. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  21782. if (this._singleInstance) {
  21783. return this._postProcesses[0];
  21784. }
  21785. else {
  21786. return this._postProcesses[camera.name];
  21787. }
  21788. };
  21789. PostProcessRenderEffect.prototype._linkParameters = function () {
  21790. var _this = this;
  21791. for (var index in this._postProcesses) {
  21792. if (this.applyParameters) {
  21793. this.applyParameters(this._postProcesses[index]);
  21794. }
  21795. this._postProcesses[index].onBeforeRender = function (effect) {
  21796. _this._linkTextures(effect);
  21797. };
  21798. }
  21799. };
  21800. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  21801. for (var renderPassName in this._renderPasses) {
  21802. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  21803. }
  21804. for (var renderEffectName in this._renderEffectAsPasses) {
  21805. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  21806. }
  21807. };
  21808. return PostProcessRenderEffect;
  21809. })();
  21810. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  21811. })(BABYLON || (BABYLON = {}));
  21812. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  21813. (function (BABYLON) {
  21814. var PostProcessRenderPipeline = (function () {
  21815. function PostProcessRenderPipeline(engine, name) {
  21816. this._engine = engine;
  21817. this._name = name;
  21818. this._renderEffects = {};
  21819. this._renderEffectsForIsolatedPass = {};
  21820. this._cameras = [];
  21821. }
  21822. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  21823. this._renderEffects[renderEffect._name] = renderEffect;
  21824. };
  21825. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  21826. var renderEffects = this._renderEffects[renderEffectName];
  21827. if (!renderEffects) {
  21828. return;
  21829. }
  21830. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21831. };
  21832. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  21833. var renderEffects = this._renderEffects[renderEffectName];
  21834. if (!renderEffects) {
  21835. return;
  21836. }
  21837. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21838. };
  21839. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  21840. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21841. var indicesToDelete = [];
  21842. for (var i = 0; i < _cam.length; i++) {
  21843. var camera = _cam[i];
  21844. var cameraName = camera.name;
  21845. if (this._cameras.indexOf(camera) === -1) {
  21846. this._cameras[cameraName] = camera;
  21847. }
  21848. else if (unique) {
  21849. indicesToDelete.push(i);
  21850. }
  21851. }
  21852. for (var i = 0; i < indicesToDelete.length; i++) {
  21853. cameras.splice(indicesToDelete[i], 1);
  21854. }
  21855. for (var renderEffectName in this._renderEffects) {
  21856. this._renderEffects[renderEffectName]._attachCameras(_cam);
  21857. }
  21858. };
  21859. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  21860. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21861. for (var renderEffectName in this._renderEffects) {
  21862. this._renderEffects[renderEffectName]._detachCameras(_cam);
  21863. }
  21864. for (var i = 0; i < _cam.length; i++) {
  21865. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  21866. }
  21867. };
  21868. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  21869. var _this = this;
  21870. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21871. var pass = null;
  21872. for (var renderEffectName in this._renderEffects) {
  21873. pass = this._renderEffects[renderEffectName].getPass(passName);
  21874. if (pass != null) {
  21875. break;
  21876. }
  21877. }
  21878. if (pass === null) {
  21879. return;
  21880. }
  21881. for (var renderEffectName in this._renderEffects) {
  21882. this._renderEffects[renderEffectName]._disable(_cam);
  21883. }
  21884. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  21885. for (var i = 0; i < _cam.length; i++) {
  21886. var camera = _cam[i];
  21887. var cameraName = camera.name;
  21888. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21889. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21890. });
  21891. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  21892. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  21893. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  21894. }
  21895. };
  21896. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  21897. var _this = this;
  21898. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21899. for (var i = 0; i < _cam.length; i++) {
  21900. var camera = _cam[i];
  21901. var cameraName = camera.name;
  21902. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21903. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21904. });
  21905. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  21906. }
  21907. for (var renderEffectName in this._renderEffects) {
  21908. this._renderEffects[renderEffectName]._enable(_cam);
  21909. }
  21910. };
  21911. PostProcessRenderPipeline.prototype._update = function () {
  21912. for (var renderEffectName in this._renderEffects) {
  21913. this._renderEffects[renderEffectName]._update();
  21914. }
  21915. for (var i = 0; i < this._cameras.length; i++) {
  21916. var cameraName = this._cameras[i].name;
  21917. if (this._renderEffectsForIsolatedPass[cameraName]) {
  21918. this._renderEffectsForIsolatedPass[cameraName]._update();
  21919. }
  21920. }
  21921. };
  21922. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  21923. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  21924. return PostProcessRenderPipeline;
  21925. })();
  21926. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  21927. })(BABYLON || (BABYLON = {}));
  21928. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  21929. (function (BABYLON) {
  21930. var PostProcessRenderPipelineManager = (function () {
  21931. function PostProcessRenderPipelineManager() {
  21932. this._renderPipelines = {};
  21933. }
  21934. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  21935. this._renderPipelines[renderPipeline._name] = renderPipeline;
  21936. };
  21937. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  21938. var renderPipeline = this._renderPipelines[renderPipelineName];
  21939. if (!renderPipeline) {
  21940. return;
  21941. }
  21942. renderPipeline._attachCameras(cameras, unique);
  21943. };
  21944. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  21945. var renderPipeline = this._renderPipelines[renderPipelineName];
  21946. if (!renderPipeline) {
  21947. return;
  21948. }
  21949. renderPipeline._detachCameras(cameras);
  21950. };
  21951. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21952. var renderPipeline = this._renderPipelines[renderPipelineName];
  21953. if (!renderPipeline) {
  21954. return;
  21955. }
  21956. renderPipeline._enableEffect(renderEffectName, cameras);
  21957. };
  21958. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21959. var renderPipeline = this._renderPipelines[renderPipelineName];
  21960. if (!renderPipeline) {
  21961. return;
  21962. }
  21963. renderPipeline._disableEffect(renderEffectName, cameras);
  21964. };
  21965. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  21966. var renderPipeline = this._renderPipelines[renderPipelineName];
  21967. if (!renderPipeline) {
  21968. return;
  21969. }
  21970. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  21971. };
  21972. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  21973. var renderPipeline = this._renderPipelines[renderPipelineName];
  21974. if (!renderPipeline) {
  21975. return;
  21976. }
  21977. renderPipeline._disableDisplayOnlyPass(cameras);
  21978. };
  21979. PostProcessRenderPipelineManager.prototype.update = function () {
  21980. for (var renderPipelineName in this._renderPipelines) {
  21981. this._renderPipelines[renderPipelineName]._update();
  21982. }
  21983. };
  21984. return PostProcessRenderPipelineManager;
  21985. })();
  21986. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  21987. })(BABYLON || (BABYLON = {}));
  21988. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  21989. var BABYLON;
  21990. (function (BABYLON) {
  21991. var DisplayPassPostProcess = (function (_super) {
  21992. __extends(DisplayPassPostProcess, _super);
  21993. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21994. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  21995. }
  21996. return DisplayPassPostProcess;
  21997. })(BABYLON.PostProcess);
  21998. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  21999. })(BABYLON || (BABYLON = {}));
  22000. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  22001. (function (BABYLON) {
  22002. var BoundingBoxRenderer = (function () {
  22003. function BoundingBoxRenderer(scene) {
  22004. this.frontColor = new BABYLON.Color3(1, 1, 1);
  22005. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  22006. this.showBackLines = true;
  22007. this.renderList = new BABYLON.SmartArray(32);
  22008. this._scene = scene;
  22009. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  22010. attributes: ["position"],
  22011. uniforms: ["worldViewProjection", "color"]
  22012. });
  22013. var engine = this._scene.getEngine();
  22014. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  22015. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  22016. 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]);
  22017. }
  22018. BoundingBoxRenderer.prototype.reset = function () {
  22019. this.renderList.reset();
  22020. };
  22021. BoundingBoxRenderer.prototype.render = function () {
  22022. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  22023. return;
  22024. }
  22025. var engine = this._scene.getEngine();
  22026. engine.setDepthWrite(false);
  22027. this._colorShader._preBind();
  22028. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  22029. var boundingBox = this.renderList.data[boundingBoxIndex];
  22030. var min = boundingBox.minimum;
  22031. var max = boundingBox.maximum;
  22032. var diff = max.subtract(min);
  22033. var median = min.add(diff.scale(0.5));
  22034. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  22035. // VBOs
  22036. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  22037. if (this.showBackLines) {
  22038. // Back
  22039. engine.setDepthFunctionToGreaterOrEqual();
  22040. this._scene.resetCachedMaterial();
  22041. this._colorShader.setColor4("color", this.backColor.toColor4());
  22042. this._colorShader.bind(worldMatrix);
  22043. // Draw order
  22044. engine.draw(false, 0, 24);
  22045. }
  22046. // Front
  22047. engine.setDepthFunctionToLess();
  22048. this._scene.resetCachedMaterial();
  22049. this._colorShader.setColor4("color", this.frontColor.toColor4());
  22050. this._colorShader.bind(worldMatrix);
  22051. // Draw order
  22052. engine.draw(false, 0, 24);
  22053. }
  22054. this._colorShader.unbind();
  22055. engine.setDepthFunctionToLessOrEqual();
  22056. engine.setDepthWrite(true);
  22057. };
  22058. BoundingBoxRenderer.prototype.dispose = function () {
  22059. this._colorShader.dispose();
  22060. this._vb.dispose();
  22061. this._scene.getEngine()._releaseBuffer(this._ib);
  22062. };
  22063. return BoundingBoxRenderer;
  22064. })();
  22065. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  22066. })(BABYLON || (BABYLON = {}));
  22067. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  22068. (function (BABYLON) {
  22069. var Internals;
  22070. (function (Internals) {
  22071. /*
  22072. * Based on jsTGALoader - Javascript loader for TGA file
  22073. * By Vincent Thibault
  22074. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  22075. */
  22076. var TGATools = (function () {
  22077. function TGATools() {
  22078. }
  22079. TGATools.GetTGAHeader = function (data) {
  22080. var offset = 0;
  22081. var header = {
  22082. id_length: data[offset++],
  22083. colormap_type: data[offset++],
  22084. image_type: data[offset++],
  22085. colormap_index: data[offset++] | data[offset++] << 8,
  22086. colormap_length: data[offset++] | data[offset++] << 8,
  22087. colormap_size: data[offset++],
  22088. origin: [
  22089. data[offset++] | data[offset++] << 8,
  22090. data[offset++] | data[offset++] << 8
  22091. ],
  22092. width: data[offset++] | data[offset++] << 8,
  22093. height: data[offset++] | data[offset++] << 8,
  22094. pixel_size: data[offset++],
  22095. flags: data[offset++]
  22096. };
  22097. return header;
  22098. };
  22099. TGATools.UploadContent = function (gl, data) {
  22100. // Not enough data to contain header ?
  22101. if (data.length < 19) {
  22102. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  22103. return;
  22104. }
  22105. // Read Header
  22106. var offset = 18;
  22107. var header = TGATools.GetTGAHeader(data);
  22108. // Assume it's a valid Targa file.
  22109. if (header.id_length + offset > data.length) {
  22110. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  22111. return;
  22112. }
  22113. // Skip not needed data
  22114. offset += header.id_length;
  22115. var use_rle = false;
  22116. var use_pal = false;
  22117. var use_rgb = false;
  22118. var use_grey = false;
  22119. switch (header.image_type) {
  22120. case TGATools._TYPE_RLE_INDEXED:
  22121. use_rle = true;
  22122. case TGATools._TYPE_INDEXED:
  22123. use_pal = true;
  22124. break;
  22125. case TGATools._TYPE_RLE_RGB:
  22126. use_rle = true;
  22127. case TGATools._TYPE_RGB:
  22128. use_rgb = true;
  22129. break;
  22130. case TGATools._TYPE_RLE_GREY:
  22131. use_rle = true;
  22132. case TGATools._TYPE_GREY:
  22133. use_grey = true;
  22134. break;
  22135. }
  22136. var pixel_data;
  22137. var numAlphaBits = header.flags & 0xf;
  22138. var pixel_size = header.pixel_size >> 3;
  22139. var pixel_total = header.width * header.height * pixel_size;
  22140. // Read palettes
  22141. var palettes;
  22142. if (use_pal) {
  22143. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  22144. }
  22145. // Read LRE
  22146. if (use_rle) {
  22147. pixel_data = new Uint8Array(pixel_total);
  22148. var c, count, i;
  22149. var localOffset = 0;
  22150. var pixels = new Uint8Array(pixel_size);
  22151. while (offset < pixel_total && localOffset < pixel_total) {
  22152. c = data[offset++];
  22153. count = (c & 0x7f) + 1;
  22154. // RLE pixels
  22155. if (c & 0x80) {
  22156. for (i = 0; i < pixel_size; ++i) {
  22157. pixels[i] = data[offset++];
  22158. }
  22159. for (i = 0; i < count; ++i) {
  22160. pixel_data.set(pixels, localOffset + i * pixel_size);
  22161. }
  22162. localOffset += pixel_size * count;
  22163. }
  22164. else {
  22165. count *= pixel_size;
  22166. for (i = 0; i < count; ++i) {
  22167. pixel_data[localOffset + i] = data[offset++];
  22168. }
  22169. localOffset += count;
  22170. }
  22171. }
  22172. }
  22173. else {
  22174. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  22175. }
  22176. // Load to texture
  22177. var x_start, y_start, x_step, y_step, y_end, x_end;
  22178. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  22179. default:
  22180. case TGATools._ORIGIN_UL:
  22181. x_start = 0;
  22182. x_step = 1;
  22183. x_end = header.width;
  22184. y_start = 0;
  22185. y_step = 1;
  22186. y_end = header.height;
  22187. break;
  22188. case TGATools._ORIGIN_BL:
  22189. x_start = 0;
  22190. x_step = 1;
  22191. x_end = header.width;
  22192. y_start = header.height - 1;
  22193. y_step = -1;
  22194. y_end = -1;
  22195. break;
  22196. case TGATools._ORIGIN_UR:
  22197. x_start = header.width - 1;
  22198. x_step = -1;
  22199. x_end = -1;
  22200. y_start = 0;
  22201. y_step = 1;
  22202. y_end = header.height;
  22203. break;
  22204. case TGATools._ORIGIN_BR:
  22205. x_start = header.width - 1;
  22206. x_step = -1;
  22207. x_end = -1;
  22208. y_start = header.height - 1;
  22209. y_step = -1;
  22210. y_end = -1;
  22211. break;
  22212. }
  22213. // Load the specify method
  22214. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  22215. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  22216. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  22217. };
  22218. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22219. var image = pixel_data, colormap = palettes;
  22220. var width = header.width, height = header.height;
  22221. var color, i = 0, x, y;
  22222. var imageData = new Uint8Array(width * height * 4);
  22223. for (y = y_start; y !== y_end; y += y_step) {
  22224. for (x = x_start; x !== x_end; x += x_step, i++) {
  22225. color = image[i];
  22226. imageData[(x + width * y) * 4 + 3] = 255;
  22227. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  22228. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  22229. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  22230. }
  22231. }
  22232. return imageData;
  22233. };
  22234. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22235. var image = pixel_data;
  22236. var width = header.width, height = header.height;
  22237. var color, i = 0, x, y;
  22238. var imageData = new Uint8Array(width * height * 4);
  22239. for (y = y_start; y !== y_end; y += y_step) {
  22240. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22241. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  22242. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  22243. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  22244. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  22245. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  22246. }
  22247. }
  22248. return imageData;
  22249. };
  22250. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22251. var image = pixel_data;
  22252. var width = header.width, height = header.height;
  22253. var i = 0, x, y;
  22254. var imageData = new Uint8Array(width * height * 4);
  22255. for (y = y_start; y !== y_end; y += y_step) {
  22256. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  22257. imageData[(x + width * y) * 4 + 3] = 255;
  22258. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22259. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22260. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22261. }
  22262. }
  22263. return imageData;
  22264. };
  22265. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22266. var image = pixel_data;
  22267. var width = header.width, height = header.height;
  22268. var i = 0, x, y;
  22269. var imageData = new Uint8Array(width * height * 4);
  22270. for (y = y_start; y !== y_end; y += y_step) {
  22271. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  22272. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22273. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22274. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22275. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  22276. }
  22277. }
  22278. return imageData;
  22279. };
  22280. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22281. var image = pixel_data;
  22282. var width = header.width, height = header.height;
  22283. var color, i = 0, x, y;
  22284. var imageData = new Uint8Array(width * height * 4);
  22285. for (y = y_start; y !== y_end; y += y_step) {
  22286. for (x = x_start; x !== x_end; x += x_step, i++) {
  22287. color = image[i];
  22288. imageData[(x + width * y) * 4 + 0] = color;
  22289. imageData[(x + width * y) * 4 + 1] = color;
  22290. imageData[(x + width * y) * 4 + 2] = color;
  22291. imageData[(x + width * y) * 4 + 3] = 255;
  22292. }
  22293. }
  22294. return imageData;
  22295. };
  22296. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22297. var image = pixel_data;
  22298. var width = header.width, height = header.height;
  22299. var i = 0, x, y;
  22300. var imageData = new Uint8Array(width * height * 4);
  22301. for (y = y_start; y !== y_end; y += y_step) {
  22302. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22303. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  22304. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  22305. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22306. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  22307. }
  22308. }
  22309. return imageData;
  22310. };
  22311. TGATools._TYPE_NO_DATA = 0;
  22312. TGATools._TYPE_INDEXED = 1;
  22313. TGATools._TYPE_RGB = 2;
  22314. TGATools._TYPE_GREY = 3;
  22315. TGATools._TYPE_RLE_INDEXED = 9;
  22316. TGATools._TYPE_RLE_RGB = 10;
  22317. TGATools._TYPE_RLE_GREY = 11;
  22318. TGATools._ORIGIN_MASK = 0x30;
  22319. TGATools._ORIGIN_SHIFT = 0x04;
  22320. TGATools._ORIGIN_BL = 0x00;
  22321. TGATools._ORIGIN_BR = 0x01;
  22322. TGATools._ORIGIN_UL = 0x02;
  22323. TGATools._ORIGIN_UR = 0x03;
  22324. return TGATools;
  22325. })();
  22326. Internals.TGATools = TGATools;
  22327. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22328. })(BABYLON || (BABYLON = {}));
  22329. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  22330. (function (BABYLON) {
  22331. var Internals;
  22332. (function (Internals) {
  22333. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  22334. // All values and structures referenced from:
  22335. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  22336. var DDS_MAGIC = 0x20534444;
  22337. 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;
  22338. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  22339. 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;
  22340. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  22341. function FourCCToInt32(value) {
  22342. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  22343. }
  22344. function Int32ToFourCC(value) {
  22345. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  22346. }
  22347. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  22348. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  22349. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  22350. var headerLengthInt = 31; // The header length in 32 bit ints
  22351. // Offsets into the header array
  22352. var off_magic = 0;
  22353. var off_size = 1;
  22354. var off_flags = 2;
  22355. var off_height = 3;
  22356. var off_width = 4;
  22357. var off_mipmapCount = 7;
  22358. var off_pfFlags = 20;
  22359. var off_pfFourCC = 21;
  22360. var off_RGBbpp = 22;
  22361. var off_RMask = 23;
  22362. var off_GMask = 24;
  22363. var off_BMask = 25;
  22364. var off_AMask = 26;
  22365. var off_caps1 = 27;
  22366. var off_caps2 = 28;
  22367. ;
  22368. var DDSTools = (function () {
  22369. function DDSTools() {
  22370. }
  22371. DDSTools.GetDDSInfo = function (arrayBuffer) {
  22372. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  22373. var mipmapCount = 1;
  22374. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  22375. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22376. }
  22377. return {
  22378. width: header[off_width],
  22379. height: header[off_height],
  22380. mipmapCount: mipmapCount,
  22381. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  22382. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  22383. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  22384. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  22385. };
  22386. };
  22387. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22388. var byteArray = new Uint8Array(dataLength);
  22389. var srcData = new Uint8Array(arrayBuffer);
  22390. var index = 0;
  22391. for (var y = height - 1; y >= 0; y--) {
  22392. for (var x = 0; x < width; x++) {
  22393. var srcPos = dataOffset + (x + y * width) * 4;
  22394. byteArray[index + 2] = srcData[srcPos];
  22395. byteArray[index + 1] = srcData[srcPos + 1];
  22396. byteArray[index] = srcData[srcPos + 2];
  22397. byteArray[index + 3] = srcData[srcPos + 3];
  22398. index += 4;
  22399. }
  22400. }
  22401. return byteArray;
  22402. };
  22403. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22404. var byteArray = new Uint8Array(dataLength);
  22405. var srcData = new Uint8Array(arrayBuffer);
  22406. var index = 0;
  22407. for (var y = height - 1; y >= 0; y--) {
  22408. for (var x = 0; x < width; x++) {
  22409. var srcPos = dataOffset + (x + y * width) * 3;
  22410. byteArray[index + 2] = srcData[srcPos];
  22411. byteArray[index + 1] = srcData[srcPos + 1];
  22412. byteArray[index] = srcData[srcPos + 2];
  22413. index += 3;
  22414. }
  22415. }
  22416. return byteArray;
  22417. };
  22418. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22419. var byteArray = new Uint8Array(dataLength);
  22420. var srcData = new Uint8Array(arrayBuffer);
  22421. var index = 0;
  22422. for (var y = height - 1; y >= 0; y--) {
  22423. for (var x = 0; x < width; x++) {
  22424. var srcPos = dataOffset + (x + y * width);
  22425. byteArray[index] = srcData[srcPos];
  22426. index++;
  22427. }
  22428. }
  22429. return byteArray;
  22430. };
  22431. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  22432. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  22433. if (header[off_magic] != DDS_MAGIC) {
  22434. BABYLON.Tools.Error("Invalid magic number in DDS header");
  22435. return;
  22436. }
  22437. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  22438. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  22439. return;
  22440. }
  22441. if (info.isFourCC) {
  22442. fourCC = header[off_pfFourCC];
  22443. switch (fourCC) {
  22444. case FOURCC_DXT1:
  22445. blockBytes = 8;
  22446. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  22447. break;
  22448. case FOURCC_DXT3:
  22449. blockBytes = 16;
  22450. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  22451. break;
  22452. case FOURCC_DXT5:
  22453. blockBytes = 16;
  22454. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  22455. break;
  22456. default:
  22457. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  22458. return;
  22459. }
  22460. }
  22461. mipmapCount = 1;
  22462. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  22463. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22464. }
  22465. var bpp = header[off_RGBbpp];
  22466. for (var face = 0; face < faces; face++) {
  22467. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  22468. width = header[off_width];
  22469. height = header[off_height];
  22470. dataOffset = header[off_size] + 4;
  22471. for (i = 0; i < mipmapCount; ++i) {
  22472. if (info.isRGB) {
  22473. if (bpp == 24) {
  22474. dataLength = width * height * 3;
  22475. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22476. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  22477. }
  22478. else {
  22479. dataLength = width * height * 4;
  22480. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22481. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  22482. }
  22483. }
  22484. else if (info.isLuminance) {
  22485. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  22486. var unpaddedRowSize = width;
  22487. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  22488. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  22489. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22490. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  22491. }
  22492. else {
  22493. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  22494. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  22495. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  22496. }
  22497. dataOffset += dataLength;
  22498. width *= 0.5;
  22499. height *= 0.5;
  22500. width = Math.max(1.0, width);
  22501. height = Math.max(1.0, height);
  22502. }
  22503. }
  22504. };
  22505. return DDSTools;
  22506. })();
  22507. Internals.DDSTools = DDSTools;
  22508. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22509. })(BABYLON || (BABYLON = {}));
  22510. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  22511. (function (BABYLON) {
  22512. var SmartArray = (function () {
  22513. function SmartArray(capacity) {
  22514. this.length = 0;
  22515. this._duplicateId = 0;
  22516. this.data = new Array(capacity);
  22517. this._id = SmartArray._GlobalId++;
  22518. }
  22519. SmartArray.prototype.push = function (value) {
  22520. this.data[this.length++] = value;
  22521. if (this.length > this.data.length) {
  22522. this.data.length *= 2;
  22523. }
  22524. if (!value.__smartArrayFlags) {
  22525. value.__smartArrayFlags = {};
  22526. }
  22527. value.__smartArrayFlags[this._id] = this._duplicateId;
  22528. };
  22529. SmartArray.prototype.pushNoDuplicate = function (value) {
  22530. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  22531. return;
  22532. }
  22533. this.push(value);
  22534. };
  22535. SmartArray.prototype.sort = function (compareFn) {
  22536. this.data.sort(compareFn);
  22537. };
  22538. SmartArray.prototype.reset = function () {
  22539. this.length = 0;
  22540. this._duplicateId++;
  22541. };
  22542. SmartArray.prototype.concat = function (array) {
  22543. if (array.length === 0) {
  22544. return;
  22545. }
  22546. if (this.length + array.length > this.data.length) {
  22547. this.data.length = (this.length + array.length) * 2;
  22548. }
  22549. for (var index = 0; index < array.length; index++) {
  22550. this.data[this.length++] = (array.data || array)[index];
  22551. }
  22552. };
  22553. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  22554. if (array.length === 0) {
  22555. return;
  22556. }
  22557. if (this.length + array.length > this.data.length) {
  22558. this.data.length = (this.length + array.length) * 2;
  22559. }
  22560. for (var index = 0; index < array.length; index++) {
  22561. var item = (array.data || array)[index];
  22562. this.pushNoDuplicate(item);
  22563. }
  22564. };
  22565. SmartArray.prototype.indexOf = function (value) {
  22566. var position = this.data.indexOf(value);
  22567. if (position >= this.length) {
  22568. return -1;
  22569. }
  22570. return position;
  22571. };
  22572. // Statics
  22573. SmartArray._GlobalId = 0;
  22574. return SmartArray;
  22575. })();
  22576. BABYLON.SmartArray = SmartArray;
  22577. })(BABYLON || (BABYLON = {}));
  22578. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  22579. (function (BABYLON) {
  22580. var CannonJSPlugin = (function () {
  22581. function CannonJSPlugin() {
  22582. this._registeredMeshes = [];
  22583. this._physicsMaterials = [];
  22584. this.updateBodyPosition = function (mesh) {
  22585. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22586. var registeredMesh = this._registeredMeshes[index];
  22587. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22588. var body = registeredMesh.body;
  22589. var center = mesh.getBoundingInfo().boundingBox.center;
  22590. body.position.set(center.x, center.z, center.y);
  22591. body.quaternion.x = mesh.rotationQuaternion.x;
  22592. body.quaternion.z = mesh.rotationQuaternion.y;
  22593. body.quaternion.y = mesh.rotationQuaternion.z;
  22594. body.quaternion.w = -mesh.rotationQuaternion.w;
  22595. return;
  22596. }
  22597. }
  22598. };
  22599. }
  22600. CannonJSPlugin.prototype.initialize = function (iterations) {
  22601. if (iterations === void 0) { iterations = 10; }
  22602. this._world = new CANNON.World();
  22603. this._world.broadphase = new CANNON.NaiveBroadphase();
  22604. this._world.solver.iterations = iterations;
  22605. };
  22606. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22607. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22608. };
  22609. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22610. this._world.step(delta);
  22611. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22612. var registeredMesh = this._registeredMeshes[index];
  22613. if (registeredMesh.isChild) {
  22614. continue;
  22615. }
  22616. // Body position
  22617. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22618. var deltaPos = registeredMesh.delta;
  22619. if (deltaPos) {
  22620. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22621. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22622. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22623. }
  22624. else {
  22625. registeredMesh.mesh.position.x = bodyX;
  22626. registeredMesh.mesh.position.y = bodyZ;
  22627. registeredMesh.mesh.position.z = bodyY;
  22628. }
  22629. if (!registeredMesh.mesh.rotationQuaternion) {
  22630. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22631. }
  22632. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22633. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22634. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22635. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22636. }
  22637. };
  22638. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22639. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22640. };
  22641. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22642. this.unregisterMesh(mesh);
  22643. mesh.computeWorldMatrix(true);
  22644. switch (impostor) {
  22645. case BABYLON.PhysicsEngine.SphereImpostor:
  22646. var bbox = mesh.getBoundingInfo().boundingBox;
  22647. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22648. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22649. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22650. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22651. case BABYLON.PhysicsEngine.BoxImpostor:
  22652. bbox = mesh.getBoundingInfo().boundingBox;
  22653. var min = bbox.minimumWorld;
  22654. var max = bbox.maximumWorld;
  22655. var box = max.subtract(min).scale(0.5);
  22656. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22657. case BABYLON.PhysicsEngine.PlaneImpostor:
  22658. return this._createPlane(mesh, options);
  22659. case BABYLON.PhysicsEngine.MeshImpostor:
  22660. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22661. var rawFaces = mesh.getIndices();
  22662. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22663. }
  22664. return null;
  22665. };
  22666. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22667. var shape = new CANNON.Sphere(radius);
  22668. if (!options) {
  22669. return shape;
  22670. }
  22671. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22672. };
  22673. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22674. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22675. if (!options) {
  22676. return shape;
  22677. }
  22678. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22679. };
  22680. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22681. var shape = new CANNON.Plane();
  22682. if (!options) {
  22683. return shape;
  22684. }
  22685. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22686. };
  22687. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22688. var verts = [], faces = [];
  22689. mesh.computeWorldMatrix(true);
  22690. for (var i = 0; i < rawVerts.length; i += 3) {
  22691. var transformed = BABYLON.Vector3.Zero();
  22692. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22693. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22694. }
  22695. for (var j = 0; j < rawFaces.length; j += 3) {
  22696. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22697. }
  22698. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22699. if (!options) {
  22700. return shape;
  22701. }
  22702. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22703. };
  22704. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22705. var index;
  22706. var mat;
  22707. for (index = 0; index < this._physicsMaterials.length; index++) {
  22708. mat = this._physicsMaterials[index];
  22709. if (mat.friction === friction && mat.restitution === restitution) {
  22710. return mat;
  22711. }
  22712. }
  22713. var currentMat = new CANNON.Material();
  22714. currentMat.friction = friction;
  22715. currentMat.restitution = restitution;
  22716. this._physicsMaterials.push(currentMat);
  22717. for (index = 0; index < this._physicsMaterials.length; index++) {
  22718. mat = this._physicsMaterials[index];
  22719. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22720. contactMaterial.contactEquationStiffness = 1e10;
  22721. contactMaterial.contactEquationRegularizationTime = 10;
  22722. this._world.addContactMaterial(contactMaterial);
  22723. }
  22724. return currentMat;
  22725. };
  22726. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22727. var initialRotation = null;
  22728. if (mesh.rotationQuaternion) {
  22729. initialRotation = mesh.rotationQuaternion.clone();
  22730. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22731. }
  22732. // The delta between the mesh position and the mesh bounding box center
  22733. var bbox = mesh.getBoundingInfo().boundingBox;
  22734. var deltaPosition = mesh.position.subtract(bbox.center);
  22735. var material = this._addMaterial(friction, restitution);
  22736. var body = new CANNON.RigidBody(mass, shape, material);
  22737. if (initialRotation) {
  22738. body.quaternion.x = initialRotation.x;
  22739. body.quaternion.z = initialRotation.y;
  22740. body.quaternion.y = initialRotation.z;
  22741. body.quaternion.w = -initialRotation.w;
  22742. }
  22743. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22744. this._world.add(body);
  22745. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22746. return body;
  22747. };
  22748. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22749. var compoundShape = new CANNON.Compound();
  22750. for (var index = 0; index < parts.length; index++) {
  22751. var mesh = parts[index].mesh;
  22752. var shape = this.registerMesh(mesh, parts[index].impostor);
  22753. if (index == 0) {
  22754. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22755. }
  22756. else {
  22757. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22758. }
  22759. }
  22760. var initialMesh = parts[0].mesh;
  22761. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22762. body.parts = parts;
  22763. return body;
  22764. };
  22765. CannonJSPlugin.prototype._unbindBody = function (body) {
  22766. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22767. var registeredMesh = this._registeredMeshes[index];
  22768. if (registeredMesh.body === body) {
  22769. registeredMesh.body = null;
  22770. registeredMesh.delta = 0;
  22771. }
  22772. }
  22773. };
  22774. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22775. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22776. var registeredMesh = this._registeredMeshes[index];
  22777. if (registeredMesh.mesh === mesh) {
  22778. // Remove body
  22779. if (registeredMesh.body) {
  22780. this._world.remove(registeredMesh.body);
  22781. this._unbindBody(registeredMesh.body);
  22782. }
  22783. this._registeredMeshes.splice(index, 1);
  22784. return;
  22785. }
  22786. }
  22787. };
  22788. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22789. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22790. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22791. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22792. var registeredMesh = this._registeredMeshes[index];
  22793. if (registeredMesh.mesh === mesh) {
  22794. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22795. return;
  22796. }
  22797. }
  22798. };
  22799. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22800. var body1 = null, body2 = null;
  22801. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22802. var registeredMesh = this._registeredMeshes[index];
  22803. if (registeredMesh.mesh === mesh1) {
  22804. body1 = registeredMesh.body;
  22805. }
  22806. else if (registeredMesh.mesh === mesh2) {
  22807. body2 = registeredMesh.body;
  22808. }
  22809. }
  22810. if (!body1 || !body2) {
  22811. return false;
  22812. }
  22813. 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));
  22814. this._world.addConstraint(constraint);
  22815. return true;
  22816. };
  22817. CannonJSPlugin.prototype.dispose = function () {
  22818. while (this._registeredMeshes.length) {
  22819. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22820. }
  22821. };
  22822. CannonJSPlugin.prototype.isSupported = function () {
  22823. return window.CANNON !== undefined;
  22824. };
  22825. return CannonJSPlugin;
  22826. })();
  22827. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22828. })(BABYLON || (BABYLON = {}));
  22829. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22830. var BABYLON;
  22831. (function (BABYLON) {
  22832. var Condition = (function () {
  22833. function Condition(actionManager) {
  22834. this._actionManager = actionManager;
  22835. }
  22836. Condition.prototype.isValid = function () {
  22837. return true;
  22838. };
  22839. Condition.prototype._getProperty = function (propertyPath) {
  22840. return this._actionManager._getProperty(propertyPath);
  22841. };
  22842. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  22843. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22844. };
  22845. return Condition;
  22846. })();
  22847. BABYLON.Condition = Condition;
  22848. var ValueCondition = (function (_super) {
  22849. __extends(ValueCondition, _super);
  22850. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  22851. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  22852. _super.call(this, actionManager);
  22853. this.propertyPath = propertyPath;
  22854. this.value = value;
  22855. this.operator = operator;
  22856. this._target = this._getEffectiveTarget(target, this.propertyPath);
  22857. this._property = this._getProperty(this.propertyPath);
  22858. }
  22859. Object.defineProperty(ValueCondition, "IsEqual", {
  22860. get: function () {
  22861. return ValueCondition._IsEqual;
  22862. },
  22863. enumerable: true,
  22864. configurable: true
  22865. });
  22866. Object.defineProperty(ValueCondition, "IsDifferent", {
  22867. get: function () {
  22868. return ValueCondition._IsDifferent;
  22869. },
  22870. enumerable: true,
  22871. configurable: true
  22872. });
  22873. Object.defineProperty(ValueCondition, "IsGreater", {
  22874. get: function () {
  22875. return ValueCondition._IsGreater;
  22876. },
  22877. enumerable: true,
  22878. configurable: true
  22879. });
  22880. Object.defineProperty(ValueCondition, "IsLesser", {
  22881. get: function () {
  22882. return ValueCondition._IsLesser;
  22883. },
  22884. enumerable: true,
  22885. configurable: true
  22886. });
  22887. // Methods
  22888. ValueCondition.prototype.isValid = function () {
  22889. switch (this.operator) {
  22890. case ValueCondition.IsGreater:
  22891. return this._target[this._property] > this.value;
  22892. case ValueCondition.IsLesser:
  22893. return this._target[this._property] < this.value;
  22894. case ValueCondition.IsEqual:
  22895. case ValueCondition.IsDifferent:
  22896. var check;
  22897. if (this.value.equals) {
  22898. check = this.value.equals(this._target[this._property]);
  22899. }
  22900. else {
  22901. check = this.value === this._target[this._property];
  22902. }
  22903. return this.operator === ValueCondition.IsEqual ? check : !check;
  22904. }
  22905. return false;
  22906. };
  22907. // Statics
  22908. ValueCondition._IsEqual = 0;
  22909. ValueCondition._IsDifferent = 1;
  22910. ValueCondition._IsGreater = 2;
  22911. ValueCondition._IsLesser = 3;
  22912. return ValueCondition;
  22913. })(Condition);
  22914. BABYLON.ValueCondition = ValueCondition;
  22915. var PredicateCondition = (function (_super) {
  22916. __extends(PredicateCondition, _super);
  22917. function PredicateCondition(actionManager, predicate) {
  22918. _super.call(this, actionManager);
  22919. this.predicate = predicate;
  22920. }
  22921. PredicateCondition.prototype.isValid = function () {
  22922. return this.predicate();
  22923. };
  22924. return PredicateCondition;
  22925. })(Condition);
  22926. BABYLON.PredicateCondition = PredicateCondition;
  22927. var StateCondition = (function (_super) {
  22928. __extends(StateCondition, _super);
  22929. function StateCondition(actionManager, target, value) {
  22930. _super.call(this, actionManager);
  22931. this.value = value;
  22932. this._target = target;
  22933. }
  22934. // Methods
  22935. StateCondition.prototype.isValid = function () {
  22936. return this._target.state === this.value;
  22937. };
  22938. return StateCondition;
  22939. })(Condition);
  22940. BABYLON.StateCondition = StateCondition;
  22941. })(BABYLON || (BABYLON = {}));
  22942. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  22943. (function (BABYLON) {
  22944. var Action = (function () {
  22945. function Action(triggerOptions, condition) {
  22946. this.triggerOptions = triggerOptions;
  22947. if (triggerOptions.parameter) {
  22948. this.trigger = triggerOptions.trigger;
  22949. this._triggerParameter = triggerOptions.parameter;
  22950. }
  22951. else {
  22952. this.trigger = triggerOptions;
  22953. }
  22954. this._nextActiveAction = this;
  22955. this._condition = condition;
  22956. }
  22957. // Methods
  22958. Action.prototype._prepare = function () {
  22959. };
  22960. Action.prototype.getTriggerParameter = function () {
  22961. return this._triggerParameter;
  22962. };
  22963. Action.prototype._executeCurrent = function (evt) {
  22964. if (this._condition) {
  22965. var currentRenderId = this._actionManager.getScene().getRenderId();
  22966. // We cache the current evaluation for the current frame
  22967. if (this._condition._evaluationId === currentRenderId) {
  22968. if (!this._condition._currentResult) {
  22969. return;
  22970. }
  22971. }
  22972. else {
  22973. this._condition._evaluationId = currentRenderId;
  22974. if (!this._condition.isValid()) {
  22975. this._condition._currentResult = false;
  22976. return;
  22977. }
  22978. this._condition._currentResult = true;
  22979. }
  22980. }
  22981. this._nextActiveAction.execute(evt);
  22982. if (this._nextActiveAction._child) {
  22983. if (!this._nextActiveAction._child._actionManager) {
  22984. this._nextActiveAction._child._actionManager = this._actionManager;
  22985. }
  22986. this._nextActiveAction = this._nextActiveAction._child;
  22987. }
  22988. else {
  22989. this._nextActiveAction = this;
  22990. }
  22991. };
  22992. Action.prototype.execute = function (evt) {
  22993. };
  22994. Action.prototype.then = function (action) {
  22995. this._child = action;
  22996. action._actionManager = this._actionManager;
  22997. action._prepare();
  22998. return action;
  22999. };
  23000. Action.prototype._getProperty = function (propertyPath) {
  23001. return this._actionManager._getProperty(propertyPath);
  23002. };
  23003. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  23004. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23005. };
  23006. return Action;
  23007. })();
  23008. BABYLON.Action = Action;
  23009. })(BABYLON || (BABYLON = {}));
  23010. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  23011. (function (BABYLON) {
  23012. /**
  23013. * ActionEvent is the event beint sent when an action is triggered.
  23014. */
  23015. var ActionEvent = (function () {
  23016. /**
  23017. * @constructor
  23018. * @param source The mesh that triggered the action.
  23019. * @param pointerX the X mouse cursor position at the time of the event
  23020. * @param pointerY the Y mouse cursor position at the time of the event
  23021. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  23022. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  23023. */
  23024. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  23025. this.source = source;
  23026. this.pointerX = pointerX;
  23027. this.pointerY = pointerY;
  23028. this.meshUnderPointer = meshUnderPointer;
  23029. this.sourceEvent = sourceEvent;
  23030. }
  23031. /**
  23032. * Helper function to auto-create an ActionEvent from a source mesh.
  23033. * @param source the source mesh that triggered the event
  23034. * @param evt {Event} The original (browser) event
  23035. */
  23036. ActionEvent.CreateNew = function (source, evt) {
  23037. var scene = source.getScene();
  23038. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23039. };
  23040. /**
  23041. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  23042. * @param scene the scene where the event occurred
  23043. * @param evt {Event} The original (browser) event
  23044. */
  23045. ActionEvent.CreateNewFromScene = function (scene, evt) {
  23046. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23047. };
  23048. return ActionEvent;
  23049. })();
  23050. BABYLON.ActionEvent = ActionEvent;
  23051. /**
  23052. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  23053. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  23054. */
  23055. var ActionManager = (function () {
  23056. function ActionManager(scene) {
  23057. // Members
  23058. this.actions = new Array();
  23059. this._scene = scene;
  23060. scene._actionManagers.push(this);
  23061. }
  23062. Object.defineProperty(ActionManager, "NothingTrigger", {
  23063. get: function () {
  23064. return ActionManager._NothingTrigger;
  23065. },
  23066. enumerable: true,
  23067. configurable: true
  23068. });
  23069. Object.defineProperty(ActionManager, "OnPickTrigger", {
  23070. get: function () {
  23071. return ActionManager._OnPickTrigger;
  23072. },
  23073. enumerable: true,
  23074. configurable: true
  23075. });
  23076. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  23077. get: function () {
  23078. return ActionManager._OnLeftPickTrigger;
  23079. },
  23080. enumerable: true,
  23081. configurable: true
  23082. });
  23083. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  23084. get: function () {
  23085. return ActionManager._OnRightPickTrigger;
  23086. },
  23087. enumerable: true,
  23088. configurable: true
  23089. });
  23090. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  23091. get: function () {
  23092. return ActionManager._OnCenterPickTrigger;
  23093. },
  23094. enumerable: true,
  23095. configurable: true
  23096. });
  23097. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  23098. get: function () {
  23099. return ActionManager._OnPointerOverTrigger;
  23100. },
  23101. enumerable: true,
  23102. configurable: true
  23103. });
  23104. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  23105. get: function () {
  23106. return ActionManager._OnPointerOutTrigger;
  23107. },
  23108. enumerable: true,
  23109. configurable: true
  23110. });
  23111. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  23112. get: function () {
  23113. return ActionManager._OnEveryFrameTrigger;
  23114. },
  23115. enumerable: true,
  23116. configurable: true
  23117. });
  23118. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  23119. get: function () {
  23120. return ActionManager._OnIntersectionEnterTrigger;
  23121. },
  23122. enumerable: true,
  23123. configurable: true
  23124. });
  23125. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  23126. get: function () {
  23127. return ActionManager._OnIntersectionExitTrigger;
  23128. },
  23129. enumerable: true,
  23130. configurable: true
  23131. });
  23132. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  23133. get: function () {
  23134. return ActionManager._OnKeyDownTrigger;
  23135. },
  23136. enumerable: true,
  23137. configurable: true
  23138. });
  23139. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  23140. get: function () {
  23141. return ActionManager._OnKeyUpTrigger;
  23142. },
  23143. enumerable: true,
  23144. configurable: true
  23145. });
  23146. // Methods
  23147. ActionManager.prototype.dispose = function () {
  23148. var index = this._scene._actionManagers.indexOf(this);
  23149. if (index > -1) {
  23150. this._scene._actionManagers.splice(index, 1);
  23151. }
  23152. };
  23153. ActionManager.prototype.getScene = function () {
  23154. return this._scene;
  23155. };
  23156. /**
  23157. * Does this action manager handles actions of any of the given triggers
  23158. * @param {number[]} triggers - the triggers to be tested
  23159. * @return {boolean} whether one (or more) of the triggers is handeled
  23160. */
  23161. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  23162. for (var index = 0; index < this.actions.length; index++) {
  23163. var action = this.actions[index];
  23164. if (triggers.indexOf(action.trigger) > -1) {
  23165. return true;
  23166. }
  23167. }
  23168. return false;
  23169. };
  23170. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  23171. /**
  23172. * Does this action manager has pointer triggers
  23173. * @return {boolean} whether or not it has pointer triggers
  23174. */
  23175. get: function () {
  23176. for (var index = 0; index < this.actions.length; index++) {
  23177. var action = this.actions[index];
  23178. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  23179. return true;
  23180. }
  23181. }
  23182. return false;
  23183. },
  23184. enumerable: true,
  23185. configurable: true
  23186. });
  23187. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  23188. /**
  23189. * Does this action manager has pick triggers
  23190. * @return {boolean} whether or not it has pick triggers
  23191. */
  23192. get: function () {
  23193. for (var index = 0; index < this.actions.length; index++) {
  23194. var action = this.actions[index];
  23195. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  23196. return true;
  23197. }
  23198. }
  23199. return false;
  23200. },
  23201. enumerable: true,
  23202. configurable: true
  23203. });
  23204. /**
  23205. * Registers an action to this action manager
  23206. * @param {BABYLON.Action} action - the action to be registered
  23207. * @return {BABYLON.Action} the action amended (prepared) after registration
  23208. */
  23209. ActionManager.prototype.registerAction = function (action) {
  23210. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  23211. if (this.getScene().actionManager !== this) {
  23212. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  23213. return null;
  23214. }
  23215. }
  23216. this.actions.push(action);
  23217. action._actionManager = this;
  23218. action._prepare();
  23219. return action;
  23220. };
  23221. /**
  23222. * Process a specific trigger
  23223. * @param {number} trigger - the trigger to process
  23224. * @param evt {BABYLON.ActionEvent} the event details to be processed
  23225. */
  23226. ActionManager.prototype.processTrigger = function (trigger, evt) {
  23227. for (var index = 0; index < this.actions.length; index++) {
  23228. var action = this.actions[index];
  23229. if (action.trigger === trigger) {
  23230. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  23231. var parameter = action.getTriggerParameter();
  23232. if (parameter) {
  23233. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  23234. var actualkey = String.fromCharCode(unicode).toLowerCase();
  23235. if (actualkey !== parameter.toLowerCase()) {
  23236. continue;
  23237. }
  23238. }
  23239. }
  23240. action._executeCurrent(evt);
  23241. }
  23242. }
  23243. };
  23244. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  23245. var properties = propertyPath.split(".");
  23246. for (var index = 0; index < properties.length - 1; index++) {
  23247. target = target[properties[index]];
  23248. }
  23249. return target;
  23250. };
  23251. ActionManager.prototype._getProperty = function (propertyPath) {
  23252. var properties = propertyPath.split(".");
  23253. return properties[properties.length - 1];
  23254. };
  23255. // Statics
  23256. ActionManager._NothingTrigger = 0;
  23257. ActionManager._OnPickTrigger = 1;
  23258. ActionManager._OnLeftPickTrigger = 2;
  23259. ActionManager._OnRightPickTrigger = 3;
  23260. ActionManager._OnCenterPickTrigger = 4;
  23261. ActionManager._OnPointerOverTrigger = 5;
  23262. ActionManager._OnPointerOutTrigger = 6;
  23263. ActionManager._OnEveryFrameTrigger = 7;
  23264. ActionManager._OnIntersectionEnterTrigger = 8;
  23265. ActionManager._OnIntersectionExitTrigger = 9;
  23266. ActionManager._OnKeyDownTrigger = 10;
  23267. ActionManager._OnKeyUpTrigger = 11;
  23268. return ActionManager;
  23269. })();
  23270. BABYLON.ActionManager = ActionManager;
  23271. })(BABYLON || (BABYLON = {}));
  23272. //# sourceMappingURL=babylon.actionManager.js.map
  23273. var BABYLON;
  23274. (function (BABYLON) {
  23275. var InterpolateValueAction = (function (_super) {
  23276. __extends(InterpolateValueAction, _super);
  23277. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  23278. if (duration === void 0) { duration = 1000; }
  23279. _super.call(this, triggerOptions, condition);
  23280. this.propertyPath = propertyPath;
  23281. this.value = value;
  23282. this.duration = duration;
  23283. this.stopOtherAnimations = stopOtherAnimations;
  23284. this._target = target;
  23285. }
  23286. InterpolateValueAction.prototype._prepare = function () {
  23287. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23288. this._property = this._getProperty(this.propertyPath);
  23289. };
  23290. InterpolateValueAction.prototype.execute = function () {
  23291. var scene = this._actionManager.getScene();
  23292. var keys = [
  23293. {
  23294. frame: 0,
  23295. value: this._target[this._property]
  23296. },
  23297. {
  23298. frame: 100,
  23299. value: this.value
  23300. }
  23301. ];
  23302. var dataType;
  23303. if (typeof this.value === "number") {
  23304. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  23305. }
  23306. else if (this.value instanceof BABYLON.Color3) {
  23307. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  23308. }
  23309. else if (this.value instanceof BABYLON.Vector3) {
  23310. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  23311. }
  23312. else if (this.value instanceof BABYLON.Matrix) {
  23313. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  23314. }
  23315. else if (this.value instanceof BABYLON.Quaternion) {
  23316. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  23317. }
  23318. else {
  23319. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  23320. return;
  23321. }
  23322. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  23323. animation.setKeys(keys);
  23324. if (this.stopOtherAnimations) {
  23325. scene.stopAnimation(this._target);
  23326. }
  23327. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  23328. };
  23329. return InterpolateValueAction;
  23330. })(BABYLON.Action);
  23331. BABYLON.InterpolateValueAction = InterpolateValueAction;
  23332. })(BABYLON || (BABYLON = {}));
  23333. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  23334. var BABYLON;
  23335. (function (BABYLON) {
  23336. var SwitchBooleanAction = (function (_super) {
  23337. __extends(SwitchBooleanAction, _super);
  23338. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  23339. _super.call(this, triggerOptions, condition);
  23340. this.propertyPath = propertyPath;
  23341. this._target = target;
  23342. }
  23343. SwitchBooleanAction.prototype._prepare = function () {
  23344. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23345. this._property = this._getProperty(this.propertyPath);
  23346. };
  23347. SwitchBooleanAction.prototype.execute = function () {
  23348. this._target[this._property] = !this._target[this._property];
  23349. };
  23350. return SwitchBooleanAction;
  23351. })(BABYLON.Action);
  23352. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  23353. var SetStateAction = (function (_super) {
  23354. __extends(SetStateAction, _super);
  23355. function SetStateAction(triggerOptions, target, value, condition) {
  23356. _super.call(this, triggerOptions, condition);
  23357. this.value = value;
  23358. this._target = target;
  23359. }
  23360. SetStateAction.prototype.execute = function () {
  23361. this._target.state = this.value;
  23362. };
  23363. return SetStateAction;
  23364. })(BABYLON.Action);
  23365. BABYLON.SetStateAction = SetStateAction;
  23366. var SetValueAction = (function (_super) {
  23367. __extends(SetValueAction, _super);
  23368. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  23369. _super.call(this, triggerOptions, condition);
  23370. this.propertyPath = propertyPath;
  23371. this.value = value;
  23372. this._target = target;
  23373. }
  23374. SetValueAction.prototype._prepare = function () {
  23375. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23376. this._property = this._getProperty(this.propertyPath);
  23377. };
  23378. SetValueAction.prototype.execute = function () {
  23379. this._target[this._property] = this.value;
  23380. };
  23381. return SetValueAction;
  23382. })(BABYLON.Action);
  23383. BABYLON.SetValueAction = SetValueAction;
  23384. var IncrementValueAction = (function (_super) {
  23385. __extends(IncrementValueAction, _super);
  23386. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  23387. _super.call(this, triggerOptions, condition);
  23388. this.propertyPath = propertyPath;
  23389. this.value = value;
  23390. this._target = target;
  23391. }
  23392. IncrementValueAction.prototype._prepare = function () {
  23393. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23394. this._property = this._getProperty(this.propertyPath);
  23395. if (typeof this._target[this._property] !== "number") {
  23396. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  23397. }
  23398. };
  23399. IncrementValueAction.prototype.execute = function () {
  23400. this._target[this._property] += this.value;
  23401. };
  23402. return IncrementValueAction;
  23403. })(BABYLON.Action);
  23404. BABYLON.IncrementValueAction = IncrementValueAction;
  23405. var PlayAnimationAction = (function (_super) {
  23406. __extends(PlayAnimationAction, _super);
  23407. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  23408. _super.call(this, triggerOptions, condition);
  23409. this.from = from;
  23410. this.to = to;
  23411. this.loop = loop;
  23412. this._target = target;
  23413. }
  23414. PlayAnimationAction.prototype._prepare = function () {
  23415. };
  23416. PlayAnimationAction.prototype.execute = function () {
  23417. var scene = this._actionManager.getScene();
  23418. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  23419. };
  23420. return PlayAnimationAction;
  23421. })(BABYLON.Action);
  23422. BABYLON.PlayAnimationAction = PlayAnimationAction;
  23423. var StopAnimationAction = (function (_super) {
  23424. __extends(StopAnimationAction, _super);
  23425. function StopAnimationAction(triggerOptions, target, condition) {
  23426. _super.call(this, triggerOptions, condition);
  23427. this._target = target;
  23428. }
  23429. StopAnimationAction.prototype._prepare = function () {
  23430. };
  23431. StopAnimationAction.prototype.execute = function () {
  23432. var scene = this._actionManager.getScene();
  23433. scene.stopAnimation(this._target);
  23434. };
  23435. return StopAnimationAction;
  23436. })(BABYLON.Action);
  23437. BABYLON.StopAnimationAction = StopAnimationAction;
  23438. var DoNothingAction = (function (_super) {
  23439. __extends(DoNothingAction, _super);
  23440. function DoNothingAction(triggerOptions, condition) {
  23441. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  23442. _super.call(this, triggerOptions, condition);
  23443. }
  23444. DoNothingAction.prototype.execute = function () {
  23445. };
  23446. return DoNothingAction;
  23447. })(BABYLON.Action);
  23448. BABYLON.DoNothingAction = DoNothingAction;
  23449. var CombineAction = (function (_super) {
  23450. __extends(CombineAction, _super);
  23451. function CombineAction(triggerOptions, children, condition) {
  23452. _super.call(this, triggerOptions, condition);
  23453. this.children = children;
  23454. }
  23455. CombineAction.prototype._prepare = function () {
  23456. for (var index = 0; index < this.children.length; index++) {
  23457. this.children[index]._actionManager = this._actionManager;
  23458. this.children[index]._prepare();
  23459. }
  23460. };
  23461. CombineAction.prototype.execute = function (evt) {
  23462. for (var index = 0; index < this.children.length; index++) {
  23463. this.children[index].execute(evt);
  23464. }
  23465. };
  23466. return CombineAction;
  23467. })(BABYLON.Action);
  23468. BABYLON.CombineAction = CombineAction;
  23469. var ExecuteCodeAction = (function (_super) {
  23470. __extends(ExecuteCodeAction, _super);
  23471. function ExecuteCodeAction(triggerOptions, func, condition) {
  23472. _super.call(this, triggerOptions, condition);
  23473. this.func = func;
  23474. }
  23475. ExecuteCodeAction.prototype.execute = function (evt) {
  23476. this.func(evt);
  23477. };
  23478. return ExecuteCodeAction;
  23479. })(BABYLON.Action);
  23480. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  23481. var SetParentAction = (function (_super) {
  23482. __extends(SetParentAction, _super);
  23483. function SetParentAction(triggerOptions, target, parent, condition) {
  23484. _super.call(this, triggerOptions, condition);
  23485. this._target = target;
  23486. this._parent = parent;
  23487. }
  23488. SetParentAction.prototype._prepare = function () {
  23489. };
  23490. SetParentAction.prototype.execute = function () {
  23491. if (this._target.parent === this._parent) {
  23492. return;
  23493. }
  23494. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  23495. invertParentWorldMatrix.invert();
  23496. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  23497. this._target.parent = this._parent;
  23498. };
  23499. return SetParentAction;
  23500. })(BABYLON.Action);
  23501. BABYLON.SetParentAction = SetParentAction;
  23502. var PlaySoundAction = (function (_super) {
  23503. __extends(PlaySoundAction, _super);
  23504. function PlaySoundAction(triggerOptions, sound, condition) {
  23505. _super.call(this, triggerOptions, condition);
  23506. this._sound = sound;
  23507. }
  23508. PlaySoundAction.prototype._prepare = function () {
  23509. };
  23510. PlaySoundAction.prototype.execute = function () {
  23511. if (this._sound !== undefined)
  23512. this._sound.play();
  23513. };
  23514. return PlaySoundAction;
  23515. })(BABYLON.Action);
  23516. BABYLON.PlaySoundAction = PlaySoundAction;
  23517. var StopSoundAction = (function (_super) {
  23518. __extends(StopSoundAction, _super);
  23519. function StopSoundAction(triggerOptions, sound, condition) {
  23520. _super.call(this, triggerOptions, condition);
  23521. this._sound = sound;
  23522. }
  23523. StopSoundAction.prototype._prepare = function () {
  23524. };
  23525. StopSoundAction.prototype.execute = function () {
  23526. if (this._sound !== undefined)
  23527. this._sound.stop();
  23528. };
  23529. return StopSoundAction;
  23530. })(BABYLON.Action);
  23531. BABYLON.StopSoundAction = StopSoundAction;
  23532. })(BABYLON || (BABYLON = {}));
  23533. //# sourceMappingURL=babylon.directActions.js.map
  23534. var BABYLON;
  23535. (function (BABYLON) {
  23536. var Geometry = (function () {
  23537. function Geometry(id, scene, vertexData, updatable, mesh) {
  23538. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23539. this._totalVertices = 0;
  23540. this._indices = [];
  23541. this.id = id;
  23542. this._engine = scene.getEngine();
  23543. this._meshes = [];
  23544. this._scene = scene;
  23545. // vertexData
  23546. if (vertexData) {
  23547. this.setAllVerticesData(vertexData, updatable);
  23548. }
  23549. else {
  23550. this._totalVertices = 0;
  23551. this._indices = [];
  23552. }
  23553. // applyToMesh
  23554. if (mesh) {
  23555. this.applyToMesh(mesh);
  23556. mesh.computeWorldMatrix(true);
  23557. }
  23558. }
  23559. Geometry.prototype.getScene = function () {
  23560. return this._scene;
  23561. };
  23562. Geometry.prototype.getEngine = function () {
  23563. return this._engine;
  23564. };
  23565. Geometry.prototype.isReady = function () {
  23566. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  23567. };
  23568. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  23569. vertexData.applyToGeometry(this, updatable);
  23570. };
  23571. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23572. this._vertexBuffers = this._vertexBuffers || {};
  23573. if (this._vertexBuffers[kind]) {
  23574. this._vertexBuffers[kind].dispose();
  23575. }
  23576. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  23577. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23578. stride = this._vertexBuffers[kind].getStrideSize();
  23579. this._totalVertices = data.length / stride;
  23580. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23581. var meshes = this._meshes;
  23582. var numOfMeshes = meshes.length;
  23583. for (var index = 0; index < numOfMeshes; index++) {
  23584. var mesh = meshes[index];
  23585. mesh._resetPointsArrayCache();
  23586. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23587. mesh._createGlobalSubMesh();
  23588. mesh.computeWorldMatrix(true);
  23589. }
  23590. }
  23591. };
  23592. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  23593. var vertexBuffer = this.getVertexBuffer(kind);
  23594. if (!vertexBuffer) {
  23595. return;
  23596. }
  23597. vertexBuffer.updateDirectly(data, offset);
  23598. };
  23599. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  23600. var vertexBuffer = this.getVertexBuffer(kind);
  23601. if (!vertexBuffer) {
  23602. return;
  23603. }
  23604. vertexBuffer.update(data);
  23605. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23606. var extend;
  23607. var stride = vertexBuffer.getStrideSize();
  23608. this._totalVertices = data.length / stride;
  23609. if (updateExtends) {
  23610. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23611. }
  23612. var meshes = this._meshes;
  23613. var numOfMeshes = meshes.length;
  23614. for (var index = 0; index < numOfMeshes; index++) {
  23615. var mesh = meshes[index];
  23616. mesh._resetPointsArrayCache();
  23617. if (updateExtends) {
  23618. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23619. }
  23620. }
  23621. }
  23622. };
  23623. Geometry.prototype.getTotalVertices = function () {
  23624. if (!this.isReady()) {
  23625. return 0;
  23626. }
  23627. return this._totalVertices;
  23628. };
  23629. Geometry.prototype.getVerticesData = function (kind) {
  23630. var vertexBuffer = this.getVertexBuffer(kind);
  23631. if (!vertexBuffer) {
  23632. return null;
  23633. }
  23634. return vertexBuffer.getData();
  23635. };
  23636. Geometry.prototype.getVertexBuffer = function (kind) {
  23637. if (!this.isReady()) {
  23638. return null;
  23639. }
  23640. return this._vertexBuffers[kind];
  23641. };
  23642. Geometry.prototype.getVertexBuffers = function () {
  23643. if (!this.isReady()) {
  23644. return null;
  23645. }
  23646. return this._vertexBuffers;
  23647. };
  23648. Geometry.prototype.isVerticesDataPresent = function (kind) {
  23649. if (!this._vertexBuffers) {
  23650. if (this._delayInfo) {
  23651. return this._delayInfo.indexOf(kind) !== -1;
  23652. }
  23653. return false;
  23654. }
  23655. return this._vertexBuffers[kind] !== undefined;
  23656. };
  23657. Geometry.prototype.getVerticesDataKinds = function () {
  23658. var result = [];
  23659. if (!this._vertexBuffers && this._delayInfo) {
  23660. for (var kind in this._delayInfo) {
  23661. result.push(kind);
  23662. }
  23663. }
  23664. else {
  23665. for (kind in this._vertexBuffers) {
  23666. result.push(kind);
  23667. }
  23668. }
  23669. return result;
  23670. };
  23671. Geometry.prototype.setIndices = function (indices, totalVertices) {
  23672. if (this._indexBuffer) {
  23673. this._engine._releaseBuffer(this._indexBuffer);
  23674. }
  23675. this._indices = indices;
  23676. if (this._meshes.length !== 0 && this._indices) {
  23677. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23678. }
  23679. if (totalVertices !== undefined) {
  23680. this._totalVertices = totalVertices;
  23681. }
  23682. var meshes = this._meshes;
  23683. var numOfMeshes = meshes.length;
  23684. for (var index = 0; index < numOfMeshes; index++) {
  23685. meshes[index]._createGlobalSubMesh();
  23686. }
  23687. };
  23688. Geometry.prototype.getTotalIndices = function () {
  23689. if (!this.isReady()) {
  23690. return 0;
  23691. }
  23692. return this._indices.length;
  23693. };
  23694. Geometry.prototype.getIndices = function () {
  23695. if (!this.isReady()) {
  23696. return null;
  23697. }
  23698. return this._indices;
  23699. };
  23700. Geometry.prototype.getIndexBuffer = function () {
  23701. if (!this.isReady()) {
  23702. return null;
  23703. }
  23704. return this._indexBuffer;
  23705. };
  23706. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  23707. var meshes = this._meshes;
  23708. var index = meshes.indexOf(mesh);
  23709. if (index === -1) {
  23710. return;
  23711. }
  23712. for (var kind in this._vertexBuffers) {
  23713. this._vertexBuffers[kind].dispose();
  23714. }
  23715. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  23716. this._indexBuffer = null;
  23717. }
  23718. meshes.splice(index, 1);
  23719. mesh._geometry = null;
  23720. if (meshes.length === 0 && shouldDispose) {
  23721. this.dispose();
  23722. }
  23723. };
  23724. Geometry.prototype.applyToMesh = function (mesh) {
  23725. if (mesh._geometry === this) {
  23726. return;
  23727. }
  23728. var previousGeometry = mesh._geometry;
  23729. if (previousGeometry) {
  23730. previousGeometry.releaseForMesh(mesh);
  23731. }
  23732. var meshes = this._meshes;
  23733. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  23734. mesh._geometry = this;
  23735. this._scene.pushGeometry(this);
  23736. meshes.push(mesh);
  23737. if (this.isReady()) {
  23738. this._applyToMesh(mesh);
  23739. }
  23740. else {
  23741. mesh._boundingInfo = this._boundingInfo;
  23742. }
  23743. };
  23744. Geometry.prototype._applyToMesh = function (mesh) {
  23745. var numOfMeshes = this._meshes.length;
  23746. for (var kind in this._vertexBuffers) {
  23747. if (numOfMeshes === 1) {
  23748. this._vertexBuffers[kind].create();
  23749. }
  23750. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  23751. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23752. mesh._resetPointsArrayCache();
  23753. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  23754. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23755. mesh._createGlobalSubMesh();
  23756. //bounding info was just created again, world matrix should be applied again.
  23757. mesh._updateBoundingInfo();
  23758. }
  23759. }
  23760. // indexBuffer
  23761. if (numOfMeshes === 1 && this._indices) {
  23762. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23763. }
  23764. if (this._indexBuffer) {
  23765. this._indexBuffer.references = numOfMeshes;
  23766. }
  23767. };
  23768. Geometry.prototype.load = function (scene, onLoaded) {
  23769. var _this = this;
  23770. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23771. return;
  23772. }
  23773. if (this.isReady()) {
  23774. if (onLoaded) {
  23775. onLoaded();
  23776. }
  23777. return;
  23778. }
  23779. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23780. scene._addPendingData(this);
  23781. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23782. _this._delayLoadingFunction(JSON.parse(data), _this);
  23783. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23784. _this._delayInfo = [];
  23785. scene._removePendingData(_this);
  23786. var meshes = _this._meshes;
  23787. var numOfMeshes = meshes.length;
  23788. for (var index = 0; index < numOfMeshes; index++) {
  23789. _this._applyToMesh(meshes[index]);
  23790. }
  23791. if (onLoaded) {
  23792. onLoaded();
  23793. }
  23794. }, function () {
  23795. }, scene.database);
  23796. };
  23797. Geometry.prototype.dispose = function () {
  23798. var meshes = this._meshes;
  23799. var numOfMeshes = meshes.length;
  23800. var index;
  23801. for (index = 0; index < numOfMeshes; index++) {
  23802. this.releaseForMesh(meshes[index]);
  23803. }
  23804. this._meshes = [];
  23805. for (var kind in this._vertexBuffers) {
  23806. this._vertexBuffers[kind].dispose();
  23807. }
  23808. this._vertexBuffers = [];
  23809. this._totalVertices = 0;
  23810. if (this._indexBuffer) {
  23811. this._engine._releaseBuffer(this._indexBuffer);
  23812. }
  23813. this._indexBuffer = null;
  23814. this._indices = [];
  23815. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23816. this.delayLoadingFile = null;
  23817. this._delayLoadingFunction = null;
  23818. this._delayInfo = [];
  23819. this._boundingInfo = null; // todo: .dispose()
  23820. var geometries = this._scene.getGeometries();
  23821. index = geometries.indexOf(this);
  23822. if (index > -1) {
  23823. geometries.splice(index, 1);
  23824. }
  23825. };
  23826. Geometry.prototype.copy = function (id) {
  23827. var vertexData = new BABYLON.VertexData();
  23828. vertexData.indices = [];
  23829. var indices = this.getIndices();
  23830. for (var index = 0; index < indices.length; index++) {
  23831. vertexData.indices.push(indices[index]);
  23832. }
  23833. var updatable = false;
  23834. var stopChecking = false;
  23835. for (var kind in this._vertexBuffers) {
  23836. vertexData.set(this.getVerticesData(kind), kind);
  23837. if (!stopChecking) {
  23838. updatable = this.getVertexBuffer(kind).isUpdatable();
  23839. stopChecking = !updatable;
  23840. }
  23841. }
  23842. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  23843. geometry.delayLoadState = this.delayLoadState;
  23844. geometry.delayLoadingFile = this.delayLoadingFile;
  23845. geometry._delayLoadingFunction = this._delayLoadingFunction;
  23846. for (kind in this._delayInfo) {
  23847. geometry._delayInfo = geometry._delayInfo || [];
  23848. geometry._delayInfo.push(kind);
  23849. }
  23850. // Bounding info
  23851. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  23852. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23853. return geometry;
  23854. };
  23855. // Statics
  23856. Geometry.ExtractFromMesh = function (mesh, id) {
  23857. var geometry = mesh._geometry;
  23858. if (!geometry) {
  23859. return null;
  23860. }
  23861. return geometry.copy(id);
  23862. };
  23863. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  23864. // be aware Math.random() could cause collisions
  23865. Geometry.RandomId = function () {
  23866. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  23867. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  23868. return v.toString(16);
  23869. });
  23870. };
  23871. return Geometry;
  23872. })();
  23873. BABYLON.Geometry = Geometry;
  23874. /////// Primitives //////////////////////////////////////////////
  23875. var Geometry;
  23876. (function (Geometry) {
  23877. var Primitives;
  23878. (function (Primitives) {
  23879. /// Abstract class
  23880. var _Primitive = (function (_super) {
  23881. __extends(_Primitive, _super);
  23882. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  23883. this._beingRegenerated = true;
  23884. this._canBeRegenerated = canBeRegenerated;
  23885. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  23886. this._beingRegenerated = false;
  23887. }
  23888. _Primitive.prototype.canBeRegenerated = function () {
  23889. return this._canBeRegenerated;
  23890. };
  23891. _Primitive.prototype.regenerate = function () {
  23892. if (!this._canBeRegenerated) {
  23893. return;
  23894. }
  23895. this._beingRegenerated = true;
  23896. this.setAllVerticesData(this._regenerateVertexData(), false);
  23897. this._beingRegenerated = false;
  23898. };
  23899. _Primitive.prototype.asNewGeometry = function (id) {
  23900. return _super.prototype.copy.call(this, id);
  23901. };
  23902. // overrides
  23903. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  23904. if (!this._beingRegenerated) {
  23905. return;
  23906. }
  23907. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  23908. };
  23909. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  23910. if (!this._beingRegenerated) {
  23911. return;
  23912. }
  23913. _super.prototype.setVerticesData.call(this, kind, data, false);
  23914. };
  23915. // to override
  23916. // protected
  23917. _Primitive.prototype._regenerateVertexData = function () {
  23918. throw new Error("Abstract method");
  23919. };
  23920. _Primitive.prototype.copy = function (id) {
  23921. throw new Error("Must be overriden in sub-classes.");
  23922. };
  23923. return _Primitive;
  23924. })(Geometry);
  23925. Primitives._Primitive = _Primitive;
  23926. var Box = (function (_super) {
  23927. __extends(Box, _super);
  23928. function Box(id, scene, size, canBeRegenerated, mesh) {
  23929. this.size = size;
  23930. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23931. }
  23932. Box.prototype._regenerateVertexData = function () {
  23933. return BABYLON.VertexData.CreateBox(this.size);
  23934. };
  23935. Box.prototype.copy = function (id) {
  23936. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23937. };
  23938. return Box;
  23939. })(_Primitive);
  23940. Primitives.Box = Box;
  23941. var Sphere = (function (_super) {
  23942. __extends(Sphere, _super);
  23943. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  23944. this.segments = segments;
  23945. this.diameter = diameter;
  23946. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23947. }
  23948. Sphere.prototype._regenerateVertexData = function () {
  23949. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  23950. };
  23951. Sphere.prototype.copy = function (id) {
  23952. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  23953. };
  23954. return Sphere;
  23955. })(_Primitive);
  23956. Primitives.Sphere = Sphere;
  23957. var Cylinder = (function (_super) {
  23958. __extends(Cylinder, _super);
  23959. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  23960. if (subdivisions === void 0) { subdivisions = 1; }
  23961. this.height = height;
  23962. this.diameterTop = diameterTop;
  23963. this.diameterBottom = diameterBottom;
  23964. this.tessellation = tessellation;
  23965. this.subdivisions = subdivisions;
  23966. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23967. }
  23968. Cylinder.prototype._regenerateVertexData = function () {
  23969. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  23970. };
  23971. Cylinder.prototype.copy = function (id) {
  23972. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  23973. };
  23974. return Cylinder;
  23975. })(_Primitive);
  23976. Primitives.Cylinder = Cylinder;
  23977. var Torus = (function (_super) {
  23978. __extends(Torus, _super);
  23979. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  23980. this.diameter = diameter;
  23981. this.thickness = thickness;
  23982. this.tessellation = tessellation;
  23983. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23984. }
  23985. Torus.prototype._regenerateVertexData = function () {
  23986. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  23987. };
  23988. Torus.prototype.copy = function (id) {
  23989. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  23990. };
  23991. return Torus;
  23992. })(_Primitive);
  23993. Primitives.Torus = Torus;
  23994. var Ground = (function (_super) {
  23995. __extends(Ground, _super);
  23996. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  23997. this.width = width;
  23998. this.height = height;
  23999. this.subdivisions = subdivisions;
  24000. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24001. }
  24002. Ground.prototype._regenerateVertexData = function () {
  24003. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  24004. };
  24005. Ground.prototype.copy = function (id) {
  24006. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  24007. };
  24008. return Ground;
  24009. })(_Primitive);
  24010. Primitives.Ground = Ground;
  24011. var TiledGround = (function (_super) {
  24012. __extends(TiledGround, _super);
  24013. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  24014. this.xmin = xmin;
  24015. this.zmin = zmin;
  24016. this.xmax = xmax;
  24017. this.zmax = zmax;
  24018. this.subdivisions = subdivisions;
  24019. this.precision = precision;
  24020. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24021. }
  24022. TiledGround.prototype._regenerateVertexData = function () {
  24023. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  24024. };
  24025. TiledGround.prototype.copy = function (id) {
  24026. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  24027. };
  24028. return TiledGround;
  24029. })(_Primitive);
  24030. Primitives.TiledGround = TiledGround;
  24031. var Plane = (function (_super) {
  24032. __extends(Plane, _super);
  24033. function Plane(id, scene, size, canBeRegenerated, mesh) {
  24034. this.size = size;
  24035. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24036. }
  24037. Plane.prototype._regenerateVertexData = function () {
  24038. return BABYLON.VertexData.CreatePlane(this.size);
  24039. };
  24040. Plane.prototype.copy = function (id) {
  24041. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  24042. };
  24043. return Plane;
  24044. })(_Primitive);
  24045. Primitives.Plane = Plane;
  24046. var TorusKnot = (function (_super) {
  24047. __extends(TorusKnot, _super);
  24048. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  24049. this.radius = radius;
  24050. this.tube = tube;
  24051. this.radialSegments = radialSegments;
  24052. this.tubularSegments = tubularSegments;
  24053. this.p = p;
  24054. this.q = q;
  24055. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24056. }
  24057. TorusKnot.prototype._regenerateVertexData = function () {
  24058. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  24059. };
  24060. TorusKnot.prototype.copy = function (id) {
  24061. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  24062. };
  24063. return TorusKnot;
  24064. })(_Primitive);
  24065. Primitives.TorusKnot = TorusKnot;
  24066. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  24067. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  24068. })(BABYLON || (BABYLON = {}));
  24069. //# sourceMappingURL=babylon.geometry.js.map
  24070. var BABYLON;
  24071. (function (BABYLON) {
  24072. var Gamepads = (function () {
  24073. function Gamepads(ongamedpadconnected) {
  24074. var _this = this;
  24075. this.babylonGamepads = [];
  24076. this.oneGamepadConnected = false;
  24077. this.isMonitoring = false;
  24078. this.gamepadEventSupported = 'GamepadEvent' in window;
  24079. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  24080. 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=";
  24081. this._callbackGamepadConnected = ongamedpadconnected;
  24082. if (this.gamepadSupportAvailable) {
  24083. // Checking if the gamepad connected event is supported (like in Firefox)
  24084. if (this.gamepadEventSupported) {
  24085. window.addEventListener('gamepadconnected', function (evt) {
  24086. _this._onGamepadConnected(evt);
  24087. }, false);
  24088. window.addEventListener('gamepaddisconnected', function (evt) {
  24089. _this._onGamepadDisconnected(evt);
  24090. }, false);
  24091. }
  24092. else {
  24093. this._startMonitoringGamepads();
  24094. }
  24095. if (!this.oneGamepadConnected) {
  24096. this._insertGamepadDOMInstructions();
  24097. }
  24098. }
  24099. else {
  24100. this._insertGamepadDOMNotSupported();
  24101. }
  24102. }
  24103. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  24104. Gamepads.gamepadDOMInfo = document.createElement("div");
  24105. var buttonAImage = document.createElement("img");
  24106. buttonAImage.src = this.buttonADataURL;
  24107. var spanMessage = document.createElement("span");
  24108. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  24109. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  24110. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24111. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24112. Gamepads.gamepadDOMInfo.style.width = "100%";
  24113. Gamepads.gamepadDOMInfo.style.height = "48px";
  24114. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24115. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24116. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24117. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24118. buttonAImage.style.position = "relative";
  24119. buttonAImage.style.bottom = "8px";
  24120. spanMessage.style.position = "relative";
  24121. spanMessage.style.fontSize = "32px";
  24122. spanMessage.style.bottom = "32px";
  24123. spanMessage.style.color = "green";
  24124. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24125. };
  24126. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  24127. Gamepads.gamepadDOMInfo = document.createElement("div");
  24128. var spanMessage = document.createElement("span");
  24129. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  24130. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24131. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24132. Gamepads.gamepadDOMInfo.style.width = "100%";
  24133. Gamepads.gamepadDOMInfo.style.height = "40px";
  24134. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24135. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24136. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24137. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24138. spanMessage.style.position = "relative";
  24139. spanMessage.style.fontSize = "32px";
  24140. spanMessage.style.color = "red";
  24141. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24142. };
  24143. Gamepads.prototype.dispose = function () {
  24144. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24145. };
  24146. Gamepads.prototype._onGamepadConnected = function (evt) {
  24147. var newGamepad = this._addNewGamepad(evt.gamepad);
  24148. if (this._callbackGamepadConnected)
  24149. this._callbackGamepadConnected(newGamepad);
  24150. this._startMonitoringGamepads();
  24151. };
  24152. Gamepads.prototype._addNewGamepad = function (gamepad) {
  24153. if (!this.oneGamepadConnected) {
  24154. this.oneGamepadConnected = true;
  24155. if (Gamepads.gamepadDOMInfo) {
  24156. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24157. Gamepads.gamepadDOMInfo = null;
  24158. }
  24159. }
  24160. var newGamepad;
  24161. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  24162. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  24163. }
  24164. else {
  24165. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  24166. }
  24167. this.babylonGamepads.push(newGamepad);
  24168. return newGamepad;
  24169. };
  24170. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  24171. for (var i in this.babylonGamepads) {
  24172. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  24173. this.babylonGamepads.splice(i, 1);
  24174. break;
  24175. }
  24176. }
  24177. // If no gamepads are left, stop the polling loop.
  24178. if (this.babylonGamepads.length == 0) {
  24179. this._stopMonitoringGamepads();
  24180. }
  24181. };
  24182. Gamepads.prototype._startMonitoringGamepads = function () {
  24183. if (!this.isMonitoring) {
  24184. this.isMonitoring = true;
  24185. this._checkGamepadsStatus();
  24186. }
  24187. };
  24188. Gamepads.prototype._stopMonitoringGamepads = function () {
  24189. this.isMonitoring = false;
  24190. };
  24191. Gamepads.prototype._checkGamepadsStatus = function () {
  24192. var _this = this;
  24193. // updating gamepad objects
  24194. this._updateGamepadObjects();
  24195. for (var i in this.babylonGamepads) {
  24196. this.babylonGamepads[i].update();
  24197. }
  24198. if (this.isMonitoring) {
  24199. if (window.requestAnimationFrame) {
  24200. window.requestAnimationFrame(function () {
  24201. _this._checkGamepadsStatus();
  24202. });
  24203. }
  24204. else if (window.mozRequestAnimationFrame) {
  24205. window.mozRequestAnimationFrame(function () {
  24206. _this._checkGamepadsStatus();
  24207. });
  24208. }
  24209. else if (window.webkitRequestAnimationFrame) {
  24210. window.webkitRequestAnimationFrame(function () {
  24211. _this._checkGamepadsStatus();
  24212. });
  24213. }
  24214. }
  24215. };
  24216. // This function is called only on Chrome, which does not yet support
  24217. // connection/disconnection events, but requires you to monitor
  24218. // an array for changes.
  24219. Gamepads.prototype._updateGamepadObjects = function () {
  24220. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  24221. for (var i = 0; i < gamepads.length; i++) {
  24222. if (gamepads[i]) {
  24223. if (!(gamepads[i].index in this.babylonGamepads)) {
  24224. var newGamepad = this._addNewGamepad(gamepads[i]);
  24225. if (this._callbackGamepadConnected) {
  24226. this._callbackGamepadConnected(newGamepad);
  24227. }
  24228. }
  24229. else {
  24230. this.babylonGamepads[i].browserGamepad = gamepads[i];
  24231. }
  24232. }
  24233. }
  24234. };
  24235. return Gamepads;
  24236. })();
  24237. BABYLON.Gamepads = Gamepads;
  24238. var StickValues = (function () {
  24239. function StickValues(x, y) {
  24240. this.x = x;
  24241. this.y = y;
  24242. }
  24243. return StickValues;
  24244. })();
  24245. BABYLON.StickValues = StickValues;
  24246. var Gamepad = (function () {
  24247. function Gamepad(id, index, browserGamepad) {
  24248. this.id = id;
  24249. this.index = index;
  24250. this.browserGamepad = browserGamepad;
  24251. if (this.browserGamepad.axes.length >= 2) {
  24252. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24253. }
  24254. if (this.browserGamepad.axes.length >= 4) {
  24255. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24256. }
  24257. }
  24258. Gamepad.prototype.onleftstickchanged = function (callback) {
  24259. this._onleftstickchanged = callback;
  24260. };
  24261. Gamepad.prototype.onrightstickchanged = function (callback) {
  24262. this._onrightstickchanged = callback;
  24263. };
  24264. Object.defineProperty(Gamepad.prototype, "leftStick", {
  24265. get: function () {
  24266. return this._leftStick;
  24267. },
  24268. set: function (newValues) {
  24269. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  24270. this._onleftstickchanged(newValues);
  24271. }
  24272. this._leftStick = newValues;
  24273. },
  24274. enumerable: true,
  24275. configurable: true
  24276. });
  24277. Object.defineProperty(Gamepad.prototype, "rightStick", {
  24278. get: function () {
  24279. return this._rightStick;
  24280. },
  24281. set: function (newValues) {
  24282. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  24283. this._onrightstickchanged(newValues);
  24284. }
  24285. this._rightStick = newValues;
  24286. },
  24287. enumerable: true,
  24288. configurable: true
  24289. });
  24290. Gamepad.prototype.update = function () {
  24291. if (this._leftStick) {
  24292. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24293. }
  24294. if (this._rightStick) {
  24295. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24296. }
  24297. };
  24298. return Gamepad;
  24299. })();
  24300. BABYLON.Gamepad = Gamepad;
  24301. var GenericPad = (function (_super) {
  24302. __extends(GenericPad, _super);
  24303. function GenericPad(id, index, gamepad) {
  24304. _super.call(this, id, index, gamepad);
  24305. this.id = id;
  24306. this.index = index;
  24307. this.gamepad = gamepad;
  24308. this._buttons = new Array(gamepad.buttons.length);
  24309. }
  24310. GenericPad.prototype.onbuttondown = function (callback) {
  24311. this._onbuttondown = callback;
  24312. };
  24313. GenericPad.prototype.onbuttonup = function (callback) {
  24314. this._onbuttonup = callback;
  24315. };
  24316. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  24317. if (newValue !== currentValue) {
  24318. if (this._onbuttondown && newValue === 1) {
  24319. this._onbuttondown(buttonIndex);
  24320. }
  24321. if (this._onbuttonup && newValue === 0) {
  24322. this._onbuttonup(buttonIndex);
  24323. }
  24324. }
  24325. return newValue;
  24326. };
  24327. GenericPad.prototype.update = function () {
  24328. _super.prototype.update.call(this);
  24329. for (var index = 0; index < this._buttons.length; index++) {
  24330. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  24331. }
  24332. };
  24333. return GenericPad;
  24334. })(Gamepad);
  24335. BABYLON.GenericPad = GenericPad;
  24336. (function (Xbox360Button) {
  24337. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  24338. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  24339. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  24340. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  24341. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  24342. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  24343. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  24344. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  24345. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  24346. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  24347. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  24348. var Xbox360Button = BABYLON.Xbox360Button;
  24349. (function (Xbox360Dpad) {
  24350. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  24351. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  24352. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  24353. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  24354. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  24355. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  24356. var Xbox360Pad = (function (_super) {
  24357. __extends(Xbox360Pad, _super);
  24358. function Xbox360Pad() {
  24359. _super.apply(this, arguments);
  24360. this._leftTrigger = 0;
  24361. this._rightTrigger = 0;
  24362. this._buttonA = 0;
  24363. this._buttonB = 0;
  24364. this._buttonX = 0;
  24365. this._buttonY = 0;
  24366. this._buttonBack = 0;
  24367. this._buttonStart = 0;
  24368. this._buttonLB = 0;
  24369. this._buttonRB = 0;
  24370. this._buttonLeftStick = 0;
  24371. this._buttonRightStick = 0;
  24372. this._dPadUp = 0;
  24373. this._dPadDown = 0;
  24374. this._dPadLeft = 0;
  24375. this._dPadRight = 0;
  24376. }
  24377. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  24378. this._onlefttriggerchanged = callback;
  24379. };
  24380. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  24381. this._onrighttriggerchanged = callback;
  24382. };
  24383. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  24384. get: function () {
  24385. return this._leftTrigger;
  24386. },
  24387. set: function (newValue) {
  24388. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  24389. this._onlefttriggerchanged(newValue);
  24390. }
  24391. this._leftTrigger = newValue;
  24392. },
  24393. enumerable: true,
  24394. configurable: true
  24395. });
  24396. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  24397. get: function () {
  24398. return this._rightTrigger;
  24399. },
  24400. set: function (newValue) {
  24401. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  24402. this._onrighttriggerchanged(newValue);
  24403. }
  24404. this._rightTrigger = newValue;
  24405. },
  24406. enumerable: true,
  24407. configurable: true
  24408. });
  24409. Xbox360Pad.prototype.onbuttondown = function (callback) {
  24410. this._onbuttondown = callback;
  24411. };
  24412. Xbox360Pad.prototype.onbuttonup = function (callback) {
  24413. this._onbuttonup = callback;
  24414. };
  24415. Xbox360Pad.prototype.ondpaddown = function (callback) {
  24416. this._ondpaddown = callback;
  24417. };
  24418. Xbox360Pad.prototype.ondpadup = function (callback) {
  24419. this._ondpadup = callback;
  24420. };
  24421. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  24422. if (newValue !== currentValue) {
  24423. if (this._onbuttondown && newValue === 1) {
  24424. this._onbuttondown(buttonType);
  24425. }
  24426. if (this._onbuttonup && newValue === 0) {
  24427. this._onbuttonup(buttonType);
  24428. }
  24429. }
  24430. return newValue;
  24431. };
  24432. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  24433. if (newValue !== currentValue) {
  24434. if (this._ondpaddown && newValue === 1) {
  24435. this._ondpaddown(buttonType);
  24436. }
  24437. if (this._ondpadup && newValue === 0) {
  24438. this._ondpadup(buttonType);
  24439. }
  24440. }
  24441. return newValue;
  24442. };
  24443. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  24444. get: function () {
  24445. return this._buttonA;
  24446. },
  24447. set: function (value) {
  24448. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  24449. },
  24450. enumerable: true,
  24451. configurable: true
  24452. });
  24453. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  24454. get: function () {
  24455. return this._buttonB;
  24456. },
  24457. set: function (value) {
  24458. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  24459. },
  24460. enumerable: true,
  24461. configurable: true
  24462. });
  24463. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  24464. get: function () {
  24465. return this._buttonX;
  24466. },
  24467. set: function (value) {
  24468. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  24469. },
  24470. enumerable: true,
  24471. configurable: true
  24472. });
  24473. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  24474. get: function () {
  24475. return this._buttonY;
  24476. },
  24477. set: function (value) {
  24478. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  24479. },
  24480. enumerable: true,
  24481. configurable: true
  24482. });
  24483. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  24484. get: function () {
  24485. return this._buttonStart;
  24486. },
  24487. set: function (value) {
  24488. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  24489. },
  24490. enumerable: true,
  24491. configurable: true
  24492. });
  24493. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  24494. get: function () {
  24495. return this._buttonBack;
  24496. },
  24497. set: function (value) {
  24498. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  24499. },
  24500. enumerable: true,
  24501. configurable: true
  24502. });
  24503. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  24504. get: function () {
  24505. return this._buttonLB;
  24506. },
  24507. set: function (value) {
  24508. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  24509. },
  24510. enumerable: true,
  24511. configurable: true
  24512. });
  24513. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  24514. get: function () {
  24515. return this._buttonRB;
  24516. },
  24517. set: function (value) {
  24518. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  24519. },
  24520. enumerable: true,
  24521. configurable: true
  24522. });
  24523. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  24524. get: function () {
  24525. return this._buttonLeftStick;
  24526. },
  24527. set: function (value) {
  24528. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  24529. },
  24530. enumerable: true,
  24531. configurable: true
  24532. });
  24533. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  24534. get: function () {
  24535. return this._buttonRightStick;
  24536. },
  24537. set: function (value) {
  24538. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  24539. },
  24540. enumerable: true,
  24541. configurable: true
  24542. });
  24543. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  24544. get: function () {
  24545. return this._dPadUp;
  24546. },
  24547. set: function (value) {
  24548. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  24549. },
  24550. enumerable: true,
  24551. configurable: true
  24552. });
  24553. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  24554. get: function () {
  24555. return this._dPadDown;
  24556. },
  24557. set: function (value) {
  24558. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  24559. },
  24560. enumerable: true,
  24561. configurable: true
  24562. });
  24563. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  24564. get: function () {
  24565. return this._dPadLeft;
  24566. },
  24567. set: function (value) {
  24568. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  24569. },
  24570. enumerable: true,
  24571. configurable: true
  24572. });
  24573. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  24574. get: function () {
  24575. return this._dPadRight;
  24576. },
  24577. set: function (value) {
  24578. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  24579. },
  24580. enumerable: true,
  24581. configurable: true
  24582. });
  24583. Xbox360Pad.prototype.update = function () {
  24584. _super.prototype.update.call(this);
  24585. this.buttonA = this.browserGamepad.buttons[0].value;
  24586. this.buttonB = this.browserGamepad.buttons[1].value;
  24587. this.buttonX = this.browserGamepad.buttons[2].value;
  24588. this.buttonY = this.browserGamepad.buttons[3].value;
  24589. this.buttonLB = this.browserGamepad.buttons[4].value;
  24590. this.buttonRB = this.browserGamepad.buttons[5].value;
  24591. this.leftTrigger = this.browserGamepad.buttons[6].value;
  24592. this.rightTrigger = this.browserGamepad.buttons[7].value;
  24593. this.buttonBack = this.browserGamepad.buttons[8].value;
  24594. this.buttonStart = this.browserGamepad.buttons[9].value;
  24595. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  24596. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  24597. this.dPadUp = this.browserGamepad.buttons[12].value;
  24598. this.dPadDown = this.browserGamepad.buttons[13].value;
  24599. this.dPadLeft = this.browserGamepad.buttons[14].value;
  24600. this.dPadRight = this.browserGamepad.buttons[15].value;
  24601. };
  24602. return Xbox360Pad;
  24603. })(Gamepad);
  24604. BABYLON.Xbox360Pad = Xbox360Pad;
  24605. })(BABYLON || (BABYLON = {}));
  24606. //# sourceMappingURL=babylon.gamepads.js.map
  24607. var BABYLON;
  24608. (function (BABYLON) {
  24609. // We're mainly based on the logic defined into the FreeCamera code
  24610. var GamepadCamera = (function (_super) {
  24611. __extends(GamepadCamera, _super);
  24612. function GamepadCamera(name, position, scene) {
  24613. var _this = this;
  24614. _super.call(this, name, position, scene);
  24615. this.angularSensibility = 200;
  24616. this.moveSensibility = 75;
  24617. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  24618. _this._onNewGameConnected(gamepad);
  24619. });
  24620. }
  24621. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  24622. // Only the first gamepad can control the camera
  24623. if (gamepad.index === 0) {
  24624. this._gamepad = gamepad;
  24625. }
  24626. };
  24627. GamepadCamera.prototype._checkInputs = function () {
  24628. if (!this._gamepad) {
  24629. return;
  24630. }
  24631. var LSValues = this._gamepad.leftStick;
  24632. var normalizedLX = LSValues.x / this.moveSensibility;
  24633. var normalizedLY = LSValues.y / this.moveSensibility;
  24634. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  24635. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  24636. var RSValues = this._gamepad.rightStick;
  24637. var normalizedRX = RSValues.x / this.angularSensibility;
  24638. var normalizedRY = RSValues.y / this.angularSensibility;
  24639. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  24640. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  24641. ;
  24642. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24643. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  24644. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24645. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  24646. };
  24647. GamepadCamera.prototype.dispose = function () {
  24648. this._gamepads.dispose();
  24649. _super.prototype.dispose.call(this);
  24650. };
  24651. return GamepadCamera;
  24652. })(BABYLON.FreeCamera);
  24653. BABYLON.GamepadCamera = GamepadCamera;
  24654. })(BABYLON || (BABYLON = {}));
  24655. //# sourceMappingURL=babylon.gamepadCamera.js.map
  24656. var BABYLON;
  24657. (function (BABYLON) {
  24658. var LinesMesh = (function (_super) {
  24659. __extends(LinesMesh, _super);
  24660. function LinesMesh(name, scene, updatable) {
  24661. if (updatable === void 0) { updatable = false; }
  24662. _super.call(this, name, scene);
  24663. this.color = new BABYLON.Color3(1, 1, 1);
  24664. this.alpha = 1;
  24665. this._indices = new Array();
  24666. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  24667. attributes: ["position"],
  24668. uniforms: ["worldViewProjection", "color"],
  24669. needAlphaBlending: true
  24670. });
  24671. }
  24672. Object.defineProperty(LinesMesh.prototype, "material", {
  24673. get: function () {
  24674. return this._colorShader;
  24675. },
  24676. enumerable: true,
  24677. configurable: true
  24678. });
  24679. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  24680. get: function () {
  24681. return false;
  24682. },
  24683. enumerable: true,
  24684. configurable: true
  24685. });
  24686. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  24687. get: function () {
  24688. return false;
  24689. },
  24690. enumerable: true,
  24691. configurable: true
  24692. });
  24693. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  24694. var engine = this.getScene().getEngine();
  24695. var indexToBind = this._geometry.getIndexBuffer();
  24696. // VBOs
  24697. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  24698. // Color
  24699. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  24700. };
  24701. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  24702. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24703. return;
  24704. }
  24705. var engine = this.getScene().getEngine();
  24706. // Draw order
  24707. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  24708. };
  24709. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  24710. return null;
  24711. };
  24712. LinesMesh.prototype.dispose = function (doNotRecurse) {
  24713. this._colorShader.dispose();
  24714. _super.prototype.dispose.call(this, doNotRecurse);
  24715. };
  24716. return LinesMesh;
  24717. })(BABYLON.Mesh);
  24718. BABYLON.LinesMesh = LinesMesh;
  24719. })(BABYLON || (BABYLON = {}));
  24720. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  24721. (function (BABYLON) {
  24722. var OutlineRenderer = (function () {
  24723. function OutlineRenderer(scene) {
  24724. this._scene = scene;
  24725. }
  24726. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  24727. var _this = this;
  24728. if (useOverlay === void 0) { useOverlay = false; }
  24729. var scene = this._scene;
  24730. var engine = this._scene.getEngine();
  24731. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24732. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  24733. return;
  24734. }
  24735. var mesh = subMesh.getRenderingMesh();
  24736. var material = subMesh.getMaterial();
  24737. engine.enableEffect(this._effect);
  24738. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  24739. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  24740. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24741. // Bones
  24742. if (mesh.useBones) {
  24743. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24744. }
  24745. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  24746. // Alpha test
  24747. if (material && material.needAlphaTesting()) {
  24748. var alphaTexture = material.getAlphaTestTexture();
  24749. this._effect.setTexture("diffuseSampler", alphaTexture);
  24750. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  24751. }
  24752. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  24753. _this._effect.setMatrix("world", world);
  24754. });
  24755. };
  24756. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  24757. var defines = [];
  24758. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  24759. var mesh = subMesh.getMesh();
  24760. var material = subMesh.getMaterial();
  24761. // Alpha test
  24762. if (material && material.needAlphaTesting()) {
  24763. defines.push("#define ALPHATEST");
  24764. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24765. attribs.push(BABYLON.VertexBuffer.UVKind);
  24766. defines.push("#define UV1");
  24767. }
  24768. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24769. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  24770. defines.push("#define UV2");
  24771. }
  24772. }
  24773. // Bones
  24774. if (mesh.useBones) {
  24775. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24776. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24777. defines.push("#define BONES");
  24778. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24779. }
  24780. // Instances
  24781. if (useInstances) {
  24782. defines.push("#define INSTANCES");
  24783. attribs.push("world0");
  24784. attribs.push("world1");
  24785. attribs.push("world2");
  24786. attribs.push("world3");
  24787. }
  24788. // Get correct effect
  24789. var join = defines.join("\n");
  24790. if (this._cachedDefines !== join) {
  24791. this._cachedDefines = join;
  24792. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  24793. }
  24794. return this._effect.isReady();
  24795. };
  24796. return OutlineRenderer;
  24797. })();
  24798. BABYLON.OutlineRenderer = OutlineRenderer;
  24799. })(BABYLON || (BABYLON = {}));
  24800. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  24801. (function (BABYLON) {
  24802. var MeshAssetTask = (function () {
  24803. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  24804. this.name = name;
  24805. this.meshesNames = meshesNames;
  24806. this.rootUrl = rootUrl;
  24807. this.sceneFilename = sceneFilename;
  24808. this.isCompleted = false;
  24809. }
  24810. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24811. var _this = this;
  24812. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  24813. _this.loadedMeshes = meshes;
  24814. _this.loadedParticleSystems = particleSystems;
  24815. _this.loadedSkeletons = skeletons;
  24816. _this.isCompleted = true;
  24817. if (_this.onSuccess) {
  24818. _this.onSuccess(_this);
  24819. }
  24820. onSuccess();
  24821. }, null, function () {
  24822. if (_this.onError) {
  24823. _this.onError(_this);
  24824. }
  24825. onError();
  24826. });
  24827. };
  24828. return MeshAssetTask;
  24829. })();
  24830. BABYLON.MeshAssetTask = MeshAssetTask;
  24831. var TextFileAssetTask = (function () {
  24832. function TextFileAssetTask(name, url) {
  24833. this.name = name;
  24834. this.url = url;
  24835. this.isCompleted = false;
  24836. }
  24837. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24838. var _this = this;
  24839. BABYLON.Tools.LoadFile(this.url, function (data) {
  24840. _this.text = data;
  24841. _this.isCompleted = true;
  24842. if (_this.onSuccess) {
  24843. _this.onSuccess(_this);
  24844. }
  24845. onSuccess();
  24846. }, null, scene.database, false, function () {
  24847. if (_this.onError) {
  24848. _this.onError(_this);
  24849. }
  24850. onError();
  24851. });
  24852. };
  24853. return TextFileAssetTask;
  24854. })();
  24855. BABYLON.TextFileAssetTask = TextFileAssetTask;
  24856. var BinaryFileAssetTask = (function () {
  24857. function BinaryFileAssetTask(name, url) {
  24858. this.name = name;
  24859. this.url = url;
  24860. this.isCompleted = false;
  24861. }
  24862. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24863. var _this = this;
  24864. BABYLON.Tools.LoadFile(this.url, function (data) {
  24865. _this.data = data;
  24866. _this.isCompleted = true;
  24867. if (_this.onSuccess) {
  24868. _this.onSuccess(_this);
  24869. }
  24870. onSuccess();
  24871. }, null, scene.database, true, function () {
  24872. if (_this.onError) {
  24873. _this.onError(_this);
  24874. }
  24875. onError();
  24876. });
  24877. };
  24878. return BinaryFileAssetTask;
  24879. })();
  24880. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  24881. var ImageAssetTask = (function () {
  24882. function ImageAssetTask(name, url) {
  24883. this.name = name;
  24884. this.url = url;
  24885. this.isCompleted = false;
  24886. }
  24887. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24888. var _this = this;
  24889. var img = new Image();
  24890. img.onload = function () {
  24891. _this.image = img;
  24892. _this.isCompleted = true;
  24893. if (_this.onSuccess) {
  24894. _this.onSuccess(_this);
  24895. }
  24896. onSuccess();
  24897. };
  24898. img.onerror = function () {
  24899. if (_this.onError) {
  24900. _this.onError(_this);
  24901. }
  24902. onError();
  24903. };
  24904. img.src = this.url;
  24905. };
  24906. return ImageAssetTask;
  24907. })();
  24908. BABYLON.ImageAssetTask = ImageAssetTask;
  24909. var TextureAssetTask = (function () {
  24910. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  24911. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24912. this.name = name;
  24913. this.url = url;
  24914. this.noMipmap = noMipmap;
  24915. this.invertY = invertY;
  24916. this.samplingMode = samplingMode;
  24917. this.isCompleted = false;
  24918. }
  24919. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24920. var _this = this;
  24921. var onload = function () {
  24922. _this.isCompleted = true;
  24923. if (_this.onSuccess) {
  24924. _this.onSuccess(_this);
  24925. }
  24926. onSuccess();
  24927. };
  24928. var onerror = function () {
  24929. if (_this.onError) {
  24930. _this.onError(_this);
  24931. }
  24932. onError();
  24933. };
  24934. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  24935. };
  24936. return TextureAssetTask;
  24937. })();
  24938. BABYLON.TextureAssetTask = TextureAssetTask;
  24939. var AssetsManager = (function () {
  24940. function AssetsManager(scene) {
  24941. this._tasks = new Array();
  24942. this._waitingTasksCount = 0;
  24943. this.useDefaultLoadingScreen = true;
  24944. this._scene = scene;
  24945. }
  24946. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  24947. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  24948. this._tasks.push(task);
  24949. return task;
  24950. };
  24951. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  24952. var task = new TextFileAssetTask(taskName, url);
  24953. this._tasks.push(task);
  24954. return task;
  24955. };
  24956. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  24957. var task = new BinaryFileAssetTask(taskName, url);
  24958. this._tasks.push(task);
  24959. return task;
  24960. };
  24961. AssetsManager.prototype.addImageTask = function (taskName, url) {
  24962. var task = new ImageAssetTask(taskName, url);
  24963. this._tasks.push(task);
  24964. return task;
  24965. };
  24966. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  24967. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24968. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  24969. this._tasks.push(task);
  24970. return task;
  24971. };
  24972. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  24973. this._waitingTasksCount--;
  24974. if (this._waitingTasksCount === 0) {
  24975. if (this.onFinish) {
  24976. this.onFinish(this._tasks);
  24977. }
  24978. this._scene.getEngine().hideLoadingUI();
  24979. }
  24980. };
  24981. AssetsManager.prototype._runTask = function (task) {
  24982. var _this = this;
  24983. task.run(this._scene, function () {
  24984. if (_this.onTaskSuccess) {
  24985. _this.onTaskSuccess(task);
  24986. }
  24987. _this._decreaseWaitingTasksCount();
  24988. }, function () {
  24989. if (_this.onTaskError) {
  24990. _this.onTaskError(task);
  24991. }
  24992. _this._decreaseWaitingTasksCount();
  24993. });
  24994. };
  24995. AssetsManager.prototype.reset = function () {
  24996. this._tasks = new Array();
  24997. return this;
  24998. };
  24999. AssetsManager.prototype.load = function () {
  25000. this._waitingTasksCount = this._tasks.length;
  25001. if (this._waitingTasksCount === 0) {
  25002. if (this.onFinish) {
  25003. this.onFinish(this._tasks);
  25004. }
  25005. return this;
  25006. }
  25007. if (this.useDefaultLoadingScreen) {
  25008. this._scene.getEngine().displayLoadingUI();
  25009. }
  25010. for (var index = 0; index < this._tasks.length; index++) {
  25011. var task = this._tasks[index];
  25012. this._runTask(task);
  25013. }
  25014. return this;
  25015. };
  25016. return AssetsManager;
  25017. })();
  25018. BABYLON.AssetsManager = AssetsManager;
  25019. })(BABYLON || (BABYLON = {}));
  25020. //# sourceMappingURL=babylon.assetsManager.js.map
  25021. var BABYLON;
  25022. (function (BABYLON) {
  25023. var VRDeviceOrientationCamera = (function (_super) {
  25024. __extends(VRDeviceOrientationCamera, _super);
  25025. function VRDeviceOrientationCamera(name, position, scene) {
  25026. _super.call(this, name, position, scene);
  25027. this._alpha = 0;
  25028. this._beta = 0;
  25029. this._gamma = 0;
  25030. }
  25031. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  25032. this._alpha = +evt.alpha | 0;
  25033. this._beta = +evt.beta | 0;
  25034. this._gamma = +evt.gamma | 0;
  25035. if (this._gamma < 0) {
  25036. this._gamma = 90 + this._gamma;
  25037. }
  25038. else {
  25039. // Incline it in the correct angle.
  25040. this._gamma = 270 - this._gamma;
  25041. }
  25042. this.rotation.x = this._gamma / 180.0 * Math.PI;
  25043. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  25044. this.rotation.z = this._beta / 180.0 * Math.PI;
  25045. };
  25046. return VRDeviceOrientationCamera;
  25047. })(BABYLON.OculusCamera);
  25048. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  25049. })(BABYLON || (BABYLON = {}));
  25050. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  25051. var BABYLON;
  25052. (function (BABYLON) {
  25053. var WebVRCamera = (function (_super) {
  25054. __extends(WebVRCamera, _super);
  25055. function WebVRCamera(name, position, scene) {
  25056. _super.call(this, name, position, scene);
  25057. this._hmdDevice = null;
  25058. this._sensorDevice = null;
  25059. this._cacheState = null;
  25060. this._cacheQuaternion = new BABYLON.Quaternion();
  25061. this._cacheRotation = BABYLON.Vector3.Zero();
  25062. this._vrEnabled = false;
  25063. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  25064. }
  25065. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  25066. var size = devices.length;
  25067. var i = 0;
  25068. // Reset devices.
  25069. this._sensorDevice = null;
  25070. this._hmdDevice = null;
  25071. while (i < size && this._hmdDevice === null) {
  25072. if (devices[i] instanceof HMDVRDevice) {
  25073. this._hmdDevice = devices[i];
  25074. }
  25075. i++;
  25076. }
  25077. i = 0;
  25078. while (i < size && this._sensorDevice === null) {
  25079. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  25080. this._sensorDevice = devices[i];
  25081. }
  25082. i++;
  25083. }
  25084. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  25085. };
  25086. WebVRCamera.prototype._update = function () {
  25087. if (this._vrEnabled) {
  25088. this._cacheState = this._sensorDevice.getState();
  25089. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  25090. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  25091. this.rotation.x = -this._cacheRotation.z;
  25092. this.rotation.y = -this._cacheRotation.y;
  25093. this.rotation.z = this._cacheRotation.x;
  25094. }
  25095. _super.prototype._update.call(this);
  25096. };
  25097. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  25098. _super.prototype.attachControl.call(this, element, noPreventDefault);
  25099. if (navigator.getVRDevices) {
  25100. navigator.getVRDevices().then(this._getWebVRDevices);
  25101. }
  25102. else if (navigator.mozGetVRDevices) {
  25103. navigator.mozGetVRDevices(this._getWebVRDevices);
  25104. }
  25105. };
  25106. WebVRCamera.prototype.detachControl = function (element) {
  25107. _super.prototype.detachControl.call(this, element);
  25108. this._vrEnabled = false;
  25109. };
  25110. return WebVRCamera;
  25111. })(BABYLON.OculusCamera);
  25112. BABYLON.WebVRCamera = WebVRCamera;
  25113. })(BABYLON || (BABYLON = {}));
  25114. //# sourceMappingURL=babylon.webVRCamera.js.map
  25115. var BABYLON;
  25116. (function (BABYLON) {
  25117. // Standard optimizations
  25118. var SceneOptimization = (function () {
  25119. function SceneOptimization(priority) {
  25120. if (priority === void 0) { priority = 0; }
  25121. this.priority = priority;
  25122. this.apply = function (scene) {
  25123. return true; // Return true if everything that can be done was applied
  25124. };
  25125. }
  25126. return SceneOptimization;
  25127. })();
  25128. BABYLON.SceneOptimization = SceneOptimization;
  25129. var TextureOptimization = (function (_super) {
  25130. __extends(TextureOptimization, _super);
  25131. function TextureOptimization(priority, maximumSize) {
  25132. var _this = this;
  25133. if (priority === void 0) { priority = 0; }
  25134. if (maximumSize === void 0) { maximumSize = 1024; }
  25135. _super.call(this, priority);
  25136. this.priority = priority;
  25137. this.maximumSize = maximumSize;
  25138. this.apply = function (scene) {
  25139. var allDone = true;
  25140. for (var index = 0; index < scene.textures.length; index++) {
  25141. var texture = scene.textures[index];
  25142. if (!texture.canRescale) {
  25143. continue;
  25144. }
  25145. var currentSize = texture.getSize();
  25146. var maxDimension = Math.max(currentSize.width, currentSize.height);
  25147. if (maxDimension > _this.maximumSize) {
  25148. texture.scale(0.5);
  25149. allDone = false;
  25150. }
  25151. }
  25152. return allDone;
  25153. };
  25154. }
  25155. return TextureOptimization;
  25156. })(SceneOptimization);
  25157. BABYLON.TextureOptimization = TextureOptimization;
  25158. var HardwareScalingOptimization = (function (_super) {
  25159. __extends(HardwareScalingOptimization, _super);
  25160. function HardwareScalingOptimization(priority, maximumScale) {
  25161. var _this = this;
  25162. if (priority === void 0) { priority = 0; }
  25163. if (maximumScale === void 0) { maximumScale = 2; }
  25164. _super.call(this, priority);
  25165. this.priority = priority;
  25166. this.maximumScale = maximumScale;
  25167. this._currentScale = 1;
  25168. this.apply = function (scene) {
  25169. _this._currentScale++;
  25170. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  25171. return _this._currentScale >= _this.maximumScale;
  25172. };
  25173. }
  25174. return HardwareScalingOptimization;
  25175. })(SceneOptimization);
  25176. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  25177. var ShadowsOptimization = (function (_super) {
  25178. __extends(ShadowsOptimization, _super);
  25179. function ShadowsOptimization() {
  25180. _super.apply(this, arguments);
  25181. this.apply = function (scene) {
  25182. scene.shadowsEnabled = false;
  25183. return true;
  25184. };
  25185. }
  25186. return ShadowsOptimization;
  25187. })(SceneOptimization);
  25188. BABYLON.ShadowsOptimization = ShadowsOptimization;
  25189. var PostProcessesOptimization = (function (_super) {
  25190. __extends(PostProcessesOptimization, _super);
  25191. function PostProcessesOptimization() {
  25192. _super.apply(this, arguments);
  25193. this.apply = function (scene) {
  25194. scene.postProcessesEnabled = false;
  25195. return true;
  25196. };
  25197. }
  25198. return PostProcessesOptimization;
  25199. })(SceneOptimization);
  25200. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  25201. var LensFlaresOptimization = (function (_super) {
  25202. __extends(LensFlaresOptimization, _super);
  25203. function LensFlaresOptimization() {
  25204. _super.apply(this, arguments);
  25205. this.apply = function (scene) {
  25206. scene.lensFlaresEnabled = false;
  25207. return true;
  25208. };
  25209. }
  25210. return LensFlaresOptimization;
  25211. })(SceneOptimization);
  25212. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  25213. var ParticlesOptimization = (function (_super) {
  25214. __extends(ParticlesOptimization, _super);
  25215. function ParticlesOptimization() {
  25216. _super.apply(this, arguments);
  25217. this.apply = function (scene) {
  25218. scene.particlesEnabled = false;
  25219. return true;
  25220. };
  25221. }
  25222. return ParticlesOptimization;
  25223. })(SceneOptimization);
  25224. BABYLON.ParticlesOptimization = ParticlesOptimization;
  25225. var RenderTargetsOptimization = (function (_super) {
  25226. __extends(RenderTargetsOptimization, _super);
  25227. function RenderTargetsOptimization() {
  25228. _super.apply(this, arguments);
  25229. this.apply = function (scene) {
  25230. scene.renderTargetsEnabled = false;
  25231. return true;
  25232. };
  25233. }
  25234. return RenderTargetsOptimization;
  25235. })(SceneOptimization);
  25236. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  25237. var MergeMeshesOptimization = (function (_super) {
  25238. __extends(MergeMeshesOptimization, _super);
  25239. function MergeMeshesOptimization() {
  25240. var _this = this;
  25241. _super.apply(this, arguments);
  25242. this._canBeMerged = function (abstractMesh) {
  25243. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  25244. return false;
  25245. }
  25246. var mesh = abstractMesh;
  25247. if (!mesh.isVisible || !mesh.isEnabled()) {
  25248. return false;
  25249. }
  25250. if (mesh.instances.length > 0) {
  25251. return false;
  25252. }
  25253. if (mesh.skeleton || mesh.hasLODLevels) {
  25254. return false;
  25255. }
  25256. return true;
  25257. };
  25258. this.apply = function (scene) {
  25259. var globalPool = scene.meshes.slice(0);
  25260. var globalLength = globalPool.length;
  25261. for (var index = 0; index < globalLength; index++) {
  25262. var currentPool = new Array();
  25263. var current = globalPool[index];
  25264. // Checks
  25265. if (!_this._canBeMerged(current)) {
  25266. continue;
  25267. }
  25268. currentPool.push(current);
  25269. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  25270. var otherMesh = globalPool[subIndex];
  25271. if (!_this._canBeMerged(otherMesh)) {
  25272. continue;
  25273. }
  25274. if (otherMesh.material !== current.material) {
  25275. continue;
  25276. }
  25277. if (otherMesh.checkCollisions !== current.checkCollisions) {
  25278. continue;
  25279. }
  25280. currentPool.push(otherMesh);
  25281. globalLength--;
  25282. globalPool.splice(subIndex, 1);
  25283. subIndex--;
  25284. }
  25285. if (currentPool.length < 2) {
  25286. continue;
  25287. }
  25288. // Merge meshes
  25289. BABYLON.Mesh.MergeMeshes(currentPool);
  25290. }
  25291. return true;
  25292. };
  25293. }
  25294. return MergeMeshesOptimization;
  25295. })(SceneOptimization);
  25296. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  25297. // Options
  25298. var SceneOptimizerOptions = (function () {
  25299. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  25300. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  25301. if (trackerDuration === void 0) { trackerDuration = 2000; }
  25302. this.targetFrameRate = targetFrameRate;
  25303. this.trackerDuration = trackerDuration;
  25304. this.optimizations = new Array();
  25305. }
  25306. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  25307. var result = new SceneOptimizerOptions(targetFrameRate);
  25308. var priority = 0;
  25309. result.optimizations.push(new MergeMeshesOptimization(priority));
  25310. result.optimizations.push(new ShadowsOptimization(priority));
  25311. result.optimizations.push(new LensFlaresOptimization(priority));
  25312. // Next priority
  25313. priority++;
  25314. result.optimizations.push(new PostProcessesOptimization(priority));
  25315. result.optimizations.push(new ParticlesOptimization(priority));
  25316. // Next priority
  25317. priority++;
  25318. result.optimizations.push(new TextureOptimization(priority, 1024));
  25319. return result;
  25320. };
  25321. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  25322. var result = new SceneOptimizerOptions(targetFrameRate);
  25323. var priority = 0;
  25324. result.optimizations.push(new MergeMeshesOptimization(priority));
  25325. result.optimizations.push(new ShadowsOptimization(priority));
  25326. result.optimizations.push(new LensFlaresOptimization(priority));
  25327. // Next priority
  25328. priority++;
  25329. result.optimizations.push(new PostProcessesOptimization(priority));
  25330. result.optimizations.push(new ParticlesOptimization(priority));
  25331. // Next priority
  25332. priority++;
  25333. result.optimizations.push(new TextureOptimization(priority, 512));
  25334. // Next priority
  25335. priority++;
  25336. result.optimizations.push(new RenderTargetsOptimization(priority));
  25337. // Next priority
  25338. priority++;
  25339. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  25340. return result;
  25341. };
  25342. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  25343. var result = new SceneOptimizerOptions(targetFrameRate);
  25344. var priority = 0;
  25345. result.optimizations.push(new MergeMeshesOptimization(priority));
  25346. result.optimizations.push(new ShadowsOptimization(priority));
  25347. result.optimizations.push(new LensFlaresOptimization(priority));
  25348. // Next priority
  25349. priority++;
  25350. result.optimizations.push(new PostProcessesOptimization(priority));
  25351. result.optimizations.push(new ParticlesOptimization(priority));
  25352. // Next priority
  25353. priority++;
  25354. result.optimizations.push(new TextureOptimization(priority, 256));
  25355. // Next priority
  25356. priority++;
  25357. result.optimizations.push(new RenderTargetsOptimization(priority));
  25358. // Next priority
  25359. priority++;
  25360. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  25361. return result;
  25362. };
  25363. return SceneOptimizerOptions;
  25364. })();
  25365. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  25366. // Scene optimizer tool
  25367. var SceneOptimizer = (function () {
  25368. function SceneOptimizer() {
  25369. }
  25370. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  25371. // TODO: add an epsilon
  25372. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  25373. if (onSuccess) {
  25374. onSuccess();
  25375. }
  25376. return;
  25377. }
  25378. // Apply current level of optimizations
  25379. var allDone = true;
  25380. var noOptimizationApplied = true;
  25381. for (var index = 0; index < options.optimizations.length; index++) {
  25382. var optimization = options.optimizations[index];
  25383. if (optimization.priority === currentPriorityLevel) {
  25384. noOptimizationApplied = false;
  25385. allDone = allDone && optimization.apply(scene);
  25386. }
  25387. }
  25388. // If no optimization was applied, this is a failure :(
  25389. if (noOptimizationApplied) {
  25390. if (onFailure) {
  25391. onFailure();
  25392. }
  25393. return;
  25394. }
  25395. // If all optimizations were done, move to next level
  25396. if (allDone) {
  25397. currentPriorityLevel++;
  25398. }
  25399. // Let's the system running for a specific amount of time before checking FPS
  25400. scene.executeWhenReady(function () {
  25401. setTimeout(function () {
  25402. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  25403. }, options.trackerDuration);
  25404. });
  25405. };
  25406. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  25407. if (!options) {
  25408. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  25409. }
  25410. // Let's the system running for a specific amount of time before checking FPS
  25411. scene.executeWhenReady(function () {
  25412. setTimeout(function () {
  25413. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  25414. }, options.trackerDuration);
  25415. });
  25416. };
  25417. return SceneOptimizer;
  25418. })();
  25419. BABYLON.SceneOptimizer = SceneOptimizer;
  25420. })(BABYLON || (BABYLON = {}));
  25421. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  25422. (function (BABYLON) {
  25423. var Internals;
  25424. (function (Internals) {
  25425. var MeshLODLevel = (function () {
  25426. function MeshLODLevel(distance, mesh) {
  25427. this.distance = distance;
  25428. this.mesh = mesh;
  25429. }
  25430. return MeshLODLevel;
  25431. })();
  25432. Internals.MeshLODLevel = MeshLODLevel;
  25433. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25434. })(BABYLON || (BABYLON = {}));
  25435. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  25436. (function (BABYLON) {
  25437. var AudioEngine = (function () {
  25438. function AudioEngine() {
  25439. this.audioContext = null;
  25440. this.canUseWebAudio = false;
  25441. this.WarnedWebAudioUnsupported = false;
  25442. try {
  25443. if (typeof AudioContext !== 'undefined') {
  25444. this.audioContext = new AudioContext();
  25445. this.canUseWebAudio = true;
  25446. }
  25447. else if (typeof webkitAudioContext !== 'undefined') {
  25448. this.audioContext = new webkitAudioContext();
  25449. this.canUseWebAudio = true;
  25450. }
  25451. }
  25452. catch (e) {
  25453. this.canUseWebAudio = false;
  25454. BABYLON.Tools.Error("Web Audio: " + e.message);
  25455. }
  25456. // create a global volume gain node
  25457. if (this.canUseWebAudio) {
  25458. this.masterGain = this.audioContext.createGain();
  25459. this.masterGain.gain.value = 1;
  25460. this.masterGain.connect(this.audioContext.destination);
  25461. }
  25462. }
  25463. AudioEngine.prototype.dispose = function () {
  25464. if (this.canUseWebAudio) {
  25465. if (this._connectedAnalyser) {
  25466. this._connectedAnalyser.stopDebugCanvas();
  25467. this._connectedAnalyser.dispose();
  25468. this.masterGain.disconnect();
  25469. this.masterGain.connect(this.audioContext.destination);
  25470. this._connectedAnalyser = null;
  25471. }
  25472. this.masterGain.gain.value = 1;
  25473. }
  25474. this.WarnedWebAudioUnsupported = false;
  25475. };
  25476. AudioEngine.prototype.getGlobalVolume = function () {
  25477. if (this.canUseWebAudio) {
  25478. return this.masterGain.gain.value;
  25479. }
  25480. else {
  25481. return -1;
  25482. }
  25483. };
  25484. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  25485. if (this.canUseWebAudio) {
  25486. this.masterGain.gain.value = newVolume;
  25487. }
  25488. };
  25489. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  25490. if (this._connectedAnalyser) {
  25491. this._connectedAnalyser.stopDebugCanvas();
  25492. }
  25493. this._connectedAnalyser = analyser;
  25494. if (this.canUseWebAudio) {
  25495. this.masterGain.disconnect();
  25496. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  25497. }
  25498. };
  25499. return AudioEngine;
  25500. })();
  25501. BABYLON.AudioEngine = AudioEngine;
  25502. })(BABYLON || (BABYLON = {}));
  25503. //# sourceMappingURL=babylon.audioengine.js.mapvar BABYLON;
  25504. (function (BABYLON) {
  25505. var Sound = (function () {
  25506. /**
  25507. * Create a sound and attach it to a scene
  25508. * @param name Name of your sound
  25509. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  25510. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  25511. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  25512. */
  25513. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  25514. var _this = this;
  25515. this.autoplay = false;
  25516. this.loop = false;
  25517. this.useCustomAttenuation = false;
  25518. this.spatialSound = false;
  25519. this.refDistance = 1;
  25520. this.rolloffFactor = 1;
  25521. this.maxDistance = 100;
  25522. this.distanceModel = "linear";
  25523. this.panningModel = "HRTF";
  25524. this._playbackRate = 1;
  25525. this._startTime = 0;
  25526. this._startOffset = 0;
  25527. this._position = BABYLON.Vector3.Zero();
  25528. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  25529. this._volume = 1;
  25530. this._isLoaded = false;
  25531. this._isReadyToPlay = false;
  25532. this._isPlaying = false;
  25533. this._isDirectional = false;
  25534. // Used if you'd like to create a directional sound.
  25535. // If not set, the sound will be omnidirectional
  25536. this._coneInnerAngle = 360;
  25537. this._coneOuterAngle = 360;
  25538. this._coneOuterGain = 0;
  25539. this.name = name;
  25540. this._scene = scene;
  25541. this._readyToPlayCallback = readyToPlayCallback;
  25542. // Default custom attenuation function is a linear attenuation
  25543. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  25544. if (currentDistance < maxDistance) {
  25545. return currentVolume * (1 - currentDistance / maxDistance);
  25546. }
  25547. else {
  25548. return 0;
  25549. }
  25550. };
  25551. if (options) {
  25552. this.autoplay = options.autoplay || false;
  25553. this.loop = options.loop || false;
  25554. // if volume === 0, we need another way to check this option
  25555. if (options.volume !== undefined) {
  25556. this._volume = options.volume;
  25557. }
  25558. this.spatialSound = options.spatialSound || false;
  25559. this.maxDistance = options.maxDistance || 100;
  25560. this.useCustomAttenuation = options.useCustomAttenuation || false;
  25561. this.rolloffFactor = options.rolloffFactor || 1;
  25562. this.refDistance = options.refDistance || 1;
  25563. this.distanceModel = options.distanceModel || "linear";
  25564. this.panningModel = options.panningModel || "HRTF";
  25565. this._playbackRate = options.playbackRate || 1;
  25566. }
  25567. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25568. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  25569. this._soundGain.gain.value = this._volume;
  25570. this._inputAudioNode = this._soundGain;
  25571. this._ouputAudioNode = this._soundGain;
  25572. if (this.spatialSound) {
  25573. this._createSpatialParameters();
  25574. }
  25575. this._scene.mainSoundTrack.AddSound(this);
  25576. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  25577. if (urlOrArrayBuffer) {
  25578. // If it's an URL
  25579. if (typeof (urlOrArrayBuffer) === "string") {
  25580. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  25581. _this._soundLoaded(data);
  25582. }, null, null, true);
  25583. }
  25584. else {
  25585. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  25586. this._soundLoaded(urlOrArrayBuffer);
  25587. }
  25588. else {
  25589. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  25590. }
  25591. }
  25592. }
  25593. }
  25594. else {
  25595. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  25596. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  25597. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  25598. }
  25599. }
  25600. }
  25601. Sound.prototype.dispose = function () {
  25602. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  25603. if (this._isPlaying) {
  25604. this.stop();
  25605. }
  25606. this._isReadyToPlay = false;
  25607. if (this.soundTrackId === -1) {
  25608. this._scene.mainSoundTrack.RemoveSound(this);
  25609. }
  25610. else {
  25611. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  25612. }
  25613. this._soundGain.disconnect();
  25614. this._soundSource.disconnect();
  25615. if (this._soundPanner) {
  25616. this._soundPanner.disconnect();
  25617. this._soundPanner = null;
  25618. }
  25619. this._audioBuffer = null;
  25620. this._soundGain = null;
  25621. this._soundSource = null;
  25622. if (this._connectedMesh) {
  25623. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  25624. this._connectedMesh = null;
  25625. }
  25626. }
  25627. };
  25628. Sound.prototype._soundLoaded = function (audioData) {
  25629. var _this = this;
  25630. this._isLoaded = true;
  25631. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  25632. _this._audioBuffer = buffer;
  25633. _this._isReadyToPlay = true;
  25634. if (_this.autoplay) {
  25635. _this.play();
  25636. }
  25637. if (_this._readyToPlayCallback) {
  25638. _this._readyToPlayCallback();
  25639. }
  25640. }, function (error) {
  25641. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  25642. });
  25643. };
  25644. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  25645. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25646. this._audioBuffer = audioBuffer;
  25647. this._isReadyToPlay = true;
  25648. }
  25649. };
  25650. Sound.prototype.updateOptions = function (options) {
  25651. if (options) {
  25652. this.loop = options.loop || this.loop;
  25653. this.maxDistance = options.maxDistance || this.maxDistance;
  25654. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  25655. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  25656. this.refDistance = options.refDistance || this.refDistance;
  25657. this.distanceModel = options.distanceModel || this.distanceModel;
  25658. this.panningModel = options.panningModel || this.panningModel;
  25659. this._playbackRate = options.playbackRate || this._playbackRate;
  25660. }
  25661. };
  25662. Sound.prototype._createSpatialParameters = function () {
  25663. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25664. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  25665. if (this.useCustomAttenuation) {
  25666. // Tricks to disable in a way embedded Web Audio attenuation
  25667. this._soundPanner.distanceModel = "linear";
  25668. this._soundPanner.maxDistance = Number.MAX_VALUE;
  25669. this._soundPanner.refDistance = 1;
  25670. this._soundPanner.rolloffFactor = 1;
  25671. this._soundPanner.panningModel = "HRTF";
  25672. }
  25673. else {
  25674. this._soundPanner.distanceModel = this.distanceModel;
  25675. this._soundPanner.maxDistance = this.maxDistance;
  25676. this._soundPanner.refDistance = this.refDistance;
  25677. this._soundPanner.rolloffFactor = this.rolloffFactor;
  25678. this._soundPanner.panningModel = this.panningModel;
  25679. }
  25680. this._soundPanner.connect(this._ouputAudioNode);
  25681. this._inputAudioNode = this._soundPanner;
  25682. }
  25683. };
  25684. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  25685. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25686. this._ouputAudioNode.disconnect();
  25687. this._ouputAudioNode.connect(soundTrackAudioNode);
  25688. }
  25689. };
  25690. /**
  25691. * Transform this sound into a directional source
  25692. * @param coneInnerAngle Size of the inner cone in degree
  25693. * @param coneOuterAngle Size of the outer cone in degree
  25694. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  25695. */
  25696. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25697. if (coneOuterAngle < coneInnerAngle) {
  25698. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  25699. return;
  25700. }
  25701. this._coneInnerAngle = coneInnerAngle;
  25702. this._coneOuterAngle = coneOuterAngle;
  25703. this._coneOuterGain = coneOuterGain;
  25704. this._isDirectional = true;
  25705. if (this._isPlaying && this.loop) {
  25706. this.stop();
  25707. this.play();
  25708. }
  25709. };
  25710. Sound.prototype.setPosition = function (newPosition) {
  25711. this._position = newPosition;
  25712. if (this._isPlaying && this.spatialSound) {
  25713. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25714. }
  25715. };
  25716. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  25717. this._localDirection = newLocalDirection;
  25718. if (this._connectedMesh && this._isPlaying) {
  25719. this._updateDirection();
  25720. }
  25721. };
  25722. Sound.prototype._updateDirection = function () {
  25723. var mat = this._connectedMesh.getWorldMatrix();
  25724. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  25725. direction.normalize();
  25726. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  25727. };
  25728. Sound.prototype.updateDistanceFromListener = function () {
  25729. if (this._connectedMesh && this.useCustomAttenuation) {
  25730. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  25731. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  25732. }
  25733. };
  25734. Sound.prototype.setAttenuationFunction = function (callback) {
  25735. this._customAttenuationFunction = callback;
  25736. };
  25737. /**
  25738. * Play the sound
  25739. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  25740. */
  25741. Sound.prototype.play = function (time) {
  25742. if (this._isReadyToPlay) {
  25743. try {
  25744. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  25745. if (!this._soundSource) {
  25746. if (this.spatialSound) {
  25747. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25748. if (this._isDirectional) {
  25749. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  25750. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  25751. this._soundPanner.coneOuterGain = this._coneOuterGain;
  25752. if (this._connectedMesh) {
  25753. this._updateDirection();
  25754. }
  25755. else {
  25756. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  25757. }
  25758. }
  25759. }
  25760. }
  25761. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  25762. this._soundSource.buffer = this._audioBuffer;
  25763. this._soundSource.connect(this._inputAudioNode);
  25764. this._soundSource.loop = this.loop;
  25765. this._soundSource.playbackRate.value = this._playbackRate;
  25766. this._startTime = startTime;
  25767. if (this.onended) {
  25768. this._soundSource.onended = this.onended;
  25769. }
  25770. this._soundSource.start(startTime, this._startOffset % this._soundSource.buffer.duration);
  25771. this._isPlaying = true;
  25772. }
  25773. catch (ex) {
  25774. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  25775. }
  25776. }
  25777. };
  25778. /**
  25779. * Stop the sound
  25780. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  25781. */
  25782. Sound.prototype.stop = function (time) {
  25783. if (this._isPlaying) {
  25784. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  25785. this._soundSource.stop(stopTime);
  25786. this._isPlaying = false;
  25787. }
  25788. };
  25789. Sound.prototype.pause = function () {
  25790. if (this._isPlaying) {
  25791. this._soundSource.stop(0);
  25792. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  25793. }
  25794. };
  25795. Sound.prototype.setVolume = function (newVolume, time) {
  25796. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25797. if (time) {
  25798. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  25799. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  25800. }
  25801. else {
  25802. this._soundGain.gain.value = newVolume;
  25803. }
  25804. }
  25805. this._volume = newVolume;
  25806. };
  25807. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  25808. this._playbackRate = newPlaybackRate;
  25809. if (this._isPlaying) {
  25810. this._soundSource.playbackRate.value = this._playbackRate;
  25811. }
  25812. };
  25813. Sound.prototype.getVolume = function () {
  25814. return this._volume;
  25815. };
  25816. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  25817. var _this = this;
  25818. this._connectedMesh = meshToConnectTo;
  25819. if (!this.spatialSound) {
  25820. this._createSpatialParameters();
  25821. this.spatialSound = true;
  25822. if (this._isPlaying && this.loop) {
  25823. this.stop();
  25824. this.play();
  25825. }
  25826. }
  25827. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  25828. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  25829. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  25830. };
  25831. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  25832. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  25833. if (this._isDirectional && this._isPlaying) {
  25834. this._updateDirection();
  25835. }
  25836. };
  25837. return Sound;
  25838. })();
  25839. BABYLON.Sound = Sound;
  25840. })(BABYLON || (BABYLON = {}));
  25841. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  25842. (function (BABYLON) {
  25843. var SoundTrack = (function () {
  25844. function SoundTrack(scene, options) {
  25845. this.id = -1;
  25846. this._isMainTrack = false;
  25847. this._scene = scene;
  25848. this._audioEngine = BABYLON.Engine.audioEngine;
  25849. this.soundCollection = new Array();
  25850. if (this._audioEngine.canUseWebAudio) {
  25851. this._trackGain = this._audioEngine.audioContext.createGain();
  25852. this._trackGain.connect(this._audioEngine.masterGain);
  25853. if (options) {
  25854. if (options.volume) {
  25855. this._trackGain.gain.value = options.volume;
  25856. }
  25857. if (options.mainTrack) {
  25858. this._isMainTrack = options.mainTrack;
  25859. }
  25860. }
  25861. }
  25862. if (!this._isMainTrack) {
  25863. this._scene.soundTracks.push(this);
  25864. this.id = this._scene.soundTracks.length - 1;
  25865. }
  25866. }
  25867. SoundTrack.prototype.dispose = function () {
  25868. if (this._audioEngine.canUseWebAudio) {
  25869. if (this._connectedAnalyser) {
  25870. this._connectedAnalyser.stopDebugCanvas();
  25871. }
  25872. while (this.soundCollection.length) {
  25873. this.soundCollection[0].dispose();
  25874. }
  25875. this._trackGain.disconnect();
  25876. this._trackGain = null;
  25877. }
  25878. };
  25879. SoundTrack.prototype.AddSound = function (sound) {
  25880. sound.connectToSoundTrackAudioNode(this._trackGain);
  25881. if (sound.soundTrackId) {
  25882. if (sound.soundTrackId === -1) {
  25883. this._scene.mainSoundTrack.RemoveSound(sound);
  25884. }
  25885. else {
  25886. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  25887. }
  25888. }
  25889. this.soundCollection.push(sound);
  25890. sound.soundTrackId = this.id;
  25891. };
  25892. SoundTrack.prototype.RemoveSound = function (sound) {
  25893. var index = this.soundCollection.indexOf(sound);
  25894. if (index !== -1) {
  25895. this.soundCollection.splice(index, 1);
  25896. }
  25897. };
  25898. SoundTrack.prototype.setVolume = function (newVolume) {
  25899. if (this._audioEngine.canUseWebAudio) {
  25900. this._trackGain.gain.value = newVolume;
  25901. }
  25902. };
  25903. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  25904. if (this._connectedAnalyser) {
  25905. this._connectedAnalyser.stopDebugCanvas();
  25906. }
  25907. this._connectedAnalyser = analyser;
  25908. if (this._audioEngine.canUseWebAudio) {
  25909. this._trackGain.disconnect();
  25910. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  25911. }
  25912. };
  25913. return SoundTrack;
  25914. })();
  25915. BABYLON.SoundTrack = SoundTrack;
  25916. })(BABYLON || (BABYLON = {}));
  25917. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  25918. (function (BABYLON) {
  25919. var DebugLayer = (function () {
  25920. function DebugLayer(scene) {
  25921. var _this = this;
  25922. this._enabled = false;
  25923. this._labelsEnabled = false;
  25924. this._displayStatistics = true;
  25925. this._displayTree = false;
  25926. this._displayLogs = false;
  25927. this._identityMatrix = BABYLON.Matrix.Identity();
  25928. this.axisRatio = 0.02;
  25929. this.accentColor = "orange";
  25930. this._scene = scene;
  25931. this._syncPositions = function () {
  25932. var engine = _this._scene.getEngine();
  25933. var canvasRect = engine.getRenderingCanvasClientRect();
  25934. if (_this._showUI) {
  25935. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  25936. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  25937. _this._statsDiv.style.width = "400px";
  25938. _this._statsDiv.style.height = "auto";
  25939. _this._statsSubsetDiv.style.maxHeight = "240px";
  25940. _this._optionsDiv.style.left = "0px";
  25941. _this._optionsDiv.style.top = "10px";
  25942. _this._optionsDiv.style.width = "200px";
  25943. _this._optionsDiv.style.height = "auto";
  25944. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  25945. _this._logDiv.style.left = "0px";
  25946. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  25947. _this._logDiv.style.width = "600px";
  25948. _this._logDiv.style.height = "160px";
  25949. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  25950. _this._treeDiv.style.top = "10px";
  25951. _this._treeDiv.style.width = "300px";
  25952. _this._treeDiv.style.height = "auto";
  25953. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  25954. }
  25955. _this._globalDiv.style.left = canvasRect.left + "px";
  25956. _this._globalDiv.style.top = canvasRect.top + "px";
  25957. _this._drawingCanvas.style.left = "0px";
  25958. _this._drawingCanvas.style.top = "0px";
  25959. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  25960. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  25961. var devicePixelRatio = window.devicePixelRatio || 1;
  25962. var context = _this._drawingContext;
  25963. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  25964. _this._ratio = devicePixelRatio / backingStoreRatio;
  25965. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  25966. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  25967. };
  25968. this._onCanvasClick = function (evt) {
  25969. _this._clickPosition = {
  25970. x: evt.clientX * _this._ratio,
  25971. y: evt.clientY * _this._ratio
  25972. };
  25973. };
  25974. this._syncData = function () {
  25975. if (_this._showUI) {
  25976. if (_this._displayStatistics) {
  25977. _this._displayStats();
  25978. _this._statsDiv.style.display = "";
  25979. }
  25980. else {
  25981. _this._statsDiv.style.display = "none";
  25982. }
  25983. if (_this._displayLogs) {
  25984. _this._logDiv.style.display = "";
  25985. }
  25986. else {
  25987. _this._logDiv.style.display = "none";
  25988. }
  25989. if (_this._displayTree) {
  25990. _this._treeDiv.style.display = "";
  25991. if (_this._needToRefreshMeshesTree) {
  25992. _this._needToRefreshMeshesTree = false;
  25993. _this._refreshMeshesTreeContent();
  25994. }
  25995. }
  25996. else {
  25997. _this._treeDiv.style.display = "none";
  25998. }
  25999. }
  26000. if (_this._labelsEnabled || !_this._showUI) {
  26001. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26002. var engine = _this._scene.getEngine();
  26003. var viewport = _this._scene.activeCamera.viewport;
  26004. var globalViewport = viewport.toGlobal(engine);
  26005. // Meshes
  26006. var meshes = _this._scene.getActiveMeshes();
  26007. for (var index = 0; index < meshes.length; index++) {
  26008. var mesh = meshes.data[index];
  26009. var position = mesh.getBoundingInfo().boundingSphere.center;
  26010. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  26011. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26012. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26013. }
  26014. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26015. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  26016. mesh.renderOverlay = !mesh.renderOverlay;
  26017. }, function () {
  26018. return mesh.renderOverlay ? 'red' : 'black';
  26019. });
  26020. }
  26021. }
  26022. // Cameras
  26023. var cameras = _this._scene.cameras;
  26024. for (index = 0; index < cameras.length; index++) {
  26025. var camera = cameras[index];
  26026. if (camera === _this._scene.activeCamera) {
  26027. continue;
  26028. }
  26029. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  26030. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26031. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26032. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  26033. _this._scene.activeCamera = camera;
  26034. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  26035. }, function () {
  26036. return "purple";
  26037. });
  26038. }
  26039. }
  26040. // Lights
  26041. var lights = _this._scene.lights;
  26042. for (index = 0; index < lights.length; index++) {
  26043. var light = lights[index];
  26044. if (light.position) {
  26045. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  26046. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26047. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26048. light.setEnabled(!light.isEnabled());
  26049. }, function () {
  26050. return light.isEnabled() ? "orange" : "gray";
  26051. });
  26052. }
  26053. }
  26054. }
  26055. }
  26056. _this._clickPosition = undefined;
  26057. };
  26058. }
  26059. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26060. while (this._treeSubsetDiv.hasChildNodes()) {
  26061. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26062. }
  26063. // Add meshes
  26064. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26065. sortedArray.sort(function (a, b) {
  26066. if (a.name === b.name) {
  26067. return 0;
  26068. }
  26069. return (a.name > b.name) ? 1 : -1;
  26070. });
  26071. for (var index = 0; index < sortedArray.length; index++) {
  26072. var mesh = sortedArray[index];
  26073. if (!mesh.isEnabled()) {
  26074. continue;
  26075. }
  26076. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26077. m.isVisible = element.checked;
  26078. }, mesh);
  26079. }
  26080. };
  26081. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26082. this._drawingContext.beginPath();
  26083. this._drawingContext.moveTo(zero.x, zero.y);
  26084. this._drawingContext.lineTo(unit.x, unit.y);
  26085. this._drawingContext.strokeStyle = color;
  26086. this._drawingContext.lineWidth = 4;
  26087. this._drawingContext.stroke();
  26088. this._drawingContext.font = "normal 14px Segoe UI";
  26089. this._drawingContext.fillStyle = color;
  26090. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26091. };
  26092. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26093. var position = mesh.getBoundingInfo().boundingSphere.center;
  26094. var worldMatrix = mesh.getWorldMatrix();
  26095. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._scene.getTransformMatrix());
  26096. var unit = (unprojectedVector.subtract(position)).length();
  26097. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26098. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26099. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  26100. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26101. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26102. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  26103. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26104. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26105. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  26106. };
  26107. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  26108. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  26109. this._drawingContext.font = "normal 12px Segoe UI";
  26110. var textMetrics = this._drawingContext.measureText(text);
  26111. var centerX = projectedPosition.x - textMetrics.width / 2;
  26112. var centerY = projectedPosition.y;
  26113. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26114. onClick();
  26115. }
  26116. this._drawingContext.beginPath();
  26117. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26118. this._drawingContext.fillStyle = getFillStyle();
  26119. this._drawingContext.globalAlpha = 0.5;
  26120. this._drawingContext.fill();
  26121. this._drawingContext.globalAlpha = 1.0;
  26122. this._drawingContext.strokeStyle = '#FFFFFF';
  26123. this._drawingContext.lineWidth = 1;
  26124. this._drawingContext.stroke();
  26125. this._drawingContext.fillStyle = "#FFFFFF";
  26126. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26127. this._drawingContext.beginPath();
  26128. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26129. this._drawingContext.fill();
  26130. }
  26131. };
  26132. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26133. if (!this._clickPosition) {
  26134. return false;
  26135. }
  26136. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26137. return false;
  26138. }
  26139. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26140. return false;
  26141. }
  26142. return true;
  26143. };
  26144. DebugLayer.prototype.isVisible = function () {
  26145. return this._enabled;
  26146. };
  26147. DebugLayer.prototype.hide = function () {
  26148. if (!this._enabled) {
  26149. return;
  26150. }
  26151. this._enabled = false;
  26152. var engine = this._scene.getEngine();
  26153. this._scene.unregisterAfterRender(this._syncData);
  26154. document.body.removeChild(this._globalDiv);
  26155. window.removeEventListener("resize", this._syncPositions);
  26156. this._scene.forceShowBoundingBoxes = false;
  26157. this._scene.forceWireframe = false;
  26158. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26159. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26160. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26161. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26162. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26163. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26164. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26165. this._scene.shadowsEnabled = true;
  26166. this._scene.particlesEnabled = true;
  26167. this._scene.postProcessesEnabled = true;
  26168. this._scene.collisionsEnabled = true;
  26169. this._scene.lightsEnabled = true;
  26170. this._scene.texturesEnabled = true;
  26171. this._scene.lensFlaresEnabled = true;
  26172. this._scene.proceduralTexturesEnabled = true;
  26173. this._scene.renderTargetsEnabled = true;
  26174. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26175. };
  26176. DebugLayer.prototype.show = function (showUI) {
  26177. if (showUI === void 0) { showUI = true; }
  26178. if (this._enabled) {
  26179. return;
  26180. }
  26181. this._enabled = true;
  26182. this._showUI = showUI;
  26183. var engine = this._scene.getEngine();
  26184. this._globalDiv = document.createElement("div");
  26185. document.body.appendChild(this._globalDiv);
  26186. this._generateDOMelements();
  26187. window.addEventListener("resize", this._syncPositions);
  26188. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26189. this._syncPositions();
  26190. this._scene.registerAfterRender(this._syncData);
  26191. };
  26192. DebugLayer.prototype._clearLabels = function () {
  26193. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26194. for (var index = 0; index < this._scene.meshes.length; index++) {
  26195. var mesh = this._scene.meshes[index];
  26196. mesh.renderOverlay = false;
  26197. }
  26198. };
  26199. DebugLayer.prototype._generateheader = function (root, text) {
  26200. var header = document.createElement("div");
  26201. header.innerHTML = text + "&nbsp;";
  26202. header.style.textAlign = "right";
  26203. header.style.width = "100%";
  26204. header.style.color = "white";
  26205. header.style.backgroundColor = "Black";
  26206. header.style.padding = "5px 5px 4px 0px";
  26207. header.style.marginLeft = "-5px";
  26208. header.style.fontWeight = "bold";
  26209. root.appendChild(header);
  26210. };
  26211. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26212. var label = document.createElement("label");
  26213. label.innerHTML = title;
  26214. label.style.color = color;
  26215. root.appendChild(label);
  26216. root.appendChild(document.createElement("br"));
  26217. };
  26218. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26219. if (tag === void 0) { tag = null; }
  26220. var label = document.createElement("label");
  26221. var boundingBoxesCheckbox = document.createElement("input");
  26222. boundingBoxesCheckbox.type = "checkbox";
  26223. boundingBoxesCheckbox.checked = initialState;
  26224. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26225. task(evt.target, tag);
  26226. });
  26227. label.appendChild(boundingBoxesCheckbox);
  26228. var container = document.createElement("span");
  26229. var leftPart = document.createElement("span");
  26230. var rightPart = document.createElement("span");
  26231. rightPart.style.cssFloat = "right";
  26232. leftPart.innerHTML = leftTitle;
  26233. rightPart.innerHTML = rightTitle;
  26234. rightPart.style.fontSize = "12px";
  26235. rightPart.style.maxWidth = "200px";
  26236. container.appendChild(leftPart);
  26237. container.appendChild(rightPart);
  26238. label.appendChild(container);
  26239. root.appendChild(label);
  26240. root.appendChild(document.createElement("br"));
  26241. };
  26242. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  26243. if (tag === void 0) { tag = null; }
  26244. var label = document.createElement("label");
  26245. var boundingBoxesCheckbox = document.createElement("input");
  26246. boundingBoxesCheckbox.type = "checkbox";
  26247. boundingBoxesCheckbox.checked = initialState;
  26248. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26249. task(evt.target, tag);
  26250. });
  26251. label.appendChild(boundingBoxesCheckbox);
  26252. label.appendChild(document.createTextNode(title));
  26253. root.appendChild(label);
  26254. root.appendChild(document.createElement("br"));
  26255. };
  26256. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  26257. if (tag === void 0) { tag = null; }
  26258. var label = document.createElement("label");
  26259. var boundingBoxesRadio = document.createElement("input");
  26260. boundingBoxesRadio.type = "radio";
  26261. boundingBoxesRadio.name = name;
  26262. boundingBoxesRadio.checked = initialState;
  26263. boundingBoxesRadio.addEventListener("change", function (evt) {
  26264. task(evt.target, tag);
  26265. });
  26266. label.appendChild(boundingBoxesRadio);
  26267. label.appendChild(document.createTextNode(title));
  26268. root.appendChild(label);
  26269. root.appendChild(document.createElement("br"));
  26270. };
  26271. DebugLayer.prototype._generateDOMelements = function () {
  26272. var _this = this;
  26273. this._globalDiv.id = "DebugLayer";
  26274. this._globalDiv.style.position = "absolute";
  26275. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  26276. this._globalDiv.style.fontSize = "14px";
  26277. this._globalDiv.style.color = "white";
  26278. // Drawing canvas
  26279. this._drawingCanvas = document.createElement("canvas");
  26280. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  26281. this._drawingCanvas.style.position = "absolute";
  26282. this._drawingCanvas.style.pointerEvents = "none";
  26283. this._drawingContext = this._drawingCanvas.getContext("2d");
  26284. this._globalDiv.appendChild(this._drawingCanvas);
  26285. if (this._showUI) {
  26286. var background = "rgba(128, 128, 128, 0.4)";
  26287. var border = "rgb(180, 180, 180) solid 1px";
  26288. // Stats
  26289. this._statsDiv = document.createElement("div");
  26290. this._statsDiv.id = "DebugLayerStats";
  26291. this._statsDiv.style.border = border;
  26292. this._statsDiv.style.position = "absolute";
  26293. this._statsDiv.style.background = background;
  26294. this._statsDiv.style.padding = "0px 0px 0px 5px";
  26295. this._generateheader(this._statsDiv, "STATISTICS");
  26296. this._statsSubsetDiv = document.createElement("div");
  26297. this._statsSubsetDiv.style.paddingTop = "5px";
  26298. this._statsSubsetDiv.style.paddingBottom = "5px";
  26299. this._statsSubsetDiv.style.overflowY = "auto";
  26300. this._statsDiv.appendChild(this._statsSubsetDiv);
  26301. // Tree
  26302. this._treeDiv = document.createElement("div");
  26303. this._treeDiv.id = "DebugLayerTree";
  26304. this._treeDiv.style.border = border;
  26305. this._treeDiv.style.position = "absolute";
  26306. this._treeDiv.style.background = background;
  26307. this._treeDiv.style.padding = "0px 0px 0px 5px";
  26308. this._treeDiv.style.display = "none";
  26309. this._generateheader(this._treeDiv, "MESHES TREE");
  26310. this._treeSubsetDiv = document.createElement("div");
  26311. this._treeSubsetDiv.style.paddingTop = "5px";
  26312. this._treeSubsetDiv.style.paddingRight = "5px";
  26313. this._treeSubsetDiv.style.overflowY = "auto";
  26314. this._treeSubsetDiv.style.maxHeight = "300px";
  26315. this._treeDiv.appendChild(this._treeSubsetDiv);
  26316. this._needToRefreshMeshesTree = true;
  26317. // Logs
  26318. this._logDiv = document.createElement("div");
  26319. this._logDiv.style.border = border;
  26320. this._logDiv.id = "DebugLayerLogs";
  26321. this._logDiv.style.position = "absolute";
  26322. this._logDiv.style.background = background;
  26323. this._logDiv.style.padding = "0px 0px 0px 5px";
  26324. this._logDiv.style.display = "none";
  26325. this._generateheader(this._logDiv, "LOGS");
  26326. this._logSubsetDiv = document.createElement("div");
  26327. this._logSubsetDiv.style.height = "127px";
  26328. this._logSubsetDiv.style.paddingTop = "5px";
  26329. this._logSubsetDiv.style.overflowY = "auto";
  26330. this._logSubsetDiv.style.fontSize = "12px";
  26331. this._logSubsetDiv.style.fontFamily = "consolas";
  26332. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  26333. this._logDiv.appendChild(this._logSubsetDiv);
  26334. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  26335. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  26336. };
  26337. // Options
  26338. this._optionsDiv = document.createElement("div");
  26339. this._optionsDiv.id = "DebugLayerOptions";
  26340. this._optionsDiv.style.border = border;
  26341. this._optionsDiv.style.position = "absolute";
  26342. this._optionsDiv.style.background = background;
  26343. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  26344. this._optionsDiv.style.overflowY = "auto";
  26345. this._generateheader(this._optionsDiv, "OPTIONS");
  26346. this._optionsSubsetDiv = document.createElement("div");
  26347. this._optionsSubsetDiv.style.paddingTop = "5px";
  26348. this._optionsSubsetDiv.style.paddingBottom = "5px";
  26349. this._optionsSubsetDiv.style.overflowY = "auto";
  26350. this._optionsSubsetDiv.style.maxHeight = "200px";
  26351. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  26352. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  26353. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  26354. _this._displayStatistics = element.checked;
  26355. });
  26356. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  26357. _this._displayLogs = element.checked;
  26358. });
  26359. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  26360. _this._displayTree = element.checked;
  26361. _this._needToRefreshMeshesTree = true;
  26362. });
  26363. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26364. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  26365. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  26366. _this._scene.forceShowBoundingBoxes = element.checked;
  26367. });
  26368. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  26369. _this._labelsEnabled = element.checked;
  26370. if (!_this._labelsEnabled) {
  26371. _this._clearLabels();
  26372. }
  26373. });
  26374. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  26375. if (element.checked) {
  26376. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  26377. }
  26378. else {
  26379. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  26380. }
  26381. });
  26382. ;
  26383. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26384. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  26385. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  26386. if (element.checked) {
  26387. _this._scene.forceWireframe = false;
  26388. _this._scene.forcePointsCloud = false;
  26389. }
  26390. });
  26391. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  26392. if (element.checked) {
  26393. _this._scene.forceWireframe = true;
  26394. _this._scene.forcePointsCloud = false;
  26395. }
  26396. });
  26397. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  26398. if (element.checked) {
  26399. _this._scene.forceWireframe = false;
  26400. _this._scene.forcePointsCloud = true;
  26401. }
  26402. });
  26403. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26404. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  26405. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  26406. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  26407. });
  26408. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  26409. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  26410. });
  26411. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  26412. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  26413. });
  26414. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  26415. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  26416. });
  26417. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  26418. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  26419. });
  26420. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  26421. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  26422. });
  26423. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  26424. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  26425. });
  26426. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  26427. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  26428. });
  26429. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26430. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  26431. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  26432. _this._scene.animationsEnabled = element.checked;
  26433. });
  26434. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  26435. _this._scene.collisionsEnabled = element.checked;
  26436. });
  26437. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  26438. _this._scene.fogEnabled = element.checked;
  26439. });
  26440. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  26441. _this._scene.lensFlaresEnabled = element.checked;
  26442. });
  26443. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  26444. _this._scene.lightsEnabled = element.checked;
  26445. });
  26446. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  26447. _this._scene.particlesEnabled = element.checked;
  26448. });
  26449. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  26450. _this._scene.postProcessesEnabled = element.checked;
  26451. });
  26452. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  26453. _this._scene.proceduralTexturesEnabled = element.checked;
  26454. });
  26455. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  26456. _this._scene.renderTargetsEnabled = element.checked;
  26457. });
  26458. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  26459. _this._scene.shadowsEnabled = element.checked;
  26460. });
  26461. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  26462. _this._scene.skeletonsEnabled = element.checked;
  26463. });
  26464. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  26465. _this._scene.texturesEnabled = element.checked;
  26466. });
  26467. this._globalDiv.appendChild(this._statsDiv);
  26468. this._globalDiv.appendChild(this._logDiv);
  26469. this._globalDiv.appendChild(this._optionsDiv);
  26470. this._globalDiv.appendChild(this._treeDiv);
  26471. }
  26472. };
  26473. DebugLayer.prototype._displayStats = function () {
  26474. var scene = this._scene;
  26475. var engine = scene.getEngine();
  26476. var glInfo = engine.getGlInfo();
  26477. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Count</b><br>" + "Total meshes: " + scene.meshes.length + "<br>" + "Total vertices: " + scene.getTotalVertices() + "<br>" + "Total materials: " + scene.materials.length + "<br>" + "Total textures: " + scene.textures.length + "<br>" + "Active meshes: " + scene.getActiveMeshes().length + "<br>" + "Active vertices: " + scene.getActiveVertices() + "<br>" + "Active bones: " + scene.getActiveBones() + "<br>" + "Active particles: " + scene.getActiveParticles() + "<br>" + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>" + "<b>Duration</b><br>" + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>" + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>" + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>" + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>" + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>" + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>" + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>" + "</div>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Extensions</b><br>" + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>" + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>" + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>" + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>" + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>" + "<b>Caps.</b><br>" + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>" + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>" + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>" + "</div><br>" + "<b>Info</b><br>" + glInfo.version + "<br>" + glInfo.renderer + "<br>";
  26478. if (this.customStatsFunction) {
  26479. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  26480. }
  26481. };
  26482. return DebugLayer;
  26483. })();
  26484. BABYLON.DebugLayer = DebugLayer;
  26485. })(BABYLON || (BABYLON = {}));
  26486. //# sourceMappingURL=babylon.debugLayer.js.map
  26487. var BABYLON;
  26488. (function (BABYLON) {
  26489. var RawTexture = (function (_super) {
  26490. __extends(RawTexture, _super);
  26491. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  26492. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26493. if (invertY === void 0) { invertY = false; }
  26494. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26495. _super.call(this, null, scene, !generateMipMaps, invertY);
  26496. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  26497. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26498. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26499. }
  26500. // Statics
  26501. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26502. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26503. if (invertY === void 0) { invertY = false; }
  26504. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26505. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  26506. };
  26507. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26508. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26509. if (invertY === void 0) { invertY = false; }
  26510. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26511. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26512. };
  26513. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26514. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26515. if (invertY === void 0) { invertY = false; }
  26516. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26517. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26518. };
  26519. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26520. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26521. if (invertY === void 0) { invertY = false; }
  26522. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26523. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  26524. };
  26525. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26526. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26527. if (invertY === void 0) { invertY = false; }
  26528. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26529. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  26530. };
  26531. return RawTexture;
  26532. })(BABYLON.Texture);
  26533. BABYLON.RawTexture = RawTexture;
  26534. })(BABYLON || (BABYLON = {}));
  26535. //# sourceMappingURL=babylon.rawTexture.js.map
  26536. var BABYLON;
  26537. (function (BABYLON) {
  26538. var IndexedVector2 = (function (_super) {
  26539. __extends(IndexedVector2, _super);
  26540. function IndexedVector2(original, index) {
  26541. _super.call(this, original.x, original.y);
  26542. this.index = index;
  26543. }
  26544. return IndexedVector2;
  26545. })(BABYLON.Vector2);
  26546. var PolygonPoints = (function () {
  26547. function PolygonPoints() {
  26548. this.elements = new Array();
  26549. }
  26550. PolygonPoints.prototype.add = function (originalPoints) {
  26551. var _this = this;
  26552. var result = new Array();
  26553. originalPoints.forEach(function (point) {
  26554. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  26555. var newPoint = new IndexedVector2(point, _this.elements.length);
  26556. result.push(newPoint);
  26557. _this.elements.push(newPoint);
  26558. }
  26559. });
  26560. return result;
  26561. };
  26562. PolygonPoints.prototype.computeBounds = function () {
  26563. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26564. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26565. this.elements.forEach(function (point) {
  26566. // x
  26567. if (point.x < lmin.x) {
  26568. lmin.x = point.x;
  26569. }
  26570. else if (point.x > lmax.x) {
  26571. lmax.x = point.x;
  26572. }
  26573. // y
  26574. if (point.y < lmin.y) {
  26575. lmin.y = point.y;
  26576. }
  26577. else if (point.y > lmax.y) {
  26578. lmax.y = point.y;
  26579. }
  26580. });
  26581. return {
  26582. min: lmin,
  26583. max: lmax,
  26584. width: lmax.x - lmin.x,
  26585. height: lmax.y - lmin.y
  26586. };
  26587. };
  26588. return PolygonPoints;
  26589. })();
  26590. var Polygon = (function () {
  26591. function Polygon() {
  26592. }
  26593. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  26594. return [
  26595. new BABYLON.Vector2(xmin, ymin),
  26596. new BABYLON.Vector2(xmax, ymin),
  26597. new BABYLON.Vector2(xmax, ymax),
  26598. new BABYLON.Vector2(xmin, ymax)
  26599. ];
  26600. };
  26601. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  26602. if (cx === void 0) { cx = 0; }
  26603. if (cy === void 0) { cy = 0; }
  26604. if (numberOfSides === void 0) { numberOfSides = 32; }
  26605. var result = new Array();
  26606. var angle = 0;
  26607. var increment = (Math.PI * 2) / numberOfSides;
  26608. for (var i = 0; i < numberOfSides; i++) {
  26609. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  26610. angle -= increment;
  26611. }
  26612. return result;
  26613. };
  26614. Polygon.Parse = function (input) {
  26615. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  26616. var i, result = [];
  26617. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  26618. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  26619. }
  26620. return result;
  26621. };
  26622. Polygon.StartingAt = function (x, y) {
  26623. return BABYLON.Path2.StartingAt(x, y);
  26624. };
  26625. return Polygon;
  26626. })();
  26627. BABYLON.Polygon = Polygon;
  26628. var PolygonMeshBuilder = (function () {
  26629. function PolygonMeshBuilder(name, contours, scene) {
  26630. this._points = new PolygonPoints();
  26631. if (!("poly2tri" in window)) {
  26632. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  26633. }
  26634. this._name = name;
  26635. this._scene = scene;
  26636. var points;
  26637. if (contours instanceof BABYLON.Path2) {
  26638. points = contours.getPoints();
  26639. }
  26640. else {
  26641. points = contours;
  26642. }
  26643. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  26644. }
  26645. PolygonMeshBuilder.prototype.addHole = function (hole) {
  26646. this._swctx.addHole(this._points.add(hole));
  26647. return this;
  26648. };
  26649. PolygonMeshBuilder.prototype.build = function (updatable) {
  26650. if (updatable === void 0) { updatable = false; }
  26651. var result = new BABYLON.Mesh(this._name, this._scene);
  26652. var normals = [];
  26653. var positions = [];
  26654. var uvs = [];
  26655. var bounds = this._points.computeBounds();
  26656. this._points.elements.forEach(function (p) {
  26657. normals.push(0, 1.0, 0);
  26658. positions.push(p.x, 0, p.y);
  26659. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  26660. });
  26661. var indices = [];
  26662. this._swctx.triangulate();
  26663. this._swctx.getTriangles().forEach(function (triangle) {
  26664. triangle.getPoints().forEach(function (point) {
  26665. indices.push(point.index);
  26666. });
  26667. });
  26668. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  26669. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  26670. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  26671. result.setIndices(indices);
  26672. return result;
  26673. };
  26674. return PolygonMeshBuilder;
  26675. })();
  26676. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  26677. })(BABYLON || (BABYLON = {}));
  26678. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  26679. (function (BABYLON) {
  26680. var SimplificationSettings = (function () {
  26681. function SimplificationSettings(quality, distance) {
  26682. this.quality = quality;
  26683. this.distance = distance;
  26684. }
  26685. return SimplificationSettings;
  26686. })();
  26687. BABYLON.SimplificationSettings = SimplificationSettings;
  26688. /**
  26689. * The implemented types of simplification.
  26690. * At the moment only Quadratic Error Decimation is implemented.
  26691. */
  26692. (function (SimplificationType) {
  26693. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  26694. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  26695. var SimplificationType = BABYLON.SimplificationType;
  26696. var DecimationTriangle = (function () {
  26697. function DecimationTriangle(vertices) {
  26698. this.vertices = vertices;
  26699. this.error = new Array(4);
  26700. this.deleted = false;
  26701. this.isDirty = false;
  26702. this.borderFactor = 0;
  26703. }
  26704. return DecimationTriangle;
  26705. })();
  26706. BABYLON.DecimationTriangle = DecimationTriangle;
  26707. var DecimationVertex = (function () {
  26708. function DecimationVertex(position, normal, uv, id) {
  26709. this.position = position;
  26710. this.normal = normal;
  26711. this.uv = uv;
  26712. this.id = id;
  26713. this.isBorder = true;
  26714. this.q = new QuadraticMatrix();
  26715. this.triangleCount = 0;
  26716. this.triangleStart = 0;
  26717. }
  26718. return DecimationVertex;
  26719. })();
  26720. BABYLON.DecimationVertex = DecimationVertex;
  26721. var QuadraticMatrix = (function () {
  26722. function QuadraticMatrix(data) {
  26723. this.data = new Array(10);
  26724. for (var i = 0; i < 10; ++i) {
  26725. if (data && data[i]) {
  26726. this.data[i] = data[i];
  26727. }
  26728. else {
  26729. this.data[i] = 0;
  26730. }
  26731. }
  26732. }
  26733. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  26734. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] + this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] - this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  26735. return det;
  26736. };
  26737. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  26738. for (var i = 0; i < 10; ++i) {
  26739. this.data[i] += matrix.data[i];
  26740. }
  26741. };
  26742. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  26743. for (var i = 0; i < 10; ++i) {
  26744. this.data[i] += data[i];
  26745. }
  26746. };
  26747. QuadraticMatrix.prototype.add = function (matrix) {
  26748. var m = new QuadraticMatrix();
  26749. for (var i = 0; i < 10; ++i) {
  26750. m.data[i] = this.data[i] + matrix.data[i];
  26751. }
  26752. return m;
  26753. };
  26754. QuadraticMatrix.FromData = function (a, b, c, d) {
  26755. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  26756. };
  26757. //returning an array to avoid garbage collection
  26758. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  26759. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  26760. };
  26761. return QuadraticMatrix;
  26762. })();
  26763. BABYLON.QuadraticMatrix = QuadraticMatrix;
  26764. var Reference = (function () {
  26765. function Reference(vertexId, triangleId) {
  26766. this.vertexId = vertexId;
  26767. this.triangleId = triangleId;
  26768. }
  26769. return Reference;
  26770. })();
  26771. BABYLON.Reference = Reference;
  26772. /**
  26773. * An implementation of the Quadratic Error simplification algorithm.
  26774. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  26775. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  26776. * @author RaananW
  26777. */
  26778. var QuadraticErrorSimplification = (function () {
  26779. function QuadraticErrorSimplification(_mesh) {
  26780. this._mesh = _mesh;
  26781. this.initialised = false;
  26782. this.syncIterations = 5000;
  26783. this.aggressiveness = 7;
  26784. this.decimationIterations = 100;
  26785. }
  26786. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  26787. var _this = this;
  26788. this.initWithMesh(this._mesh, function () {
  26789. _this.runDecimation(settings, successCallback);
  26790. });
  26791. };
  26792. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  26793. var _this = this;
  26794. var targetCount = ~~(this.triangles.length * settings.quality);
  26795. var deletedTriangles = 0;
  26796. var triangleCount = this.triangles.length;
  26797. var iterationFunction = function (iteration, callback) {
  26798. setTimeout(function () {
  26799. if (iteration % 5 === 0) {
  26800. _this.updateMesh(iteration === 0);
  26801. }
  26802. for (var i = 0; i < _this.triangles.length; ++i) {
  26803. _this.triangles[i].isDirty = false;
  26804. }
  26805. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  26806. var trianglesIterator = function (i) {
  26807. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  26808. var t = _this.triangles[tIdx];
  26809. if (!t)
  26810. return;
  26811. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  26812. return;
  26813. }
  26814. for (var j = 0; j < 3; ++j) {
  26815. if (t.error[j] < threshold) {
  26816. var deleted0 = [];
  26817. var deleted1 = [];
  26818. var i0 = t.vertices[j];
  26819. var i1 = t.vertices[(j + 1) % 3];
  26820. var v0 = _this.vertices[i0];
  26821. var v1 = _this.vertices[i1];
  26822. if (v0.isBorder !== v1.isBorder)
  26823. continue;
  26824. var p = BABYLON.Vector3.Zero();
  26825. var n = BABYLON.Vector3.Zero();
  26826. var uv = BABYLON.Vector2.Zero();
  26827. var color = new BABYLON.Color4(0, 0, 0, 1);
  26828. _this.calculateError(v0, v1, p, n, uv, color);
  26829. var delTr = [];
  26830. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  26831. continue;
  26832. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  26833. continue;
  26834. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  26835. continue;
  26836. }
  26837. v0.normal = n;
  26838. if (v0.uv)
  26839. v0.uv = uv;
  26840. else if (v0.color)
  26841. v0.color = color;
  26842. v0.q = v1.q.add(v0.q);
  26843. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  26844. continue;
  26845. if (p.equals(v0.position))
  26846. continue;
  26847. v0.position = p;
  26848. var tStart = _this.references.length;
  26849. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  26850. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  26851. var tCount = _this.references.length - tStart;
  26852. if (tCount <= v0.triangleCount) {
  26853. if (tCount) {
  26854. for (var c = 0; c < tCount; c++) {
  26855. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  26856. }
  26857. }
  26858. }
  26859. else {
  26860. v0.triangleStart = tStart;
  26861. }
  26862. v0.triangleCount = tCount;
  26863. break;
  26864. }
  26865. }
  26866. };
  26867. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  26868. return (triangleCount - deletedTriangles <= targetCount);
  26869. });
  26870. }, 0);
  26871. };
  26872. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  26873. if (triangleCount - deletedTriangles <= targetCount)
  26874. loop.breakLoop();
  26875. else {
  26876. iterationFunction(loop.index, function () {
  26877. loop.executeNext();
  26878. });
  26879. }
  26880. }, function () {
  26881. setTimeout(function () {
  26882. successCallback(_this.reconstructMesh());
  26883. }, 0);
  26884. });
  26885. };
  26886. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  26887. var _this = this;
  26888. if (!mesh)
  26889. return;
  26890. this.vertices = [];
  26891. this.triangles = [];
  26892. this._mesh = mesh;
  26893. //It is assumed that a mesh has positions, normals and either uvs or colors.
  26894. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26895. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26896. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26897. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26898. var indices = mesh.getIndices();
  26899. var vertexInit = function (i) {
  26900. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), null, i);
  26901. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26902. vertex.uv = BABYLON.Vector2.FromArray(uvs, i * 2);
  26903. }
  26904. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26905. vertex.color = BABYLON.Color4.FromArray(colorsData, i * 4);
  26906. }
  26907. _this.vertices.push(vertex);
  26908. };
  26909. var totalVertices = mesh.getTotalVertices();
  26910. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  26911. var indicesInit = function (i) {
  26912. var pos = i * 3;
  26913. var i0 = indices[pos + 0];
  26914. var i1 = indices[pos + 1];
  26915. var i2 = indices[pos + 2];
  26916. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  26917. _this.triangles.push(triangle);
  26918. };
  26919. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  26920. _this.init(callback);
  26921. });
  26922. });
  26923. };
  26924. QuadraticErrorSimplification.prototype.init = function (callback) {
  26925. var _this = this;
  26926. var triangleInit1 = function (i) {
  26927. var t = _this.triangles[i];
  26928. t.normal = BABYLON.Vector3.Cross(_this.vertices[t.vertices[1]].position.subtract(_this.vertices[t.vertices[0]].position), _this.vertices[t.vertices[2]].position.subtract(_this.vertices[t.vertices[0]].position)).normalize();
  26929. for (var j = 0; j < 3; j++) {
  26930. _this.vertices[t.vertices[j]].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, _this.vertices[t.vertices[0]].position))));
  26931. }
  26932. };
  26933. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  26934. var triangleInit2 = function (i) {
  26935. var t = _this.triangles[i];
  26936. for (var j = 0; j < 3; ++j) {
  26937. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  26938. }
  26939. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  26940. };
  26941. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  26942. _this.initialised = true;
  26943. callback();
  26944. });
  26945. });
  26946. };
  26947. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  26948. var newTriangles = [];
  26949. var i;
  26950. for (i = 0; i < this.vertices.length; ++i) {
  26951. this.vertices[i].triangleCount = 0;
  26952. }
  26953. var t;
  26954. var j;
  26955. for (i = 0; i < this.triangles.length; ++i) {
  26956. if (!this.triangles[i].deleted) {
  26957. t = this.triangles[i];
  26958. for (j = 0; j < 3; ++j) {
  26959. this.vertices[t.vertices[j]].triangleCount = 1;
  26960. }
  26961. newTriangles.push(t);
  26962. }
  26963. }
  26964. var newVerticesOrder = [];
  26965. //compact vertices, get the IDs of the vertices used.
  26966. var dst = 0;
  26967. for (i = 0; i < this.vertices.length; ++i) {
  26968. if (this.vertices[i].triangleCount) {
  26969. this.vertices[i].triangleStart = dst;
  26970. this.vertices[dst].position = this.vertices[i].position;
  26971. this.vertices[dst].normal = this.vertices[i].normal;
  26972. this.vertices[dst].uv = this.vertices[i].uv;
  26973. this.vertices[dst].color = this.vertices[i].color;
  26974. newVerticesOrder.push(i);
  26975. dst++;
  26976. }
  26977. }
  26978. for (i = 0; i < newTriangles.length; ++i) {
  26979. t = newTriangles[i];
  26980. for (j = 0; j < 3; ++j) {
  26981. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  26982. }
  26983. }
  26984. this.vertices = this.vertices.slice(0, dst);
  26985. var newPositionData = [];
  26986. var newNormalData = [];
  26987. var newUVsData = [];
  26988. var newColorsData = [];
  26989. for (i = 0; i < newVerticesOrder.length; ++i) {
  26990. newPositionData.push(this.vertices[i].position.x);
  26991. newPositionData.push(this.vertices[i].position.y);
  26992. newPositionData.push(this.vertices[i].position.z);
  26993. newNormalData.push(this.vertices[i].normal.x);
  26994. newNormalData.push(this.vertices[i].normal.y);
  26995. newNormalData.push(this.vertices[i].normal.z);
  26996. if (this.vertices[i].uv) {
  26997. newUVsData.push(this.vertices[i].uv.x);
  26998. newUVsData.push(this.vertices[i].uv.y);
  26999. }
  27000. else if (this.vertices[i].color) {
  27001. newColorsData.push(this.vertices[i].color.r);
  27002. newColorsData.push(this.vertices[i].color.g);
  27003. newColorsData.push(this.vertices[i].color.b);
  27004. newColorsData.push(this.vertices[i].color.a);
  27005. }
  27006. }
  27007. var newIndicesArray = [];
  27008. for (i = 0; i < newTriangles.length; ++i) {
  27009. newIndicesArray.push(newTriangles[i].vertices[0]);
  27010. newIndicesArray.push(newTriangles[i].vertices[1]);
  27011. newIndicesArray.push(newTriangles[i].vertices[2]);
  27012. }
  27013. //not cloning, to avoid geometry problems. Creating a whole new mesh.
  27014. var newMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  27015. newMesh.material = this._mesh.material;
  27016. newMesh.parent = this._mesh.parent;
  27017. newMesh.setIndices(newIndicesArray);
  27018. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  27019. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  27020. if (newUVsData.length > 0)
  27021. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  27022. if (newColorsData.length > 0)
  27023. newMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  27024. //preparing the skeleton support
  27025. if (this._mesh.skeleton) {
  27026. }
  27027. return newMesh;
  27028. };
  27029. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  27030. for (var i = 0; i < vertex1.triangleCount; ++i) {
  27031. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  27032. if (t.deleted)
  27033. continue;
  27034. var s = this.references[vertex1.triangleStart + i].vertexId;
  27035. var id1 = t.vertices[(s + 1) % 3];
  27036. var id2 = t.vertices[(s + 2) % 3];
  27037. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  27038. deletedArray[i] = true;
  27039. delTr.push(t);
  27040. continue;
  27041. }
  27042. var d1 = this.vertices[id1].position.subtract(point);
  27043. d1 = d1.normalize();
  27044. var d2 = this.vertices[id2].position.subtract(point);
  27045. d2 = d2.normalize();
  27046. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  27047. return true;
  27048. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  27049. deletedArray[i] = false;
  27050. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  27051. return true;
  27052. }
  27053. return false;
  27054. };
  27055. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  27056. var newDeleted = deletedTriangles;
  27057. for (var i = 0; i < vertex.triangleCount; ++i) {
  27058. var ref = this.references[vertex.triangleStart + i];
  27059. var t = this.triangles[ref.triangleId];
  27060. if (t.deleted)
  27061. continue;
  27062. if (deletedArray[i]) {
  27063. t.deleted = true;
  27064. newDeleted++;
  27065. continue;
  27066. }
  27067. t.vertices[ref.vertexId] = vertexId;
  27068. t.isDirty = true;
  27069. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  27070. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  27071. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  27072. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  27073. this.references.push(ref);
  27074. }
  27075. return newDeleted;
  27076. };
  27077. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  27078. for (var i = 0; i < this.vertices.length; ++i) {
  27079. var vCount = [];
  27080. var vId = [];
  27081. var v = this.vertices[i];
  27082. var j;
  27083. for (j = 0; j < v.triangleCount; ++j) {
  27084. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  27085. for (var ii = 0; ii < 3; ii++) {
  27086. var ofs = 0;
  27087. var id = triangle.vertices[ii];
  27088. while (ofs < vCount.length) {
  27089. if (vId[ofs] === id)
  27090. break;
  27091. ++ofs;
  27092. }
  27093. if (ofs === vCount.length) {
  27094. vCount.push(1);
  27095. vId.push(id);
  27096. }
  27097. else {
  27098. vCount[ofs]++;
  27099. }
  27100. }
  27101. }
  27102. for (j = 0; j < vCount.length; ++j) {
  27103. if (vCount[j] === 1) {
  27104. this.vertices[vId[j]].isBorder = true;
  27105. }
  27106. else {
  27107. this.vertices[vId[j]].isBorder = false;
  27108. }
  27109. }
  27110. }
  27111. };
  27112. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  27113. if (identifyBorders === void 0) { identifyBorders = false; }
  27114. var i;
  27115. if (!identifyBorders) {
  27116. var newTrianglesVector = [];
  27117. for (i = 0; i < this.triangles.length; ++i) {
  27118. if (!this.triangles[i].deleted) {
  27119. newTrianglesVector.push(this.triangles[i]);
  27120. }
  27121. }
  27122. this.triangles = newTrianglesVector;
  27123. }
  27124. for (i = 0; i < this.vertices.length; ++i) {
  27125. this.vertices[i].triangleCount = 0;
  27126. this.vertices[i].triangleStart = 0;
  27127. }
  27128. var t;
  27129. var j;
  27130. var v;
  27131. for (i = 0; i < this.triangles.length; ++i) {
  27132. t = this.triangles[i];
  27133. for (j = 0; j < 3; ++j) {
  27134. v = this.vertices[t.vertices[j]];
  27135. v.triangleCount++;
  27136. }
  27137. }
  27138. var tStart = 0;
  27139. for (i = 0; i < this.vertices.length; ++i) {
  27140. this.vertices[i].triangleStart = tStart;
  27141. tStart += this.vertices[i].triangleCount;
  27142. this.vertices[i].triangleCount = 0;
  27143. }
  27144. var newReferences = new Array(this.triangles.length * 3);
  27145. for (i = 0; i < this.triangles.length; ++i) {
  27146. t = this.triangles[i];
  27147. for (j = 0; j < 3; ++j) {
  27148. v = this.vertices[t.vertices[j]];
  27149. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  27150. v.triangleCount++;
  27151. }
  27152. }
  27153. this.references = newReferences;
  27154. if (identifyBorders) {
  27155. this.identifyBorder();
  27156. }
  27157. };
  27158. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  27159. var x = point.x;
  27160. var y = point.y;
  27161. var z = point.z;
  27162. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  27163. };
  27164. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  27165. var q = vertex1.q.add(vertex2.q);
  27166. var border = vertex1.isBorder && vertex2.isBorder;
  27167. var error = 0;
  27168. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  27169. if (qDet !== 0 && !border) {
  27170. if (!pointResult) {
  27171. pointResult = BABYLON.Vector3.Zero();
  27172. }
  27173. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  27174. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  27175. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  27176. error = this.vertexError(q, pointResult);
  27177. //TODO this should be correctly calculated
  27178. if (normalResult) {
  27179. normalResult.copyFrom(vertex1.normal);
  27180. if (vertex1.uv)
  27181. uvResult.copyFrom(vertex1.uv);
  27182. else if (vertex1.color)
  27183. colorResult.copyFrom(vertex1.color);
  27184. }
  27185. }
  27186. else {
  27187. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  27188. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  27189. var error1 = this.vertexError(q, vertex1.position);
  27190. var error2 = this.vertexError(q, vertex2.position);
  27191. var error3 = this.vertexError(q, p3);
  27192. error = Math.min(error1, error2, error3);
  27193. if (error === error1) {
  27194. if (pointResult) {
  27195. pointResult.copyFrom(vertex1.position);
  27196. normalResult.copyFrom(vertex1.normal);
  27197. if (vertex1.uv)
  27198. uvResult.copyFrom(vertex1.uv);
  27199. else if (vertex1.color)
  27200. colorResult.copyFrom(vertex1.color);
  27201. }
  27202. }
  27203. else if (error === error2) {
  27204. if (pointResult) {
  27205. pointResult.copyFrom(vertex2.position);
  27206. normalResult.copyFrom(vertex2.normal);
  27207. if (vertex2.uv)
  27208. uvResult.copyFrom(vertex2.uv);
  27209. else if (vertex2.color)
  27210. colorResult.copyFrom(vertex2.color);
  27211. }
  27212. }
  27213. else {
  27214. if (pointResult) {
  27215. pointResult.copyFrom(p3);
  27216. normalResult.copyFrom(vertex1.normal);
  27217. if (vertex1.uv)
  27218. uvResult.copyFrom(vertex1.uv);
  27219. else if (vertex1.color)
  27220. colorResult.copyFrom(vertex1.color);
  27221. }
  27222. }
  27223. }
  27224. return error;
  27225. };
  27226. return QuadraticErrorSimplification;
  27227. })();
  27228. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  27229. })(BABYLON || (BABYLON = {}));
  27230. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  27231. (function (BABYLON) {
  27232. var Analyser = (function () {
  27233. function Analyser(scene) {
  27234. this.SMOOTHING = 0.75;
  27235. this.FFT_SIZE = 512;
  27236. this.BARGRAPHAMPLITUDE = 256;
  27237. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  27238. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  27239. this._scene = scene;
  27240. this._audioEngine = BABYLON.Engine.audioEngine;
  27241. if (this._audioEngine.canUseWebAudio) {
  27242. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  27243. this._webAudioAnalyser.minDecibels = -140;
  27244. this._webAudioAnalyser.maxDecibels = 0;
  27245. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27246. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27247. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  27248. }
  27249. }
  27250. Analyser.prototype.getFrequencyBinCount = function () {
  27251. if (this._audioEngine.canUseWebAudio) {
  27252. return this._webAudioAnalyser.frequencyBinCount;
  27253. }
  27254. else {
  27255. return 0;
  27256. }
  27257. };
  27258. Analyser.prototype.getByteFrequencyData = function () {
  27259. if (this._audioEngine.canUseWebAudio) {
  27260. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27261. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27262. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  27263. }
  27264. return this._byteFreqs;
  27265. };
  27266. Analyser.prototype.getByteTimeDomainData = function () {
  27267. if (this._audioEngine.canUseWebAudio) {
  27268. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27269. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27270. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  27271. }
  27272. return this._byteTime;
  27273. };
  27274. Analyser.prototype.getFloatFrequencyData = function () {
  27275. if (this._audioEngine.canUseWebAudio) {
  27276. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27277. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27278. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  27279. }
  27280. return this._floatFreqs;
  27281. };
  27282. Analyser.prototype.drawDebugCanvas = function () {
  27283. var _this = this;
  27284. if (this._audioEngine.canUseWebAudio) {
  27285. if (!this._debugCanvas) {
  27286. this._debugCanvas = document.createElement("canvas");
  27287. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  27288. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  27289. this._debugCanvas.style.position = "absolute";
  27290. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  27291. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  27292. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  27293. document.body.appendChild(this._debugCanvas);
  27294. this._registerFunc = function () {
  27295. _this.drawDebugCanvas();
  27296. };
  27297. this._scene.registerBeforeRender(this._registerFunc);
  27298. }
  27299. if (this._registerFunc) {
  27300. var workingArray = this.getByteFrequencyData();
  27301. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  27302. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  27303. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  27304. var value = workingArray[i];
  27305. var percent = value / this.BARGRAPHAMPLITUDE;
  27306. var height = this.DEBUGCANVASSIZE.height * percent;
  27307. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  27308. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  27309. var hue = i / this.getFrequencyBinCount() * 360;
  27310. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  27311. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  27312. }
  27313. }
  27314. }
  27315. };
  27316. Analyser.prototype.stopDebugCanvas = function () {
  27317. if (this._debugCanvas) {
  27318. this._scene.unregisterBeforeRender(this._registerFunc);
  27319. this._registerFunc = null;
  27320. document.body.removeChild(this._debugCanvas);
  27321. this._debugCanvas = null;
  27322. this._debugCanvasContext = null;
  27323. }
  27324. };
  27325. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  27326. if (this._audioEngine.canUseWebAudio) {
  27327. inputAudioNode.connect(this._webAudioAnalyser);
  27328. this._webAudioAnalyser.connect(outputAudioNode);
  27329. }
  27330. };
  27331. Analyser.prototype.dispose = function () {
  27332. if (this._audioEngine.canUseWebAudio) {
  27333. this._webAudioAnalyser.disconnect();
  27334. }
  27335. };
  27336. return Analyser;
  27337. })();
  27338. BABYLON.Analyser = Analyser;
  27339. })(BABYLON || (BABYLON = {}));
  27340. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  27341. (function (BABYLON) {
  27342. var DepthRenderer = (function () {
  27343. function DepthRenderer(scene, type) {
  27344. var _this = this;
  27345. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  27346. this._viewMatrix = BABYLON.Matrix.Zero();
  27347. this._projectionMatrix = BABYLON.Matrix.Zero();
  27348. this._transformMatrix = BABYLON.Matrix.Zero();
  27349. this._worldViewProjection = BABYLON.Matrix.Zero();
  27350. this._scene = scene;
  27351. var engine = scene.getEngine();
  27352. // Render target
  27353. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  27354. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27355. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27356. this._depthMap.refreshRate = 1;
  27357. this._depthMap.renderParticles = false;
  27358. this._depthMap.renderList = null;
  27359. // Custom render function
  27360. var renderSubMesh = function (subMesh) {
  27361. var mesh = subMesh.getRenderingMesh();
  27362. var scene = _this._scene;
  27363. var engine = scene.getEngine();
  27364. // Culling
  27365. engine.setState(subMesh.getMaterial().backFaceCulling);
  27366. // Managing instances
  27367. var batch = mesh._getInstancesRenderList(subMesh._id);
  27368. if (batch.mustReturn) {
  27369. return;
  27370. }
  27371. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  27372. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  27373. engine.enableEffect(_this._effect);
  27374. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  27375. var material = subMesh.getMaterial();
  27376. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27377. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  27378. // Alpha test
  27379. if (material && material.needAlphaTesting()) {
  27380. var alphaTexture = material.getAlphaTestTexture();
  27381. _this._effect.setTexture("diffuseSampler", alphaTexture);
  27382. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27383. }
  27384. // Bones
  27385. if (mesh.useBones) {
  27386. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27387. }
  27388. // Draw
  27389. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  27390. }
  27391. };
  27392. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  27393. var index;
  27394. for (index = 0; index < opaqueSubMeshes.length; index++) {
  27395. renderSubMesh(opaqueSubMeshes.data[index]);
  27396. }
  27397. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  27398. renderSubMesh(alphaTestSubMeshes.data[index]);
  27399. }
  27400. };
  27401. }
  27402. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  27403. var defines = [];
  27404. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27405. var mesh = subMesh.getMesh();
  27406. var scene = mesh.getScene();
  27407. var material = subMesh.getMaterial();
  27408. // Alpha test
  27409. if (material && material.needAlphaTesting()) {
  27410. defines.push("#define ALPHATEST");
  27411. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27412. attribs.push(BABYLON.VertexBuffer.UVKind);
  27413. defines.push("#define UV1");
  27414. }
  27415. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27416. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27417. defines.push("#define UV2");
  27418. }
  27419. }
  27420. // Bones
  27421. if (mesh.useBones) {
  27422. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27423. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27424. defines.push("#define BONES");
  27425. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27426. }
  27427. // Instances
  27428. if (useInstances) {
  27429. defines.push("#define INSTANCES");
  27430. attribs.push("world0");
  27431. attribs.push("world1");
  27432. attribs.push("world2");
  27433. attribs.push("world3");
  27434. }
  27435. // Get correct effect
  27436. var join = defines.join("\n");
  27437. if (this._cachedDefines !== join) {
  27438. this._cachedDefines = join;
  27439. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  27440. }
  27441. return this._effect.isReady();
  27442. };
  27443. DepthRenderer.prototype.getDepthMap = function () {
  27444. return this._depthMap;
  27445. };
  27446. // Methods
  27447. DepthRenderer.prototype.dispose = function () {
  27448. this._depthMap.dispose();
  27449. };
  27450. return DepthRenderer;
  27451. })();
  27452. BABYLON.DepthRenderer = DepthRenderer;
  27453. })(BABYLON || (BABYLON = {}));
  27454. //# sourceMappingURL=babylon.depthRenderer.js.map
  27455. var BABYLON;
  27456. (function (BABYLON) {
  27457. var SSAORenderingPipeline = (function (_super) {
  27458. __extends(SSAORenderingPipeline, _super);
  27459. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  27460. var _this = this;
  27461. if (ratio === void 0) { ratio = 1.0; }
  27462. _super.call(this, scene.getEngine(), name);
  27463. // Members
  27464. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  27465. this.SSAORenderEffect = "SSAORenderEffect";
  27466. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  27467. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  27468. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  27469. this._firstUpdate = true;
  27470. this._scene = scene;
  27471. // Set up assets
  27472. this._createRandomTexture();
  27473. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  27474. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27475. this._createSSAOPostProcess(ratio);
  27476. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27477. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27478. this._createSSAOCombinePostProcess();
  27479. // Set up pipeline
  27480. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  27481. return _this._originalColorPostProcess;
  27482. }, true));
  27483. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  27484. return _this._ssaoPostProcess;
  27485. }, true));
  27486. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  27487. return _this._blurHPostProcess;
  27488. }, true));
  27489. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  27490. return _this._blurVPostProcess;
  27491. }, true));
  27492. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  27493. return _this._ssaoCombinePostProcess;
  27494. }, true));
  27495. // Finish
  27496. scene.postProcessRenderPipelineManager.addPipeline(this);
  27497. if (cameras)
  27498. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  27499. }
  27500. // Public Methods
  27501. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  27502. return this._blurHPostProcess;
  27503. };
  27504. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  27505. return this._blurVPostProcess;
  27506. };
  27507. SSAORenderingPipeline.prototype.dispose = function (cameras) {
  27508. if (cameras !== undefined)
  27509. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, cameras);
  27510. this._originalColorPostProcess = undefined;
  27511. this._ssaoPostProcess = undefined;
  27512. this._blurHPostProcess = undefined;
  27513. this._blurVPostProcess = undefined;
  27514. this._ssaoCombinePostProcess = undefined;
  27515. this._randomTexture.dispose();
  27516. };
  27517. // Private Methods
  27518. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  27519. var _this = this;
  27520. var sampleSphere = [
  27521. 0.5381,
  27522. 0.1856,
  27523. -0.4319,
  27524. 0.1379,
  27525. 0.2486,
  27526. 0.4430,
  27527. 0.3371,
  27528. 0.5679,
  27529. -0.0057,
  27530. -0.6999,
  27531. -0.0451,
  27532. -0.0019,
  27533. 0.0689,
  27534. -0.1598,
  27535. -0.8547,
  27536. 0.0560,
  27537. 0.0069,
  27538. -0.1843,
  27539. -0.0146,
  27540. 0.1402,
  27541. 0.0762,
  27542. 0.0100,
  27543. -0.1924,
  27544. -0.0344,
  27545. -0.3577,
  27546. -0.5301,
  27547. -0.4358,
  27548. -0.3169,
  27549. 0.1063,
  27550. 0.0158,
  27551. 0.0103,
  27552. -0.5869,
  27553. 0.0046,
  27554. -0.0897,
  27555. -0.4940,
  27556. 0.3287,
  27557. 0.7119,
  27558. -0.0154,
  27559. -0.0918,
  27560. -0.0533,
  27561. 0.0596,
  27562. -0.5411,
  27563. 0.0352,
  27564. -0.0631,
  27565. 0.5460,
  27566. -0.4776,
  27567. 0.2847,
  27568. -0.0271
  27569. ];
  27570. var samplesFactor = 1.0 / 16.0;
  27571. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  27572. this._ssaoPostProcess.onApply = function (effect) {
  27573. if (_this._firstUpdate) {
  27574. effect.setArray3("sampleSphere", sampleSphere);
  27575. effect.setFloat("samplesFactor", samplesFactor);
  27576. effect.setFloat("randTextureTiles", 4.0 / ratio);
  27577. _this._firstUpdate = false;
  27578. }
  27579. effect.setTexture("textureSampler", _this._depthTexture);
  27580. effect.setTexture("randomSampler", _this._randomTexture);
  27581. };
  27582. };
  27583. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function () {
  27584. var _this = this;
  27585. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  27586. this._ssaoCombinePostProcess.onApply = function (effect) {
  27587. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  27588. };
  27589. };
  27590. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  27591. var size = 512;
  27592. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  27593. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  27594. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  27595. var context = this._randomTexture.getContext();
  27596. var rand = function (min, max) {
  27597. return Math.random() * (max - min) + min;
  27598. };
  27599. for (var x = 0; x < size; x++) {
  27600. for (var y = 0; y < size; y++) {
  27601. var randVector = BABYLON.Vector3.Zero();
  27602. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  27603. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  27604. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  27605. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  27606. context.fillRect(x, y, 1, 1);
  27607. }
  27608. }
  27609. this._randomTexture.update(false);
  27610. };
  27611. return SSAORenderingPipeline;
  27612. })(BABYLON.PostProcessRenderPipeline);
  27613. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  27614. })(BABYLON || (BABYLON = {}));
  27615. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  27616. var BABYLON;
  27617. (function (BABYLON) {
  27618. var GodRaysPostProcess = (function (_super) {
  27619. __extends(GodRaysPostProcess, _super);
  27620. function GodRaysPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27621. var _this = this;
  27622. _super.call(this, name, "volumetricLightScattering", ["lightPositionOnScreen"], ["lightScatteringSampler"], ratio, camera, samplingMode, engine, reusable);
  27623. this._screenCoordinates = BABYLON.Vector2.Zero();
  27624. this.invert = true;
  27625. var scene = camera.getScene();
  27626. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  27627. // Create billboard
  27628. this.mesh = BABYLON.Mesh.CreatePlane("VolumetricLightScatteringMesh", 2, scene);
  27629. this.mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  27630. this.mesh.material = new BABYLON.StandardMaterial('VolumetricLightScatteringMaterial', scene);
  27631. // Configure
  27632. this._createPass(scene);
  27633. this.onApply = function (effect) {
  27634. _this._updateScreenCoordinates(scene);
  27635. effect.setTexture("lightScatteringSampler", _this._godRaysRTT);
  27636. effect.setVector2("lightPositionOnScreen", _this._screenCoordinates);
  27637. };
  27638. }
  27639. GodRaysPostProcess.prototype.isReady = function (subMesh, useInstances) {
  27640. var mesh = subMesh.getMesh();
  27641. var scene = mesh.getScene();
  27642. var defines = [];
  27643. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27644. var material = subMesh.getMaterial();
  27645. // Render this.mesh as default
  27646. if (mesh === this.mesh)
  27647. defines.push("#define BASIC_RENDER");
  27648. // Alpha test
  27649. if (material) {
  27650. if (material.needAlphaTesting() || mesh === this.mesh)
  27651. defines.push("#define ALPHATEST");
  27652. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27653. attribs.push(BABYLON.VertexBuffer.UVKind);
  27654. defines.push("#define UV1");
  27655. }
  27656. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27657. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27658. defines.push("#define UV2");
  27659. }
  27660. }
  27661. // Bones
  27662. if (mesh.useBones) {
  27663. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27664. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27665. defines.push("#define BONES");
  27666. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27667. }
  27668. // Instances
  27669. if (useInstances) {
  27670. defines.push("#define INSTANCES");
  27671. attribs.push("world0");
  27672. attribs.push("world1");
  27673. attribs.push("world2");
  27674. attribs.push("world3");
  27675. }
  27676. // Get correct effect
  27677. var join = defines.join("\n");
  27678. if (this._cachedDefines !== join) {
  27679. this._cachedDefines = join;
  27680. this._godRaysPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  27681. }
  27682. return this._godRaysPass.isReady();
  27683. };
  27684. GodRaysPostProcess.prototype.dispose = function (camera) {
  27685. this._godRaysRTT.dispose();
  27686. _super.prototype.dispose.call(this, camera);
  27687. };
  27688. GodRaysPostProcess.prototype.getPass = function () {
  27689. return this._godRaysRTT;
  27690. };
  27691. // Private methods
  27692. GodRaysPostProcess.prototype._createPass = function (scene) {
  27693. var _this = this;
  27694. var engine = scene.getEngine();
  27695. this._godRaysRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  27696. this._godRaysRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27697. this._godRaysRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27698. this._godRaysRTT.renderList = null;
  27699. this._godRaysRTT.renderParticles = false;
  27700. scene.customRenderTargets.push(this._godRaysRTT);
  27701. // Custom render function for submeshes
  27702. var renderSubMesh = function (subMesh) {
  27703. var mesh = subMesh.getRenderingMesh();
  27704. var scene = mesh.getScene();
  27705. var engine = scene.getEngine();
  27706. // Culling
  27707. engine.setState(subMesh.getMaterial().backFaceCulling);
  27708. // Managing instances
  27709. var batch = mesh._getInstancesRenderList(subMesh._id);
  27710. if (batch.mustReturn) {
  27711. return;
  27712. }
  27713. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  27714. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  27715. engine.enableEffect(_this._godRaysPass);
  27716. mesh._bind(subMesh, _this._godRaysPass, BABYLON.Material.TriangleFillMode);
  27717. var material = subMesh.getMaterial();
  27718. _this._godRaysPass.setMatrix("viewProjection", scene.getTransformMatrix());
  27719. // Alpha test
  27720. if (material && (mesh === _this.mesh || material.needAlphaTesting())) {
  27721. var alphaTexture = material.getAlphaTestTexture();
  27722. _this._godRaysPass.setTexture("diffuseSampler", alphaTexture);
  27723. _this._godRaysPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27724. }
  27725. // Bones
  27726. if (mesh.useBones) {
  27727. _this._godRaysPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27728. }
  27729. // Draw
  27730. mesh._processRendering(subMesh, _this._godRaysPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._godRaysPass.setMatrix("world", world); });
  27731. }
  27732. };
  27733. // Render target texture callbacks
  27734. var savedSceneClearColor;
  27735. var sceneClearColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  27736. this._godRaysRTT.onBeforeRender = function () {
  27737. savedSceneClearColor = scene.clearColor;
  27738. scene.clearColor = sceneClearColor;
  27739. };
  27740. this._godRaysRTT.onAfterRender = function () {
  27741. scene.clearColor = savedSceneClearColor;
  27742. };
  27743. this._godRaysRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  27744. var index;
  27745. for (index = 0; index < opaqueSubMeshes.length; index++) {
  27746. renderSubMesh(opaqueSubMeshes.data[index]);
  27747. }
  27748. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  27749. renderSubMesh(alphaTestSubMeshes.data[index]);
  27750. }
  27751. };
  27752. };
  27753. GodRaysPostProcess.prototype._updateScreenCoordinates = function (scene) {
  27754. var transform = scene.getTransformMatrix();
  27755. var pos = BABYLON.Vector3.Project(this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  27756. this._screenCoordinates.x = pos.x / this._viewPort.width;
  27757. this._screenCoordinates.y = pos.y / this._viewPort.height;
  27758. if (this.invert)
  27759. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  27760. };
  27761. return GodRaysPostProcess;
  27762. })(BABYLON.PostProcess);
  27763. BABYLON.GodRaysPostProcess = GodRaysPostProcess;
  27764. })(BABYLON || (BABYLON = {}));
  27765. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map